context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using Infoplus.Client; using Infoplus.Model; namespace Infoplus.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IUserApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Get an user by id /// </summary> /// <remarks> /// Returns the user identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="userId">Id of user to be returned.</param> /// <returns>User</returns> User GetUserById (string userId); /// <summary> /// Get an user by id /// </summary> /// <remarks> /// Returns the user identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="userId">Id of user to be returned.</param> /// <returns>ApiResponse of User</returns> ApiResponse<User> GetUserByIdWithHttpInfo (string userId); /// <summary> /// Search users /// </summary> /// <remarks> /// Returns the list of users that match the given searchText. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>List&lt;User&gt;</returns> List<User> GetUserBySearchText (string searchText = null, int? page = null, int? limit = null); /// <summary> /// Search users /// </summary> /// <remarks> /// Returns the list of users that match the given searchText. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>ApiResponse of List&lt;User&gt;</returns> ApiResponse<List<User>> GetUserBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Get an user by id /// </summary> /// <remarks> /// Returns the user identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="userId">Id of user to be returned.</param> /// <returns>Task of User</returns> System.Threading.Tasks.Task<User> GetUserByIdAsync (string userId); /// <summary> /// Get an user by id /// </summary> /// <remarks> /// Returns the user identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="userId">Id of user to be returned.</param> /// <returns>Task of ApiResponse (User)</returns> System.Threading.Tasks.Task<ApiResponse<User>> GetUserByIdAsyncWithHttpInfo (string userId); /// <summary> /// Search users /// </summary> /// <remarks> /// Returns the list of users that match the given searchText. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>Task of List&lt;User&gt;</returns> System.Threading.Tasks.Task<List<User>> GetUserBySearchTextAsync (string searchText = null, int? page = null, int? limit = null); /// <summary> /// Search users /// </summary> /// <remarks> /// Returns the list of users that match the given searchText. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>Task of ApiResponse (List&lt;User&gt;)</returns> System.Threading.Tasks.Task<ApiResponse<List<User>>> GetUserBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class UserApi : IUserApi { private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="UserApi"/> class. /// </summary> /// <returns></returns> public UserApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="UserApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public UserApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public Infoplus.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Get an user by id Returns the user identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="userId">Id of user to be returned.</param> /// <returns>User</returns> public User GetUserById (string userId) { ApiResponse<User> localVarResponse = GetUserByIdWithHttpInfo(userId); return localVarResponse.Data; } /// <summary> /// Get an user by id Returns the user identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="userId">Id of user to be returned.</param> /// <returns>ApiResponse of User</returns> public ApiResponse< User > GetUserByIdWithHttpInfo (string userId) { // verify the required parameter 'userId' is set if (userId == null) throw new ApiException(400, "Missing required parameter 'userId' when calling UserApi->GetUserById"); var localVarPath = "/v1.0/user/{userId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (userId != null) localVarPathParams.Add("userId", Configuration.ApiClient.ParameterToString(userId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetUserById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<User>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (User) Configuration.ApiClient.Deserialize(localVarResponse, typeof(User))); } /// <summary> /// Get an user by id Returns the user identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="userId">Id of user to be returned.</param> /// <returns>Task of User</returns> public async System.Threading.Tasks.Task<User> GetUserByIdAsync (string userId) { ApiResponse<User> localVarResponse = await GetUserByIdAsyncWithHttpInfo(userId); return localVarResponse.Data; } /// <summary> /// Get an user by id Returns the user identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="userId">Id of user to be returned.</param> /// <returns>Task of ApiResponse (User)</returns> public async System.Threading.Tasks.Task<ApiResponse<User>> GetUserByIdAsyncWithHttpInfo (string userId) { // verify the required parameter 'userId' is set if (userId == null) throw new ApiException(400, "Missing required parameter 'userId' when calling UserApi->GetUserById"); var localVarPath = "/v1.0/user/{userId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (userId != null) localVarPathParams.Add("userId", Configuration.ApiClient.ParameterToString(userId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetUserById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<User>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (User) Configuration.ApiClient.Deserialize(localVarResponse, typeof(User))); } /// <summary> /// Search users Returns the list of users that match the given searchText. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>List&lt;User&gt;</returns> public List<User> GetUserBySearchText (string searchText = null, int? page = null, int? limit = null) { ApiResponse<List<User>> localVarResponse = GetUserBySearchTextWithHttpInfo(searchText, page, limit); return localVarResponse.Data; } /// <summary> /// Search users Returns the list of users that match the given searchText. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>ApiResponse of List&lt;User&gt;</returns> public ApiResponse< List<User> > GetUserBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null) { var localVarPath = "/v1.0/user/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetUserBySearchText", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<User>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<User>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<User>))); } /// <summary> /// Search users Returns the list of users that match the given searchText. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>Task of List&lt;User&gt;</returns> public async System.Threading.Tasks.Task<List<User>> GetUserBySearchTextAsync (string searchText = null, int? page = null, int? limit = null) { ApiResponse<List<User>> localVarResponse = await GetUserBySearchTextAsyncWithHttpInfo(searchText, page, limit); return localVarResponse.Data; } /// <summary> /// Search users Returns the list of users that match the given searchText. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>Task of ApiResponse (List&lt;User&gt;)</returns> public async System.Threading.Tasks.Task<ApiResponse<List<User>>> GetUserBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null) { var localVarPath = "/v1.0/user/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetUserBySearchText", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<User>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<User>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<User>))); } } }
/* * Location Intelligence APIs * * Incorporate our extensive geodata into everyday applications, business processes and workflows. * * OpenAPI spec version: 8.5.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace pb.locationIntelligence.Model { /// <summary> /// Risk /// </summary> [DataContract] public partial class Risk : IEquatable<Risk> { /// <summary> /// Initializes a new instance of the <see cref="Risk" /> class. /// </summary> /// <param name="Type">Type.</param> /// <param name="Description">Description.</param> /// <param name="Risk50Rating">Risk50Rating.</param> /// <param name="Frequency">Frequency.</param> /// <param name="Nonburn">Nonburn.</param> /// <param name="PastFires">PastFires.</param> /// <param name="Severity">Severity.</param> /// <param name="Continuity">Continuity.</param> /// <param name="Adjustment">Adjustment.</param> /// <param name="Aspect">Aspect.</param> /// <param name="CrownFire">CrownFire.</param> /// <param name="Vegetation">Vegetation.</param> /// <param name="Foehn">Foehn.</param> /// <param name="GolfCourse">GolfCourse.</param> /// <param name="RoadDist">RoadDist.</param> /// <param name="Slope">Slope.</param> /// <param name="WaterDist">WaterDist.</param> /// <param name="Tier">Tier.</param> /// <param name="TierDescription">TierDescription.</param> /// <param name="DistanceToFireStation">DistanceToFireStation.</param> public Risk(string Type = null, string Description = null, int? Risk50Rating = null, int? Frequency = null, string Nonburn = null, int? PastFires = null, int? Severity = null, string Continuity = null, string Adjustment = null, string Aspect = null, string CrownFire = null, string Vegetation = null, string Foehn = null, string GolfCourse = null, string RoadDist = null, string Slope = null, string WaterDist = null, string Tier = null, string TierDescription = null, int? DistanceToFireStation = null) { this.Type = Type; this.Description = Description; this.Risk50Rating = Risk50Rating; this.Frequency = Frequency; this.Nonburn = Nonburn; this.PastFires = PastFires; this.Severity = Severity; this.Continuity = Continuity; this.Adjustment = Adjustment; this.Aspect = Aspect; this.CrownFire = CrownFire; this.Vegetation = Vegetation; this.Foehn = Foehn; this.GolfCourse = GolfCourse; this.RoadDist = RoadDist; this.Slope = Slope; this.WaterDist = WaterDist; this.Tier = Tier; this.TierDescription = TierDescription; this.DistanceToFireStation = DistanceToFireStation; } /// <summary> /// Gets or Sets Type /// </summary> [DataMember(Name="type", EmitDefaultValue=false)] public string Type { get; set; } /// <summary> /// Gets or Sets Description /// </summary> [DataMember(Name="description", EmitDefaultValue=false)] public string Description { get; set; } /// <summary> /// Gets or Sets Risk50Rating /// </summary> [DataMember(Name="risk50Rating", EmitDefaultValue=false)] public int? Risk50Rating { get; set; } /// <summary> /// Gets or Sets Frequency /// </summary> [DataMember(Name="frequency", EmitDefaultValue=false)] public int? Frequency { get; set; } /// <summary> /// Gets or Sets Nonburn /// </summary> [DataMember(Name="nonburn", EmitDefaultValue=false)] public string Nonburn { get; set; } /// <summary> /// Gets or Sets PastFires /// </summary> [DataMember(Name="pastFires", EmitDefaultValue=false)] public int? PastFires { get; set; } /// <summary> /// Gets or Sets Severity /// </summary> [DataMember(Name="severity", EmitDefaultValue=false)] public int? Severity { get; set; } /// <summary> /// Gets or Sets Continuity /// </summary> [DataMember(Name="continuity", EmitDefaultValue=false)] public string Continuity { get; set; } /// <summary> /// Gets or Sets Adjustment /// </summary> [DataMember(Name="adjustment", EmitDefaultValue=false)] public string Adjustment { get; set; } /// <summary> /// Gets or Sets Aspect /// </summary> [DataMember(Name="aspect", EmitDefaultValue=false)] public string Aspect { get; set; } /// <summary> /// Gets or Sets CrownFire /// </summary> [DataMember(Name="crownFire", EmitDefaultValue=false)] public string CrownFire { get; set; } /// <summary> /// Gets or Sets Vegetation /// </summary> [DataMember(Name="vegetation", EmitDefaultValue=false)] public string Vegetation { get; set; } /// <summary> /// Gets or Sets Foehn /// </summary> [DataMember(Name="foehn", EmitDefaultValue=false)] public string Foehn { get; set; } /// <summary> /// Gets or Sets GolfCourse /// </summary> [DataMember(Name="golfCourse", EmitDefaultValue=false)] public string GolfCourse { get; set; } /// <summary> /// Gets or Sets RoadDist /// </summary> [DataMember(Name="roadDist", EmitDefaultValue=false)] public string RoadDist { get; set; } /// <summary> /// Gets or Sets Slope /// </summary> [DataMember(Name="slope", EmitDefaultValue=false)] public string Slope { get; set; } /// <summary> /// Gets or Sets WaterDist /// </summary> [DataMember(Name="waterDist", EmitDefaultValue=false)] public string WaterDist { get; set; } /// <summary> /// Gets or Sets Tier /// </summary> [DataMember(Name="tier", EmitDefaultValue=false)] public string Tier { get; set; } /// <summary> /// Gets or Sets TierDescription /// </summary> [DataMember(Name="tierDescription", EmitDefaultValue=false)] public string TierDescription { get; set; } /// <summary> /// Gets or Sets DistanceToFireStation /// </summary> [DataMember(Name="distanceToFireStation", EmitDefaultValue=false)] public int? DistanceToFireStation { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Risk {\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" Description: ").Append(Description).Append("\n"); sb.Append(" Risk50Rating: ").Append(Risk50Rating).Append("\n"); sb.Append(" Frequency: ").Append(Frequency).Append("\n"); sb.Append(" Nonburn: ").Append(Nonburn).Append("\n"); sb.Append(" PastFires: ").Append(PastFires).Append("\n"); sb.Append(" Severity: ").Append(Severity).Append("\n"); sb.Append(" Continuity: ").Append(Continuity).Append("\n"); sb.Append(" Adjustment: ").Append(Adjustment).Append("\n"); sb.Append(" Aspect: ").Append(Aspect).Append("\n"); sb.Append(" CrownFire: ").Append(CrownFire).Append("\n"); sb.Append(" Vegetation: ").Append(Vegetation).Append("\n"); sb.Append(" Foehn: ").Append(Foehn).Append("\n"); sb.Append(" GolfCourse: ").Append(GolfCourse).Append("\n"); sb.Append(" RoadDist: ").Append(RoadDist).Append("\n"); sb.Append(" Slope: ").Append(Slope).Append("\n"); sb.Append(" WaterDist: ").Append(WaterDist).Append("\n"); sb.Append(" Tier: ").Append(Tier).Append("\n"); sb.Append(" TierDescription: ").Append(TierDescription).Append("\n"); sb.Append(" DistanceToFireStation: ").Append(DistanceToFireStation).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as Risk); } /// <summary> /// Returns true if Risk instances are equal /// </summary> /// <param name="other">Instance of Risk to be compared</param> /// <returns>Boolean</returns> public bool Equals(Risk other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Type == other.Type || this.Type != null && this.Type.Equals(other.Type) ) && ( this.Description == other.Description || this.Description != null && this.Description.Equals(other.Description) ) && ( this.Risk50Rating == other.Risk50Rating || this.Risk50Rating != null && this.Risk50Rating.Equals(other.Risk50Rating) ) && ( this.Frequency == other.Frequency || this.Frequency != null && this.Frequency.Equals(other.Frequency) ) && ( this.Nonburn == other.Nonburn || this.Nonburn != null && this.Nonburn.Equals(other.Nonburn) ) && ( this.PastFires == other.PastFires || this.PastFires != null && this.PastFires.Equals(other.PastFires) ) && ( this.Severity == other.Severity || this.Severity != null && this.Severity.Equals(other.Severity) ) && ( this.Continuity == other.Continuity || this.Continuity != null && this.Continuity.Equals(other.Continuity) ) && ( this.Adjustment == other.Adjustment || this.Adjustment != null && this.Adjustment.Equals(other.Adjustment) ) && ( this.Aspect == other.Aspect || this.Aspect != null && this.Aspect.Equals(other.Aspect) ) && ( this.CrownFire == other.CrownFire || this.CrownFire != null && this.CrownFire.Equals(other.CrownFire) ) && ( this.Vegetation == other.Vegetation || this.Vegetation != null && this.Vegetation.Equals(other.Vegetation) ) && ( this.Foehn == other.Foehn || this.Foehn != null && this.Foehn.Equals(other.Foehn) ) && ( this.GolfCourse == other.GolfCourse || this.GolfCourse != null && this.GolfCourse.Equals(other.GolfCourse) ) && ( this.RoadDist == other.RoadDist || this.RoadDist != null && this.RoadDist.Equals(other.RoadDist) ) && ( this.Slope == other.Slope || this.Slope != null && this.Slope.Equals(other.Slope) ) && ( this.WaterDist == other.WaterDist || this.WaterDist != null && this.WaterDist.Equals(other.WaterDist) ) && ( this.Tier == other.Tier || this.Tier != null && this.Tier.Equals(other.Tier) ) && ( this.TierDescription == other.TierDescription || this.TierDescription != null && this.TierDescription.Equals(other.TierDescription) ) && ( this.DistanceToFireStation == other.DistanceToFireStation || this.DistanceToFireStation != null && this.DistanceToFireStation.Equals(other.DistanceToFireStation) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Type != null) hash = hash * 59 + this.Type.GetHashCode(); if (this.Description != null) hash = hash * 59 + this.Description.GetHashCode(); if (this.Risk50Rating != null) hash = hash * 59 + this.Risk50Rating.GetHashCode(); if (this.Frequency != null) hash = hash * 59 + this.Frequency.GetHashCode(); if (this.Nonburn != null) hash = hash * 59 + this.Nonburn.GetHashCode(); if (this.PastFires != null) hash = hash * 59 + this.PastFires.GetHashCode(); if (this.Severity != null) hash = hash * 59 + this.Severity.GetHashCode(); if (this.Continuity != null) hash = hash * 59 + this.Continuity.GetHashCode(); if (this.Adjustment != null) hash = hash * 59 + this.Adjustment.GetHashCode(); if (this.Aspect != null) hash = hash * 59 + this.Aspect.GetHashCode(); if (this.CrownFire != null) hash = hash * 59 + this.CrownFire.GetHashCode(); if (this.Vegetation != null) hash = hash * 59 + this.Vegetation.GetHashCode(); if (this.Foehn != null) hash = hash * 59 + this.Foehn.GetHashCode(); if (this.GolfCourse != null) hash = hash * 59 + this.GolfCourse.GetHashCode(); if (this.RoadDist != null) hash = hash * 59 + this.RoadDist.GetHashCode(); if (this.Slope != null) hash = hash * 59 + this.Slope.GetHashCode(); if (this.WaterDist != null) hash = hash * 59 + this.WaterDist.GetHashCode(); if (this.Tier != null) hash = hash * 59 + this.Tier.GetHashCode(); if (this.TierDescription != null) hash = hash * 59 + this.TierDescription.GetHashCode(); if (this.DistanceToFireStation != null) hash = hash * 59 + this.DistanceToFireStation.GetHashCode(); return hash; } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using Platform.Support.Windows; using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace Platform.Presentation.Forms.Controls { /// <summary> /// Provides an animated bitmap control. /// </summary> [ToolboxBitmap(typeof(System.Windows.Forms.PictureBox))] [ToolboxItem(true)] public class AnimatedBitmap : Control { #region Private Member Variables /// <summary> /// The bitmap list. /// </summary> private Bitmap[] bitmaps; /// <summary> /// The current bitmap index. /// </summary> private int currentBitmapIndex; /// <summary> /// The timer that runs the animation. /// </summary> private Timer timerAnimation; private bool useVirtualTransparency; /// <summary> /// Components. /// </summary> private IContainer components; #endregion Private Member Variables #region Class Initialization & Termination /// <summary> /// Initializes a new instance of the AnimatedBitmapControl class. /// </summary> public AnimatedBitmap() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Turn on double buffered painting. SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.DoubleBuffer, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.SupportsTransparentBackColor, true); // Redraw the control on resize. SetStyle(ControlStyles.ResizeRedraw, true); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { // Stop the animation timer. timerAnimation.Stop(); timerAnimation.Tick -= new EventHandler(this.timerAnimation_Tick); timerAnimation.Dispose(); timerAnimation = null; if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #endregion Class Initialization & Termination #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.timerAnimation = new System.Windows.Forms.Timer(this.components); // // timerAnimation // this.timerAnimation.Tick += new System.EventHandler(this.timerAnimation_Tick); // // AnimatedBitmapControl // this.Name = "AnimatedBitmapControl"; this.Size = new System.Drawing.Size(64, 48); } #endregion Component Designer generated code #region Public Properties /// <summary> /// Gets or sets the animation /// </summary> public int Interval { get { return timerAnimation.Interval; } set { if (timerAnimation.Interval != value) { bool running = timerAnimation.Enabled; if (running) timerAnimation.Stop(); timerAnimation.Interval = value; if (running) timerAnimation.Start(); } } } /// <summary> /// Gets or sets the bitmaps. /// </summary> public Bitmap[] Bitmaps { get { return bitmaps; } set { bitmaps = value; } } /// <summary> /// Gets or sets the animation running state. /// </summary> public bool Running { get { return timerAnimation.Enabled; } set { if (timerAnimation.Enabled != value) timerAnimation.Enabled = value; } } public bool UseVirtualTransparency { get { return useVirtualTransparency; } set { useVirtualTransparency = value; } } #endregion Public Properties #region Public Methods /// <summary> /// Starts the animation. /// </summary> public void Start() { Enabled = true; timerAnimation.Start(); } /// <summary> /// Stops the animation. /// </summary> public void Stop() { Enabled = false; timerAnimation.Stop(); } #endregion Public Methods #region Protected Event Overrides /// <summary> /// Raises the Paint event. /// </summary> /// <param name="e">A PaintEventArgs that contains the event data.</param> protected override void OnPaint(PaintEventArgs e) { // Call the base class's method so that registered delegates receive the event. base.OnPaint(e); Graphics g = e.Graphics; // Obtain the bitmap to draw and, if there is one, draw it. Bitmap bitmap = BitmapToDraw; if (bitmap != null) { // Fill the offscreen graphics context with the background color. if (UseVirtualTransparency) { VirtualTransparency.VirtualPaint(this, new PaintEventArgs(g, ClientRectangle)); } else { using (SolidBrush solidBrush = new SolidBrush(BackColor)) g.FillRectangle(solidBrush, ClientRectangle); } BidiGraphics bg = new BidiGraphics(g, ClientRectangle, RightToLeft); Rectangle bounds = new Rectangle(Point.Empty, bitmap.Size); bg.DrawImage(true, bitmap, bounds); } } #endregion Protected Event Overrides #region Private Event Handlers /// <summary> /// timerAnimation_Tick event handler. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">An EventArgs that contains the event data.</param> private void timerAnimation_Tick(object sender, EventArgs e) { currentBitmapIndex = (bitmaps != null && bitmaps.Length > 0) ? (currentBitmapIndex + 1) % bitmaps.Length : 0; Invalidate(); Update(); } #endregion Private Event Handlers #region Private Methods /// <summary> /// Gets the bitmap to draw. /// </summary> /// <returns>The Bitmap to draw, or null.</returns> private Bitmap BitmapToDraw { get { // If there are no bitmaps, return null. if (bitmaps == null || bitmaps.Length == 0) return null; // Return the bitmap to draw, and advance the frame as needed. return bitmaps[currentBitmapIndex]; } } #endregion Private Methods } #region VirtualTransparency internal interface IVirtualTransparencyHost { void Paint(PaintEventArgs args); } internal class VirtualTransparency { public static IVirtualTransparencyHost VirtualParent(Control child) { for (Control parent = child.Parent; parent != null; parent = parent.Parent) { if (parent is IVirtualTransparencyHost) { return (IVirtualTransparencyHost)parent; } } return null; } public static void VirtualPaint(Control child, PaintEventArgs args) { IVirtualTransparencyHost parent = VirtualParent(child); Debug.Assert(parent != null, "No virtual transparency host found in ancestor chain of " + child.Name); VirtualPaint(parent, child, args); } public static void VirtualPaint(IVirtualTransparencyHost host, Control child, PaintEventArgs args) { Control hostControl = (Control)host; bool rtl = host is Form && ((Form)host).RightToLeft == RightToLeft.Yes && ((Form)host).RightToLeftLayout; Point childLocation = child.PointToScreen(new Point(0, 0)); Point hostLocation = hostControl.PointToScreen(new Point(rtl ? hostControl.ClientSize.Width : 0, 0)); Point relativeChildLocation = new Point(childLocation.X - hostLocation.X, childLocation.Y - hostLocation.Y); if (relativeChildLocation == Point.Empty) { // no translation transform required host.Paint(args); return; } Rectangle relativeClipRectangle = args.ClipRectangle; relativeClipRectangle.Offset(relativeChildLocation); args.Graphics.SetClip(relativeClipRectangle, CombineMode.Replace); // Global transformations applied in GDI+ land don't apply to // GDI calls. So we need to drop down to GDI, apply a transformation // there, then wrap with GDI+. IntPtr hdc = args.Graphics.GetHdc(); try { Gdi32.GraphicsMode oldGraphicsMode = Gdi32.SetGraphicsMode(hdc, Gdi32.GraphicsMode.Advanced); Gdi32.XFORM xformOrig; Gdi32.GetWorldTransform(hdc, out xformOrig); try { Gdi32.XFORM xform = xformOrig; xform.eDx -= relativeChildLocation.X; xform.eDy -= relativeChildLocation.Y; Gdi32.SetWorldTransform(hdc, ref xform); using (Graphics g = Graphics.FromHdc(hdc)) { host.Paint(new PaintEventArgs(g, relativeClipRectangle)); } } finally { Gdi32.SetWorldTransform(hdc, ref xformOrig); Gdi32.SetGraphicsMode(hdc, oldGraphicsMode); } } finally { args.Graphics.ReleaseHdc(hdc); } } } #endregion VirtualTransparency }
// <copyright file="TabletDeviceCollection.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> using System; using System.Diagnostics; using System.Windows; using System.Collections; using System.Globalization; using System.Windows.Media; using MS.Utility; using System.Security; using System.Security.Permissions; using MS.Internal; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using MS.Win32.Penimc; using System.Runtime.InteropServices; using MS.Win32; using Microsoft.Win32; namespace System.Windows.Input { ///////////////////////////////////////////////////////////////////////// /// <summary> /// Collection of the tablet devices that are available on the machine. /// </summary> public class TabletDeviceCollection : ICollection, IEnumerable { const int VistaMajorVersion = 6; ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical: Calls ShouldEnableTablets /// </SecurityNote> [SecurityCritical] internal TabletDeviceCollection() { StylusLogic stylusLogic = StylusLogic.CurrentStylusLogic; bool enabled = stylusLogic.Enabled; if (!enabled) { enabled = ShouldEnableTablets(); } // If enabled or we are a tabletpc (vista sets dynamically if digitizers present) then enable the pen! if (enabled) { UpdateTablets(); // Create the tablet device collection! // Enable stylus input on all hwnds if we have not yet done so. if (!stylusLogic.Enabled) { stylusLogic.EnableCore(); } } } /// <summary> /// Checks if Tablets should be enabled. /// </summary> /// <returns></returns> /// <SecurityNote> /// Critical: Calls SecurityCritical routines (IsWisptisRegistered, /// HasTabletDevices, UnsafeNativeMethods.GetSystemMetrics, /// PenThreadPool.GetPenThreadForPenContext, PenThread.WorkerGetTabletsInfo, /// TabletDevice constructor, StylusLogic.EnableCore and /// StylusLogic.CurrentStylusLogic). /// </SecurityNote> [SecurityCritical] internal static bool ShouldEnableTablets() { bool enabled = false; // We only want to enable by default if Wisptis is registered and tablets are detected. // We do the same detection on all OS versions. // // NOTE: This code does not support the new Vista wisptis feature to be able to exclude // tablet devices using a special registy key. The only side effect of not supporting // this feature is that we would go ahead and load wisptis when we really don't need to // (since wisptis would not return us any tablet devices). This should be a fairly rare // case though. if (IsWisptisRegistered() && HasTabletDevices()) { enabled = true; // start up wisptis } return enabled; } ///<SecurityNote> /// Critical - Asserts read registry permission... /// - TreatAsSafe boundry is HwndSource constructor and Tablet.TabletDevices. /// - called by this objects constructor ///</SecurityNote> [SecurityCritical] private static bool IsWisptisRegistered() { bool fRegistered = false; RegistryKey key = null; // This object has finalizer to close the key. Object valDefault = null; bool runningOnVista = (Environment.OSVersion.Version.Major >= VistaMajorVersion); string keyToAssertPermissionFor = runningOnVista ? "HKEY_CLASSES_ROOT\\Interface\\{C247F616-BBEB-406A-AED3-F75E656599AE}" : "HKEY_CLASSES_ROOT\\CLSID\\{A5B020FD-E04B-4e67-B65A-E7DEED25B2CF}\\LocalServer32"; string subkeyToOpen = runningOnVista ? "Interface\\{C247F616-BBEB-406A-AED3-F75E656599AE}" : "CLSID\\{A5B020FD-E04B-4e67-B65A-E7DEED25B2CF}\\LocalServer32"; string valueToSearchFor = runningOnVista ? "ITablet2" : "wisptis.exe"; // Perform the OS specific check for wisptis new RegistryPermission(RegistryPermissionAccess.Read, keyToAssertPermissionFor).Assert(); // BlessedAssert try { key = Registry.ClassesRoot.OpenSubKey(subkeyToOpen); if (key != null) { valDefault = key.GetValue(""); } } finally { RegistryPermission.RevertAssert(); } if (key != null) { string sValDefault = valDefault as string; if (sValDefault != null && sValDefault.LastIndexOf(valueToSearchFor, StringComparison.OrdinalIgnoreCase) != -1) { fRegistered = true; } key.Close(); } return fRegistered; } ///<SecurityNote> /// Critical - Calls critical methods (GetRawInputDeviceList, GetRawInputDeviceInfo, Marshal.SizeOf). /// - TreatAsSafe boundry is HwndSource constructor and Tablet.TabletDevices. /// - called by constructor ///</SecurityNote> [SecurityCritical] private static bool HasTabletDevices() { uint deviceCount = 0; // Determine the number of devices first (result will be -1 if fails and cDevices will have count) int result = (int)MS.Win32.UnsafeNativeMethods.GetRawInputDeviceList(null, ref deviceCount, (uint)Marshal.SizeOf(typeof(NativeMethods.RAWINPUTDEVICELIST))); if (result >= 0 && deviceCount != 0) { NativeMethods.RAWINPUTDEVICELIST[] ridl = new NativeMethods.RAWINPUTDEVICELIST[deviceCount]; int count = (int)MS.Win32.UnsafeNativeMethods.GetRawInputDeviceList(ridl, ref deviceCount, (uint)Marshal.SizeOf(typeof(NativeMethods.RAWINPUTDEVICELIST))); if (count > 0) { for (int i = 0; i < count; i++) { if (ridl[i].dwType == NativeMethods.RIM_TYPEHID) { NativeMethods.RID_DEVICE_INFO deviceInfo = new NativeMethods.RID_DEVICE_INFO(); deviceInfo.cbSize = (uint)Marshal.SizeOf(typeof(NativeMethods.RID_DEVICE_INFO)); uint cbSize = (uint)deviceInfo.cbSize; int cBytes = (int)MS.Win32.UnsafeNativeMethods.GetRawInputDeviceInfo(ridl[i].hDevice, NativeMethods.RIDI_DEVICEINFO, ref deviceInfo, ref cbSize); if (cBytes > 0) { if (deviceInfo.hid.usUsagePage == NativeMethods.HID_USAGE_PAGE_DIGITIZER) { switch (deviceInfo.hid.usUsage) { case NativeMethods.HID_USAGE_DIGITIZER_DIGITIZER: case NativeMethods.HID_USAGE_DIGITIZER_PEN: case NativeMethods.HID_USAGE_DIGITIZER_TOUCHSCREEN: case NativeMethods.HID_USAGE_DIGITIZER_LIGHTPEN: { return true; } } } } else { System.Diagnostics.Debug.WriteLine("TabletDeviceCollection: GetRawInputDeviceInfo failed!"); } } } } else if (count < 0) { System.Diagnostics.Debug.WriteLine("TabletDeviceCollection: GetRawInputDeviceList failed!"); } } return false; } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical: calls into SecurityCritical code with SuppressUnmangedCode /// (GetTabletCount, GetTablet, PimcPInvoke and PimcManager) /// and calls SecurityCritical code TabletDevice constructor. /// </SecurityNote> [SecurityCritical] internal void UpdateTablets() { if (_tablets == null) throw new ObjectDisposedException("TabletDeviceCollection"); // This method can be re-entered in a way that can cause deadlock // (Dev11 960656). This can happen if multiple WM_DEVICECHANGE // messages are pending and we have not yet built the tablet collection. // Here's how: // 1. First WM_DEVICECHANGE message enters here, starts to launch pen thread // 2. Penimc.UnsafeNativeMethods used for the first time, start its // static constructor. // 3. The static cctor starts to create a PimcManager via COM CLSID. // 4. COM pumps message, a second WM_DEVICECHANGE re-enters here // and starts to launch another pen thread. // 5. The static cctor is skipped (although step 3 hasn't finished), // and the pen thread is started // 6. The PenThreadWorker (on the UI thread) waits for the // PenThread to respond. // 7. Meanwhile the pen thread's code refers to Pimc.UnsafeNativeMethods. // It's on a separate thread, so it waits for the static cctor to finish. // Deadlock: UI thread is waiting for PenThread, but holding the CLR's // lock on the static cctor. The Pen thread is waiting for the static cctor. // // Multiple WM_DEVICECHANGE messages also cause re-entrancy even if the // static cctor has already finished. There's no deadlock in that case, // but we end up with multiple pen threads (steps 1 and 4). Besides being // redundant, that can cause problems when the threads collide with each // other or do work twice. // // In any case, the re-entrancy is harmful. So we avoid it in the usual // way - setting a flag on entry and early-exit if the flag is set. // // Usually the outermost call will leave the tablet collection in the // right state, but there's a small chance that the OS or pen-input service // will change something while the outermost call is in progress, so that // the inner (re-entrant) call really would have picked up new information. // To handle that case, we'll simply re-run the outermost call if any // re-entrancy is detected. Usually that will have no real effect, as // the code here detects when no change is made to the tablet collection. if (_inUpdateTablets) { // this is a re-entrant call. Note that it happened, but do no work. _hasUpdateTabletsBeenCalledReentrantly = true; return; } try { _inUpdateTablets = true; do { _hasUpdateTabletsBeenCalledReentrantly = false; // do the real work UpdateTabletsImpl(); // if re-entrancy happened, start over // This could loop forever, but only if we get an unbounded // number of re-entrant events; that would have looped // forever even without this re-entrancy logic. } while (_hasUpdateTabletsBeenCalledReentrantly); } finally { // when we're done (either normally or via exception) // reset the re-entrancy state _inUpdateTablets = false; _hasUpdateTabletsBeenCalledReentrantly = false; } } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical: calls into SecurityCritical code with SuppressUnmangedCode /// (GetTabletCount, GetTablet, PimcPInvoke and PimcManager) /// and calls SecurityCritical code TabletDevice constructor. /// </SecurityNote> [SecurityCritical] void UpdateTabletsImpl() { // REENTRANCY NOTE: Let a PenThread do this work to avoid reentrancy! // On return you get entire list of tablet and info needed to // create all the tablet devices (and stylus device info gets // cached too in penimc which avoids calls to wisptis.exe). // Use existing penthread if we have one otherwise grab an available one. PenThread penThread = _tablets.Length > 0 ? _tablets[0].PenThread : PenThreadPool.GetPenThreadForPenContext(null); TabletDeviceInfo [] tabletdevices = penThread.WorkerGetTabletsInfo(); // First find out the index of the mouse device (usually the first at index 0) uint indexMouseTablet = UInt32.MaxValue; for (uint i = 0; i < tabletdevices.Length; i++) { // See if this is a bogus entry first. if (tabletdevices[i].PimcTablet == null) continue; // If it is the mouse tablet device we want to ignore it. if (tabletdevices[i].DeviceType == (TabletDeviceType)(-1)) { indexMouseTablet = i; tabletdevices[i].PimcTablet = null; // ignore this one! } } // Now figure out count of valid tablet devices left uint count = 0; for (uint k = 0; k < tabletdevices.Length; k++) { if (tabletdevices[k].PimcTablet != null) count++; } TabletDevice[] tablets = new TabletDevice[count]; uint tabletsIndex = 0; uint unchangedTabletCount = 0; for (uint iTablet = 0; iTablet < tabletdevices.Length; iTablet++) { if (tabletdevices[iTablet].PimcTablet == null) { continue; // Skip looking at this index (mouse and bogus tablets are ignored). } int id = tabletdevices[iTablet].Id; // First see if same index has not changed (typical case) if (tabletsIndex < _tablets.Length && _tablets[tabletsIndex] != null && _tablets[tabletsIndex].Id == id) { tablets[tabletsIndex] = _tablets[tabletsIndex]; _tablets[tabletsIndex] = null; // clear to ignore on cleanup pass. unchangedTabletCount++; } else { // Look up and see if we have this tabletdevice created already... TabletDevice tablet = null; for (uint i = 0; i < _tablets.Length; i++) { if (_tablets[i] != null && _tablets[i].Id == id) { tablet = _tablets[i]; _tablets[i] = null; // clear it so we don't dispose it. break; } } // Not found so create it. if (tablet == null) { try { tablet = new TabletDevice(tabletdevices[iTablet], penThread); } catch (InvalidOperationException ex) { // This is caused by the Stylus ID not being unique when trying // to register it in the StylusLogic.__stylusDeviceMap. If we // come across a dup then just ignore registering this tablet device. // There seems to be an issue in wisptis where different tablet IDs get // duplicate Stylus Ids when installing the VHID test devices. if (ex.Data.Contains("System.Windows.Input.StylusLogic")) { continue; // Just go to next without adding this one. } else { throw; // not an expected exception, rethrow it. } } } tablets[tabletsIndex] = tablet; } tabletsIndex++; } if (unchangedTabletCount == _tablets.Length && unchangedTabletCount == tabletsIndex && tabletsIndex == count) { // Keep the _tablet reference when nothing changes. // The reason is that if this method gets called from within // CreateContexts while looping on _tablets, it could result in // a null ref exception since the original _tablets array has // been purged to nulls. // NOTE: There is still the case of changing the ref (else case below) // when tablet devices actually change. But such a case is rare // (if not improbable) from within CreateContexts. Array.Copy(tablets, 0, _tablets, 0, count); _indexMouseTablet = indexMouseTablet; } else { // See if we need to re alloc the array due to invalid tabletdevice being seen. if (tabletsIndex != count) { TabletDevice[] updatedTablets = new TabletDevice[tabletsIndex]; Array.Copy(tablets, 0, updatedTablets, 0, tabletsIndex); tablets = updatedTablets; } DisposeTablets(); // Clean up any non null TabletDevice entries on old array. _tablets = tablets; // set updated tabletdevice array _indexMouseTablet = indexMouseTablet; } } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical: calls into SecurityCritical code with SuppressUnmangedCode /// (GetTablet, PimcPInvoke and PimcManager) /// and calls SecurityCritical code TabletDevice constructor. /// </SecurityNote> [SecurityCritical] internal bool HandleTabletAdded(uint wisptisIndex, ref uint tabletIndexChanged) { if (_tablets == null) throw new ObjectDisposedException("TabletDeviceCollection"); tabletIndexChanged = UInt32.MaxValue; // REENTRANCY NOTE: Let a PenThread do this work to avoid reentrancy! // On return you get the tablet info needed to // create a tablet devices (and stylus device info gets // cached in penimc too which avoids calls to wisptis.exe). // Use existing penthread if we have one otherwise grab an available one. PenThread penThread = _tablets.Length > 0 ? _tablets[0].PenThread : PenThreadPool.GetPenThreadForPenContext(null); TabletDeviceInfo tabletInfo = penThread.WorkerGetTabletInfo(wisptisIndex); // If we failed due to a COM exception on the pen thread then return if (tabletInfo.PimcTablet == null) { return true; // make sure we rebuild our tablet collection. (return true + MaxValue). } // if mouse tabletdevice then ignore it. if (tabletInfo.DeviceType == (TabletDeviceType)(-1)) { _indexMouseTablet = wisptisIndex; // update index. return false; // TabletDevices did not change. } // Now see if this is a duplicate add call we want to filter out (ie - already added to tablet collection). uint indexFound = UInt32.MaxValue; for (uint i = 0; i < _tablets.Length; i++) { // If it is the mouse tablet device we want to ignore it. if (_tablets[i].Id == tabletInfo.Id) { indexFound = i; break; } } // We only want to add this if it is not currently in the collection. Wisptis will send // us duplicate adds at times so this is a work around for that issue. uint tabletIndex = UInt32.MaxValue; if (indexFound == UInt32.MaxValue) { tabletIndex = wisptisIndex; if (tabletIndex > _indexMouseTablet) { tabletIndex--; } else { _indexMouseTablet++; } // if index is out of range then ignore it. Return of MaxValue causes a rebuild of the devices. if (tabletIndex <= _tablets.Length) { try { // Add new tablet at end of collection AddTablet(tabletIndex, new TabletDevice(tabletInfo, penThread)); } catch (InvalidOperationException ex) { // This is caused by the Stylus ID not being unique when trying // to register it in the StylusLogic.__stylusDeviceMap. If we // come across a dup then we should rebuild the tablet device collection. // There seems to be an issue in wisptis where different tablet IDs get // duplicate Stylus Ids when installing the VHID test devices. if (ex.Data.Contains("System.Windows.Input.StylusLogic")) { return true; // trigger the tabletdevices to be rebuilt. } else { throw; // not an expected exception, rethrow it. } } tabletIndexChanged = tabletIndex; return true; } else { return true; // bogus index. Return true so that the caller can rebuild the collection. } } else { return false; // We found this tablet device already. Don't do anything. } } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical: calls into SecurityCritical code RemoveTablet. /// </SecurityNote> [SecurityCritical] internal uint HandleTabletRemoved(uint wisptisIndex) { if (_tablets == null) throw new ObjectDisposedException("TabletDeviceCollection"); // if mouse tabletdevice then ignore it. if (wisptisIndex == _indexMouseTablet) { _indexMouseTablet = UInt32.MaxValue; return UInt32.MaxValue; // Don't process this notification any further. } uint tabletIndex = wisptisIndex; if (wisptisIndex > _indexMouseTablet) { tabletIndex--; } else { // Must be less than _indexMouseTablet since equality is done above. _indexMouseTablet--; } // if index is out of range then ignore it. if (tabletIndex >= _tablets.Length) { return UInt32.MaxValue; // Don't process this notification any further. } // Remove tablet from collection RemoveTablet(tabletIndex); return tabletIndex; } ///////////////////////////////////////////////////////////////////// // NOTE: This routine takes indexes that are in the TabletCollection range // and not in the wisptis tablet index range. /// <SecurityNote> /// Critical: calls into SecurityCritical code TabletDevice constructor. /// </SecurityNote> [SecurityCritical] void AddTablet(uint index, TabletDevice tabletDevice) { Debug.Assert(index <= Count); Debug.Assert(tabletDevice.Type != (TabletDeviceType)(-1)); // make sure not the mouse tablet device! TabletDevice[] newTablets = new TabletDevice[Count + 1]; uint preCopyCount = index; uint postCopyCount = (uint)_tablets.Length - index; Array.Copy(_tablets, 0, newTablets, 0, preCopyCount); newTablets[index] = tabletDevice; Array.Copy(_tablets, index, newTablets, index+1, postCopyCount); _tablets = newTablets; } ///////////////////////////////////////////////////////////////////// // NOTE: This routine takes indexes that are in the TabletCollection range // and not in the wisptis tablet index range. /// <SecurityNote> /// Critical: calls SecurityCritical code TabletDevice.Dispose. /// and StylusLogic.SelectStylusDevice /// </SecurityNote> [SecurityCritical] void RemoveTablet(uint index) { System.Diagnostics.Debug.Assert(index < Count && Count > 0); TabletDevice removeTablet = _tablets[index]; TabletDevice[] tablets = new TabletDevice[_tablets.Length - 1]; uint preCopyCount = index; uint postCopyCount = (uint)_tablets.Length - index - 1; Array.Copy(_tablets, 0, tablets, 0, preCopyCount); Array.Copy(_tablets, index+1, tablets, index, postCopyCount); _tablets = tablets; // Make sure we release any references to a stylus device that may // have been removed if (Tablet.CurrentTabletDevice == removeTablet) { StylusLogic.CurrentStylusLogic.SelectStylusDevice(null, null, true); } removeTablet.Dispose(); } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical: calls into SecurityCritical code with SuppressUnmangedCode /// (GetTablet, PimcPInvoke and PimcManager) /// and calls SecurityCritical code TabletDevice constructor. /// </SecurityNote> [SecurityCritical] internal StylusDevice UpdateStylusDevices(int tabletId, int stylusId) { if (_tablets == null) throw new ObjectDisposedException("TabletDeviceCollection"); for (int iTablet = 0, cTablets = _tablets.Length; iTablet < cTablets; iTablet++) { TabletDevice tablet = _tablets[iTablet]; if (tablet.Id == tabletId) { return tablet.UpdateStylusDevices(stylusId); } } return null; } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical: calls into SecurityCritical code TabletDevice.Dispose. /// and StylusLogic.SelectStylusDevice /// </SecurityNote> [SecurityCritical] internal void DisposeTablets() { if (_tablets != null) { for (int iTablet = 0, cTablets = _tablets.Length; iTablet < cTablets; iTablet++) { if (_tablets[iTablet] != null) { // Make sure this stylus device is not the current one. if (Tablet.CurrentTabletDevice == _tablets[iTablet]) { StylusLogic.CurrentStylusLogic.SelectStylusDevice(null, null, true); } _tablets[iTablet].Dispose(); } } _tablets = null; } } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical: - calls into security critical code (PenContext constructor /// and PenContext.CreateContext) /// - takes in data that is potential security risk (hwnd) /// </SecurityNote> [SecurityCritical] internal PenContext[] CreateContexts(IntPtr hwnd, PenContexts contexts) { int c = Count; PenContext[] ctxs = new PenContext[c]; int i = 0; foreach (TabletDevice tablet in _tablets) { ctxs[i] = tablet.CreateContext(hwnd, contexts); i++; } return ctxs; } ///////////////////////////////////////////////////////////////////// /// <summary> /// Retrieve the number of TabletDevice objects in the collection. /// </summary> public int Count { get { if (_tablets == null) throw new ObjectDisposedException("TabletDeviceCollection"); return _tablets.Length; } } ///////////////////////////////////////////////////////////////////// /// <summary> /// Copy the TabletDevice objects in the collection to another array. /// </summary> /// <param name="array">destination array</param> /// <param name="index">position in destination array to begin copying</param> void ICollection.CopyTo(Array array, int index) { // Delegate error checking to Array.Copy. Array.Copy(_tablets, 0, array, index, this.Count); } ///////////////////////////////////////////////////////////////////// /// <summary> /// Copy the TabletDevice objects in the collection to another array /// of TabletDevices. /// </summary> /// <param name="array">destination array</param> /// <param name="index">position in destination array to begin copying</param> public void CopyTo(TabletDevice[] array, int index) { ((ICollection)this).CopyTo(array, index); } ///////////////////////////////////////////////////////////////////// /// <summary> /// Retrieve the specified TabletDevice object from the collection. /// </summary> /// <param name="index">index of TabletDevice in collection to retrieve</param> public TabletDevice this[int index] { get { if (index >= Count || index < 0) throw new ArgumentException(SR.Get(SRID.Stylus_IndexOutOfRange, index.ToString(System.Globalization.CultureInfo.InvariantCulture)), "index"); return _tablets[index]; } } ///////////////////////////////////////////////////////////////////// /// <summary> /// Returns an object which can be used to lock during synchronization by collection users. /// <seealso cref="System.Collections.ICollection.SyncRoot"/> /// </summary> public object SyncRoot { get { return this; } } ///////////////////////////////////////////////////////////////////// /// <summary> /// Determine if the collection has thread-safe operations. /// </summary> public bool IsSynchronized { get { return false; } } ///////////////////////////////////////////////////////////////////// /// <summary> /// Standard implementation of IEnumerable which enables callers to use the /// foreach construct to enumerate through each TabletDevice in the collection. /// </summary> IEnumerator IEnumerable.GetEnumerator() { return new TabletDeviceEnumerator(this); } ///////////////////////////////////////////////////////////////////// /// <summary> /// Standard implementation of IEnumerator for the Tablets collection /// </summary> internal struct TabletDeviceEnumerator : IEnumerator { ///////////////////////////////////////////////////////////////// /// <summary> /// Create a new enumerator, initialized with a TabletDeviceCollection /// </summary> /// <param name="tabletDeviceCollection">collection to enumerate over</param> internal TabletDeviceEnumerator(TabletDeviceCollection tabletDeviceCollection) { _tabletDeviceCollection = tabletDeviceCollection; _index = -1; } ///////////////////////////////////////////////////////////////// /// <summary> /// Move the enumerator index to the next property in the collection. /// </summary> public bool MoveNext() { if (_tabletDeviceCollection != null) { if (_index < _tabletDeviceCollection.Count) { _index++; } return _index < _tabletDeviceCollection.Count; } else { return false; } } ///////////////////////////////////////////////////////////////// /// <summary> /// Reset the enumerator index in the collection to the beginning /// of the collection /// </summary> public void Reset() { _index = -1; } ///////////////////////////////////////////////////////////////// /// <summary> /// Retrieve the currently indexed property in the collection /// </summary> object IEnumerator.Current { get { return (TabletDevice)Current; } } ///////////////////////////////////////////////////////////////// /// <summary> /// Strongly-typed method to retrieve the currently indexed property in the collection /// </summary> public TabletDevice Current { get { if ((_index < 0) || (_tabletDeviceCollection == null) || (_index >= _tabletDeviceCollection.Count)) { // samgeo - Presharp issue // Presharp gives a warning when get methods of a property throws an exception. // However, the get method of the IEnumerator class has to throw an exception // by Design. The details can be found in the MSDN documentation for IEnumerator. #pragma warning disable 1634, 1691 #pragma warning suppress 6503 throw new InvalidOperationException(SR.Get(SRID.Stylus_EnumeratorFailure)); #pragma warning restore 1634, 1691 } return _tabletDeviceCollection[_index]; } } ///////////////////////////////////////////////////////////////// TabletDeviceCollection _tabletDeviceCollection; int _index; } ///////////////////////////////////////////////////////////////////// TabletDevice[] _tablets = new TabletDevice[0]; uint _indexMouseTablet = UInt32.MaxValue; bool _inUpdateTablets; // detect re-entrancy bool _hasUpdateTabletsBeenCalledReentrantly; } }
/* * 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); } /// <summary> /// Creates a vector of tables. /// </summary> /// <param name="offsets">Offsets of the tables.</param> public VectorOffset CreateVectorOfTables<T>(Offset<T>[] offsets) where T : struct { NotNested(); StartVector(sizeof(int), offsets.Length, sizeof(int)); for (int i = offsets.Length - 1; i >= 0; i--) AddOffset(offsets[i].Value); return EndVector(); } /// @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. int i = _vtableSize - 1; // Trim trailing zeroes. for (; i >= 0 && _vtable[i] == 0; i--) {} int trimmedSize = i + 1; for (; 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)((trimmedSize + standardFields) * sizeof(short))); // Search for an existing vtable that matches the current one. int existingVtable = 0; for (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); } } } /// @}
using System.IO; using System.Linq; using System.Threading; using NBitcoin; using Xunit; using System; using NBitcoin.Protocol; using System.Net; using NBitcoin.DataEncoders; namespace NBitcoin.Tests { public class NetworkAddressTests { [Fact] [Trait("UnitTest", "UnitTest")] public void CanParseSpecialAddresses() { var addr = new NetworkAddress(); // TORv2 Assert.True(addr.SetSpecial("6hzph5hv6337r6p2.onion")); Assert.True(addr.AddressType == NetworkAddressType.Onion); Assert.True(addr.IsAddrV1Compatible); Assert.Equal("6hzph5hv6337r6p2.onion", addr.ToAddressString()); // TORv3 var torv3_addr = "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion"; Assert.True(addr.SetSpecial(torv3_addr)); Assert.True(addr.AddressType == NetworkAddressType.Onion); Assert.False(addr.IsAddrV1Compatible); Assert.Equal(addr.ToAddressString(), torv3_addr); // TORv3, broken, with wrong checksum Assert.False(addr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscsad.onion")); // TORv3, broken, with wrong version Assert.False(addr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscrye.onion")); // TORv3, malicious Assert.False(addr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd\0wtf.onion")); // TOR, bogus length Assert.False(addr.SetSpecial("mfrggzak.onion")); // TOR, invalid base32 Assert.False(addr.SetSpecial("mf*g zak.onion")); // I2P var i2p_addr = "udhdrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v4jna.b32.i2p"; Assert.True(addr.SetSpecial(i2p_addr)); Assert.True(addr.AddressType == NetworkAddressType.I2P); Assert.False(addr.IsAddrV1Compatible); Assert.Equal(addr.ToAddressString(), i2p_addr); // I2P, malicious Assert.False(addr.SetSpecial("udhdrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v4jna\0wtf.b32.i2p")); // I2P, valid but unsupported Assert.False(addr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscsad.b32.i2p")); // I2P, invalid base32 Assert.False(addr.SetSpecial("tp*szydbh4dp.b32.i2p")); // General validations Assert.False(addr.SetSpecial(".onion")); Assert.False(addr.SetSpecial("")); } [Fact] [Trait("UnitTest", "UnitTest")] public void SerializeV1() { var addr = new NetworkAddress(); var mem = new MemoryStream(); var stream = new BitcoinStream(mem, true); string AddressHex() { var arr = mem.ToArray(); return Encoders.Hex.EncodeData(arr, 8, 16); } // serialize method produces an address in v2 format. stream.Type = SerializationType.Hash; stream.ReadWrite(addr); Assert.Equal("00000000000000000000000000000000", AddressHex()); mem.Clear(); addr = new NetworkAddress(IPAddress.Parse("1.2.3.4")); stream.ReadWrite(addr); Assert.Equal("00000000000000000000ffff01020304", AddressHex()); mem.Clear(); addr = new NetworkAddress(IPAddress.Parse("1a1b:2a2b:3a3b:4a4b:5a5b:6a6b:7a7b:8a8b")); stream.ReadWrite(addr); Assert.Equal("1a1b2a2b3a3b4a4b5a5b6a6b7a7b8a8b", AddressHex()); mem.Clear(); addr = new NetworkAddress(); addr.SetSpecial("6hzph5hv6337r6p2.onion"); stream.ReadWrite(addr); Assert.Equal("fd87d87eeb43f1f2f3f4f5f6f7f8f9fa", AddressHex()); mem.Clear(); addr = new NetworkAddress(); addr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion"); stream.ReadWrite(addr); Assert.Equal("00000000000000000000000000000000", AddressHex()); } [Fact] [Trait("UnitTest", "UnitTest")] public void SerializeV2() { var addr = new NetworkAddress(); var mem = new MemoryStream(); var stream = new BitcoinStream(mem, true); string HexStr() { var arr = mem.ToArray(); return Encoders.Hex.EncodeData(arr, 1, arr.Length - 3); } // Add ADDRV2_FORMAT to the version so that the CNetAddr // serialize method produces an address in v2 format. stream.ProtocolVersion = NetworkAddress.AddrV2Format; stream.Type = SerializationType.Hash; stream.ReadWrite(addr); Assert.Equal("021000000000000000000000000000000000", HexStr()); mem.Clear(); addr = new NetworkAddress(IPAddress.Parse("1.2.3.4")); stream.ReadWrite(addr); Assert.Equal("010401020304", HexStr()); mem.Clear(); addr = new NetworkAddress(IPAddress.Parse("1a1b:2a2b:3a3b:4a4b:5a5b:6a6b:7a7b:8a8b")); stream.ReadWrite(addr); Assert.Equal("02101a1b2a2b3a3b4a4b5a5b6a6b7a7b8a8b", HexStr()); mem.Clear(); addr = new NetworkAddress(); addr.SetSpecial("6hzph5hv6337r6p2.onion"); stream.ReadWrite(addr); Assert.Equal("030af1f2f3f4f5f6f7f8f9fa", HexStr()); mem.Clear(); addr = new NetworkAddress(); addr.SetSpecial("kpgvmscirrdqpekbqjsvw5teanhatztpp2gl6eee4zkowvwfxwenqaid.onion"); stream.ReadWrite(addr); Assert.Equal("042053cd5648488c4707914182655b7664034e09e66f7e8cbf1084e654eb56c5bd88", HexStr()); } [Fact] [Trait("UnitTest", "UnitTest")] public void UnserializeV2() { static BitcoinStream MakeNewStream(byte[] payload) { return new BitcoinStream(payload) { ProtocolVersion = NetworkAddress.AddrV2Format, Type = SerializationType.Hash }; } var addr = new NetworkAddress(); // Valid IPv4. var payload = Encoders.Hex.DecodeData( "00" + // services (varint) "01" + // network type (IPv4) "04" + // address length "01020304" + // address "0000"); // port var stream = MakeNewStream(payload); stream.ReadWrite(ref addr); Assert.True(addr.Endpoint.IsValid()); Assert.True(addr.AddressType == NetworkAddressType.IPv4); Assert.True(addr.IsAddrV1Compatible); Assert.Equal("1.2.3.4", addr.ToAddressString()); Assert.Equal(stream.Inner.Length, stream.Inner.Position); // Invalid IPv4, valid length but address itself is shorter. payload = Encoders.Hex.DecodeData( "00" + // services (varint) "01" + // network type (IPv4) "04" + // address length "0102" + // address "0000"); // port stream = MakeNewStream(payload); Assert.Throws<EndOfStreamException>(() => stream.ReadWrite(ref addr)); Assert.Equal(stream.Inner.Length, stream.Inner.Position); // Invalid IPv4, with bogus length. // Invalid IPv4, valid length but address itself is shorter. payload = Encoders.Hex.DecodeData( "00" + // services (varint) "01" + // network type (IPv4) "05" + // address length "0102030400"); // address stream = MakeNewStream(payload); var ex = Assert.Throws<ArgumentException>(() => stream.ReadWrite(ref addr)); Assert.Equal("BIP155 IPv4 address is 5 bytes long. Expected length is 4 bytes.", ex.Message); // Valid IPv6. payload = Encoders.Hex.DecodeData( "00" + // services (varint) "02" + // network type (IPv6) "10" + // address length "0102030405060708090a0b0c0d0e0f10" + // address "0000"); // port stream = MakeNewStream(payload); stream.ReadWrite(ref addr); Assert.True(addr.Endpoint.IsValid()); Assert.True(addr.AddressType == NetworkAddressType.IPv6); Assert.True(addr.IsAddrV1Compatible); Assert.Equal("102:304:506:708:90a:b0c:d0e:f10", addr.ToAddressString()); Assert.Equal(stream.Inner.Length, stream.Inner.Position); // Invalid IPv6, with bogus length. payload = Encoders.Hex.DecodeData( "00" + // services (varint) "02" + // network type (IPv6) "04" + // address length "00000000"); // address stream = MakeNewStream(payload); ex = Assert.Throws<ArgumentException>(() => stream.ReadWrite(ref addr)); Assert.Equal("BIP155 IPv6 address is 4 bytes long. Expected length is 16 bytes.", ex.Message); // Invalid IPv6, contains embedded IPv4. payload = Encoders.Hex.DecodeData( "00" + // services (varint) "02" + // network type (IPv6) "10" + // address length "00000000000000000000ffff01020304" + // address "0000"); // port stream = MakeNewStream(payload); stream.ReadWrite(ref addr); Assert.False(addr.Endpoint.IsValid()); Assert.Equal(stream.Inner.Length, stream.Inner.Position); // Invalid IPv6, contains embedded TORv2. payload = Encoders.Hex.DecodeData( "00" + // services (varint) "02" + // network type (IPv6) "10" + // address length "fd87d87eeb430102030405060708090a" + // address "0000"); // port stream = MakeNewStream(payload); stream.ReadWrite(ref addr); Assert.False(addr.Endpoint.IsValid()); Assert.Equal(stream.Inner.Length, stream.Inner.Position); // Valid TORv2. payload = Encoders.Hex.DecodeData( "00" + // services (varint) "03" + // network type (TORv2) "0a" + // address length "f1f2f3f4f5f6f7f8f9fa" + // address "0000"); // port stream = MakeNewStream(payload); stream.ReadWrite(ref addr); Assert.True(addr.Endpoint.IsValid()); Assert.True(addr.AddressType == NetworkAddressType.Onion); Assert.True(addr.IsAddrV1Compatible); Assert.Equal("6hzph5hv6337r6p2.onion", addr.ToAddressString()); Assert.Equal(stream.Inner.Length, stream.Inner.Position); // Invalid TORv2, with bogus length. payload = Encoders.Hex.DecodeData( "00" + // services (varint) "03" + // network type (TORv2) "07" + // address length "00000000000000" ); // address stream = MakeNewStream(payload); ex = Assert.Throws<ArgumentException>(() => stream.ReadWrite(ref addr)); Assert.Equal("BIP155 TORv2 address is 7 bytes long. Expected length is 10 bytes.", ex.Message); // Valid TORv3. payload = Encoders.Hex.DecodeData( "00" + // services (varint) "04" + // network type (TORv3) "20" + // address length "79bcc625184b05194975c28b66b66b0469f7f6556fb1ac3189a79b40dda32f1f" + // address "0000"); // port stream = MakeNewStream(payload); stream.ReadWrite(ref addr); Assert.True(addr.Endpoint.IsValid()); Assert.True(addr.AddressType == NetworkAddressType.Onion); Assert.False(addr.IsAddrV1Compatible); Assert.Equal("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion", addr.ToAddressString()); Assert.Equal(stream.Inner.Length, stream.Inner.Position); // Invalid TORv3, with bogus length. payload = Encoders.Hex.DecodeData( "00" + // services (varint) "04" + // network type (TORv3) "00" + // address length "00" ); // address stream = MakeNewStream(payload); ex = Assert.Throws<ArgumentException>(() => stream.ReadWrite(ref addr)); Assert.Equal("BIP155 TORv3 address is 0 bytes long. Expected length is 32 bytes.", ex.Message); Assert.NotEqual(stream.Inner.Length, stream.Inner.Position); // Valid I2P. payload = Encoders.Hex.DecodeData( "00" + // services (varint) "05" + // network type (I2P) "20" + // address length "a2894dabaec08c0051a481a6dac88b64f98232ae42d4b6fd2fa81952dfe36a87" + // address "0000"); // port stream = MakeNewStream(payload); stream.ReadWrite(ref addr); Assert.True(addr.Endpoint.IsValid()); Assert.True(addr.AddressType == NetworkAddressType.I2P); Assert.False(addr.IsAddrV1Compatible); Assert.Equal("ukeu3k5oycgaauneqgtnvselmt4yemvoilkln7jpvamvfx7dnkdq.b32.i2p", addr.ToAddressString()); Assert.Equal(stream.Inner.Length, stream.Inner.Position); // Invalid I2P, with bogus length. payload = Encoders.Hex.DecodeData( "00" + // services (varint) "05" + // network type (I2P) "03" + // address length "000000"); // address stream = MakeNewStream(payload); ex = Assert.Throws<ArgumentException>(() => stream.ReadWrite(ref addr)); Assert.Equal("BIP155 I2P address is 3 bytes long. Expected length is 32 bytes.", ex.Message); // Valid CJDNS. payload = Encoders.Hex.DecodeData( "00" + // services (varint) "06" + // network type (CJDNS) "10" + // address length "fc000001000200030004000500060007" + // address "0000"); // port stream = MakeNewStream(payload); stream.ReadWrite(ref addr); Assert.True(addr.Endpoint.IsValid()); Assert.True(addr.AddressType == NetworkAddressType.Cjdns); Assert.False(addr.IsAddrV1Compatible); Assert.Equal("fc00:1:2:3:4:5:6:7", addr.ToAddressString()); Assert.Equal(stream.Inner.Length, stream.Inner.Position); // Invalid CJDNS, with bogus length. payload = Encoders.Hex.DecodeData( "00" + // services (varint) "06" + // network type (CJDNS) "01" + // address length "00"); // address stream = MakeNewStream(payload); ex = Assert.Throws<ArgumentException>(() => stream.ReadWrite(ref addr)); Assert.Equal("BIP155 Cjdns address is 1 bytes long. Expected length is 16 bytes.", ex.Message); // Unknown, with extreme length. payload = Encoders.Hex.DecodeData( "00" + // services (varint) "aa" + // network type (unknown) "fe00000002" + // address length (CompactSize's MAX_SIZE) "01020304050607"); // address stream = MakeNewStream(payload); ex = Assert.Throws<ArgumentOutOfRangeException>(() => stream.ReadWrite(ref addr)); Assert.Contains("Array size too big", ex.Message); Assert.NotEqual(stream.Inner.Length, stream.Inner.Position); // Unknown, with reasonable length. payload = Encoders.Hex.DecodeData( "00" + // services (varint) "aa" + // network type (unknown) "04" + // address length "01020304" + // address "0000"); // port stream = MakeNewStream(payload); stream.ReadWrite(ref addr); Assert.False(addr.Endpoint.IsValid()); Assert.Equal(stream.Inner.Length, stream.Inner.Position); // Unknown, with zero length. payload = Encoders.Hex.DecodeData( "00" + // services (varint) "aa" + // network type (unknown) "00" + // address length "0000"); // port stream = MakeNewStream(payload); stream.ReadWrite(ref addr); Assert.False(addr.Endpoint.IsValid()); Assert.Equal(stream.Inner.Length, stream.Inner.Position); } static NetworkAddress[] fixture_addresses = new NetworkAddress[] { new NetworkAddress(IPAddress.IPv6Loopback, 0) { Services = NodeServices.Nothing, Time = Utils.UnixTimeToDateTime(0x4966bc61U) /* Fri Jan 9 02:54:25 UTC 2009 */ }, new NetworkAddress(IPAddress.IPv6Loopback, 0x00f1 /* port */) { Services = NodeServices.Network, Time = Utils.UnixTimeToDateTime(0x83766279U) /* Tue Nov 22 11:22:33 UTC 2039 */ }, new NetworkAddress(IPAddress.IPv6Loopback, 0xf1f2 /* port */) { Services = NodeServices.NODE_WITNESS | NodeServices.NODE_NETWORK_LIMITED | NodeServices.NODE_COMPACT_FILTERS, Time = Utils.UnixTimeToDateTime(0xffffffffU) /* Sun Feb 7 06:28:15 UTC 2106 */ } }; // fixture_addresses should be equal to this when serialized in V1 format. // When this is unserialized from V1 format it should equal to fixture_addresses. const string stream_addrv1_hex = "03" // number of entries + "61bc6649" // time, Fri Jan 9 02:54:25 UTC 2009 + "0000000000000000" // service flags, NODE_NONE + "00000000000000000000000000000001" // address, fixed 16 bytes (IPv4 embedded in IPv6) + "0000" // port + "79627683" // time, Tue Nov 22 11:22:33 UTC 2039 + "0100000000000000" // service flags, NODE_NETWORK + "00000000000000000000000000000001" // address, fixed 16 bytes (IPv6) + "00f1" // port + "ffffffff" // time, Sun Feb 7 06:28:15 UTC 2106 + "4804000000000000" // service flags, NODE_WITNESS | NODE_COMPACT_FILTERS | NODE_NETWORK_LIMITED + "00000000000000000000000000000001" // address, fixed 16 bytes (IPv6) + "f1f2"; // port // fixture_addresses should be equal to this when serialized in V2 format. // When this is unserialized from V2 format it should equal to fixture_addresses. static string stream_addrv2_hex = "03" // number of entries + "61bc6649" // time, Fri Jan 9 02:54:25 UTC 2009 + "00" // service flags, COMPACTSIZE(NODE_NONE) + "02" // network id, IPv6 + "10" // address length, COMPACTSIZE(16) + "00000000000000000000000000000001" // address + "0000" // port + "79627683" // time, Tue Nov 22 11:22:33 UTC 2039 + "01" // service flags, COMPACTSIZE(NODE_NETWORK) + "02" // network id, IPv6 + "10" // address length, COMPACTSIZE(16) + "00000000000000000000000000000001" // address + "00f1" // port + "ffffffff" // time, Sun Feb 7 06:28:15 UTC 2106 + "fd4804" // service flags, COMPACTSIZE(NODE_WITNESS | NODE_COMPACT_FILTERS | NODE_NETWORK_LIMITED) + "02" // network id, IPv6 + "10" // address length, COMPACTSIZE(16) + "00000000000000000000000000000001" // address + "f1f2"; // port [Fact] [Trait("UnitTest", "UnitTest")] public void SerializeAddressV1() { var mem = new MemoryStream(); var stream = new BitcoinStream(mem, serializing: true){ Type = SerializationType.Network }; stream.ReadWrite(ref fixture_addresses); Assert.Equal(stream_addrv1_hex, Encoders.Hex.EncodeData(mem.ToArray())); } [Fact] [Trait("UnitTest", "UnitTest")] public void SerializeAddressV2() { var mem = new MemoryStream(); var stream = new BitcoinStream(mem, serializing: true){ Type = SerializationType.Network, ProtocolVersion = NetworkAddress.AddrV2Format }; stream.ReadWrite(ref fixture_addresses); Assert.Equal(stream_addrv2_hex, Encoders.Hex.EncodeData(mem.ToArray())); } [Fact] [Trait("UnitTest", "UnitTest")] public void DeserializeAddressV2() { var stream = new BitcoinStream(Encoders.Hex.DecodeData(stream_addrv2_hex)){ Type = SerializationType.Network, ProtocolVersion = NetworkAddress.AddrV2Format }; NetworkAddress[] addresses = null; stream.ReadWrite(ref addresses); Assert.Equal(fixture_addresses.Length, addresses.Length); for (var i = 0; i < fixture_addresses.Length; i++) { Assert.Equal(fixture_addresses[i].ToAddressString(), addresses[i].ToAddressString()); } } } public static class StreamExtensions { public static void Clear(this Stream s) { s.Seek(0, SeekOrigin.Begin); s.SetLength(0); } } }
// Copyright (c) 2015, Outercurve Foundation. // 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 the Outercurve Foundation 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 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. namespace WebsitePanel.Installer.Controls { partial class ServerControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ServerControl)); this.grpConnectionSettings = new System.Windows.Forms.GroupBox(); this.txtPassword = new System.Windows.Forms.TextBox(); this.lblPassword = new System.Windows.Forms.Label(); this.txtPort = new System.Windows.Forms.TextBox(); this.lblPort = new System.Windows.Forms.Label(); this.txtServer = new System.Windows.Forms.TextBox(); this.lblServer = new System.Windows.Forms.Label(); this.btnUpdate = new System.Windows.Forms.Button(); this.btnTest = new System.Windows.Forms.Button(); this.btnRemove = new System.Windows.Forms.Button(); this.grpConnectionSettings.SuspendLayout(); this.SuspendLayout(); // // grpConnectionSettings // this.grpConnectionSettings.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.grpConnectionSettings.Controls.Add(this.txtPassword); this.grpConnectionSettings.Controls.Add(this.lblPassword); this.grpConnectionSettings.Controls.Add(this.txtPort); this.grpConnectionSettings.Controls.Add(this.lblPort); this.grpConnectionSettings.Controls.Add(this.txtServer); this.grpConnectionSettings.Controls.Add(this.lblServer); this.grpConnectionSettings.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.grpConnectionSettings.Location = new System.Drawing.Point(14, 43); this.grpConnectionSettings.Name = "grpConnectionSettings"; this.grpConnectionSettings.Size = new System.Drawing.Size(379, 122); this.grpConnectionSettings.TabIndex = 0; this.grpConnectionSettings.TabStop = false; this.grpConnectionSettings.Text = "Connection settings"; // // txtPassword // this.txtPassword.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtPassword.Location = new System.Drawing.Point(122, 82); this.txtPassword.Name = "txtPassword"; this.txtPassword.PasswordChar = '*'; this.txtPassword.Size = new System.Drawing.Size(234, 21); this.txtPassword.TabIndex = 5; // // lblPassword // this.lblPassword.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.lblPassword.Location = new System.Drawing.Point(16, 82); this.lblPassword.Name = "lblPassword"; this.lblPassword.Size = new System.Drawing.Size(100, 21); this.lblPassword.TabIndex = 4; this.lblPassword.Text = "Password"; // // txtPort // this.txtPort.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtPort.Location = new System.Drawing.Point(122, 55); this.txtPort.Name = "txtPort"; this.txtPort.Size = new System.Drawing.Size(234, 21); this.txtPort.TabIndex = 3; // // lblPort // this.lblPort.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.lblPort.Location = new System.Drawing.Point(16, 55); this.lblPort.Name = "lblPort"; this.lblPort.Size = new System.Drawing.Size(100, 21); this.lblPort.TabIndex = 2; this.lblPort.Text = "Port"; // // txtServer // this.txtServer.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtServer.Location = new System.Drawing.Point(122, 28); this.txtServer.Name = "txtServer"; this.txtServer.Size = new System.Drawing.Size(234, 21); this.txtServer.TabIndex = 1; // // lblServer // this.lblServer.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.lblServer.Location = new System.Drawing.Point(16, 28); this.lblServer.Name = "lblServer"; this.lblServer.Size = new System.Drawing.Size(100, 21); this.lblServer.TabIndex = 0; this.lblServer.Text = "Server"; // // btnUpdate // this.btnUpdate.Image = ((System.Drawing.Image)(resources.GetObject("btnUpdate.Image"))); this.btnUpdate.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnUpdate.Location = new System.Drawing.Point(148, 171); this.btnUpdate.Name = "btnUpdate"; this.btnUpdate.Size = new System.Drawing.Size(128, 28); this.btnUpdate.TabIndex = 9; this.btnUpdate.Text = "Update"; this.btnUpdate.UseVisualStyleBackColor = true; // // btnTest // this.btnTest.Image = ((System.Drawing.Image)(resources.GetObject("btnTest.Image"))); this.btnTest.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnTest.Location = new System.Drawing.Point(14, 171); this.btnTest.Name = "btnTest"; this.btnTest.Size = new System.Drawing.Size(128, 28); this.btnTest.TabIndex = 8; this.btnTest.Text = "Test connection"; this.btnTest.UseVisualStyleBackColor = true; // // btnRemove // this.btnRemove.Image = ((System.Drawing.Image)(resources.GetObject("btnRemove.Image"))); this.btnRemove.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnRemove.Location = new System.Drawing.Point(14, 9); this.btnRemove.Name = "btnRemove"; this.btnRemove.Size = new System.Drawing.Size(128, 28); this.btnRemove.TabIndex = 10; this.btnRemove.Text = "Remove server"; this.btnRemove.UseVisualStyleBackColor = true; // // ServerControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.btnRemove); this.Controls.Add(this.btnUpdate); this.Controls.Add(this.btnTest); this.Controls.Add(this.grpConnectionSettings); this.Name = "ServerControl"; this.Size = new System.Drawing.Size(406, 327); this.grpConnectionSettings.ResumeLayout(false); this.grpConnectionSettings.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox grpConnectionSettings; private System.Windows.Forms.TextBox txtPassword; private System.Windows.Forms.Label lblPassword; private System.Windows.Forms.TextBox txtPort; private System.Windows.Forms.Label lblPort; private System.Windows.Forms.TextBox txtServer; private System.Windows.Forms.Label lblServer; private System.Windows.Forms.Button btnUpdate; private System.Windows.Forms.Button btnTest; private System.Windows.Forms.Button btnRemove; } }
// File generated from our OpenAPI spec namespace Stripe { using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Stripe.Infrastructure; /// <summary> /// Sometimes you want to add a charge or credit to a customer, but actually charge or /// credit the customer's card only at the end of a regular billing cycle. This is useful /// for combining several charges (to minimize per-transaction fees), or for having Stripe /// tabulate your usage-based billing totals. /// /// Related guide: <a /// href="https://stripe.com/docs/billing/invoices/subscription#adding-upcoming-invoice-items">Subscription /// Invoices</a>. /// </summary> public class InvoiceItem : StripeEntity<InvoiceItem>, IHasId, IHasMetadata, IHasObject { /// <summary> /// Unique identifier for the object. /// </summary> [JsonProperty("id")] public string Id { get; set; } /// <summary> /// String representing the object's type. Objects of the same type share the same value. /// </summary> [JsonProperty("object")] public string Object { get; set; } /// <summary> /// Amount (in the <c>currency</c> specified) of the invoice item. This should always be /// equal to <c>unit_amount * quantity</c>. /// </summary> [JsonProperty("amount")] public long Amount { get; set; } /// <summary> /// Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency /// code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported /// currency</a>. /// </summary> [JsonProperty("currency")] public string Currency { get; set; } #region Expandable Customer /// <summary> /// (ID of the Customer) /// The ID of the customer who will be billed when this invoice item is billed. /// </summary> [JsonIgnore] public string CustomerId { get => this.InternalCustomer?.Id; set => this.InternalCustomer = SetExpandableFieldId(value, this.InternalCustomer); } /// <summary> /// (Expanded) /// The ID of the customer who will be billed when this invoice item is billed. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public Customer Customer { get => this.InternalCustomer?.ExpandedObject; set => this.InternalCustomer = SetExpandableFieldObject(value, this.InternalCustomer); } [JsonProperty("customer")] [JsonConverter(typeof(ExpandableFieldConverter<Customer>))] internal ExpandableField<Customer> InternalCustomer { get; set; } #endregion /// <summary> /// Time at which the object was created. Measured in seconds since the Unix epoch. /// </summary> [JsonProperty("date")] [JsonConverter(typeof(UnixDateTimeConverter))] public DateTime Date { get; set; } = Stripe.Infrastructure.DateTimeUtils.UnixEpoch; /// <summary> /// Whether this object is deleted or not. /// </summary> [JsonProperty("deleted", NullValueHandling = NullValueHandling.Ignore)] public bool? Deleted { get; set; } /// <summary> /// An arbitrary string attached to the object. Often useful for displaying to users. /// </summary> [JsonProperty("description")] public string Description { get; set; } /// <summary> /// If true, discounts will apply to this invoice item. Always false for prorations. /// </summary> [JsonProperty("discountable")] public bool Discountable { get; set; } #region Expandable Discounts /// <summary> /// (IDs of the Discounts) /// The discounts which apply to the invoice item. Item discounts are applied before invoice /// discounts. Use <c>expand[]=discounts</c> to expand each discount. /// </summary> [JsonIgnore] public List<string> DiscountIds { get => this.InternalDiscounts?.Select((x) => x.Id).ToList(); set => this.InternalDiscounts = SetExpandableArrayIds<Discount>(value); } /// <summary> /// (Expanded) /// The discounts which apply to the invoice item. Item discounts are applied before invoice /// discounts. Use <c>expand[]=discounts</c> to expand each discount. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public List<Discount> Discounts { get => this.InternalDiscounts?.Select((x) => x.ExpandedObject).ToList(); set => this.InternalDiscounts = SetExpandableArrayObjects(value); } [JsonProperty("discounts", ItemConverterType = typeof(ExpandableFieldConverter<Discount>))] internal List<ExpandableField<Discount>> InternalDiscounts { get; set; } #endregion #region Expandable Invoice /// <summary> /// (ID of the Invoice) /// The ID of the invoice this invoice item belongs to. /// </summary> [JsonIgnore] public string InvoiceId { get => this.InternalInvoice?.Id; set => this.InternalInvoice = SetExpandableFieldId(value, this.InternalInvoice); } /// <summary> /// (Expanded) /// The ID of the invoice this invoice item belongs to. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public Invoice Invoice { get => this.InternalInvoice?.ExpandedObject; set => this.InternalInvoice = SetExpandableFieldObject(value, this.InternalInvoice); } [JsonProperty("invoice")] [JsonConverter(typeof(ExpandableFieldConverter<Invoice>))] internal ExpandableField<Invoice> InternalInvoice { get; set; } #endregion /// <summary> /// Has the value <c>true</c> if the object exists in live mode or the value <c>false</c> if /// the object exists in test mode. /// </summary> [JsonProperty("livemode")] public bool Livemode { get; set; } /// <summary> /// Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can /// attach to an object. This can be useful for storing additional information about the /// object in a structured format. /// </summary> [JsonProperty("metadata")] public Dictionary<string, string> Metadata { get; set; } [JsonProperty("period")] public InvoiceItemPeriod Period { get; set; } /// <summary> /// If the invoice item is a proration, the plan of the subscription that the proration was /// computed for. /// </summary> [JsonProperty("plan")] public Plan Plan { get; set; } /// <summary> /// The price of the invoice item. /// </summary> [JsonProperty("price")] public Price Price { get; set; } /// <summary> /// Whether the invoice item was created automatically as a proration adjustment when the /// customer switched plans. /// </summary> [JsonProperty("proration")] public bool Proration { get; set; } /// <summary> /// Quantity of units for the invoice item. If the invoice item is a proration, the quantity /// of the subscription that the proration was computed for. /// </summary> [JsonProperty("quantity")] public long Quantity { get; set; } #region Expandable Subscription /// <summary> /// (ID of the Subscription) /// The subscription that this invoice item has been created for, if any. /// </summary> [JsonIgnore] public string SubscriptionId { get => this.InternalSubscription?.Id; set => this.InternalSubscription = SetExpandableFieldId(value, this.InternalSubscription); } /// <summary> /// (Expanded) /// The subscription that this invoice item has been created for, if any. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public Subscription Subscription { get => this.InternalSubscription?.ExpandedObject; set => this.InternalSubscription = SetExpandableFieldObject(value, this.InternalSubscription); } [JsonProperty("subscription")] [JsonConverter(typeof(ExpandableFieldConverter<Subscription>))] internal ExpandableField<Subscription> InternalSubscription { get; set; } #endregion /// <summary> /// The subscription item that this invoice item has been created for, if any. /// </summary> [JsonProperty("subscription_item")] public string SubscriptionItem { get; set; } /// <summary> /// The tax rates which apply to the invoice item. When set, the <c>default_tax_rates</c> on /// the invoice do not apply to this invoice item. /// </summary> [JsonProperty("tax_rates")] public List<TaxRate> TaxRates { get; set; } #region Expandable TestClock /// <summary> /// (ID of the TestHelpers.TestClock) /// ID of the test clock this invoice item belongs to. /// </summary> [JsonIgnore] public string TestClockId { get => this.InternalTestClock?.Id; set => this.InternalTestClock = SetExpandableFieldId(value, this.InternalTestClock); } /// <summary> /// (Expanded) /// ID of the test clock this invoice item belongs to. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public TestHelpers.TestClock TestClock { get => this.InternalTestClock?.ExpandedObject; set => this.InternalTestClock = SetExpandableFieldObject(value, this.InternalTestClock); } [JsonProperty("test_clock")] [JsonConverter(typeof(ExpandableFieldConverter<TestHelpers.TestClock>))] internal ExpandableField<TestHelpers.TestClock> InternalTestClock { get; set; } #endregion /// <summary> /// Unit amount (in the <c>currency</c> specified) of the invoice item. /// </summary> [JsonProperty("unit_amount")] public long? UnitAmount { get; set; } /// <summary> /// Same as <c>unit_amount</c>, but contains a decimal value with at most 12 decimal places. /// </summary> [JsonProperty("unit_amount_decimal")] public decimal? UnitAmountDecimal { get; set; } } }
using System; using System.Xml; using System.Diagnostics; using System.Collections; using System.Globalization; using System.Collections.Generic; using System.Threading.Tasks; namespace System.Xml { internal sealed partial class XmlSubtreeReader : XmlWrappingReader, IXmlLineInfo, IXmlNamespaceResolver { public override Task<string> GetValueAsync() { if (useCurNode) { return Task.FromResult(curNode.value); } else { return reader.GetValueAsync(); } } public override async Task< bool > ReadAsync() { switch ( state ) { case State.Initial: useCurNode = false; state = State.Interactive; ProcessNamespaces(); return true; case State.Interactive: curNsAttr = -1; useCurNode = false; reader.MoveToElement(); Debug.Assert( reader.Depth >= initialDepth ); if ( reader.Depth == initialDepth ) { if ( reader.NodeType == XmlNodeType.EndElement || ( reader.NodeType == XmlNodeType.Element && reader.IsEmptyElement ) ) { state = State.EndOfFile; SetEmptyNode(); return false; } Debug.Assert( reader.NodeType == XmlNodeType.Element && !reader.IsEmptyElement ); } if ( await reader.ReadAsync().ConfigureAwait(false) ) { ProcessNamespaces(); return true; } else { SetEmptyNode(); return false; } case State.EndOfFile: case State.Closed: case State.Error: return false; case State.PopNamespaceScope: nsManager.PopScope(); goto case State.ClearNsAttributes; case State.ClearNsAttributes: nsAttrCount = 0; state = State.Interactive; goto case State.Interactive; case State.ReadElementContentAsBase64: case State.ReadElementContentAsBinHex: if ( !await FinishReadElementContentAsBinaryAsync().ConfigureAwait(false) ) { return false; } return await ReadAsync().ConfigureAwait(false); case State.ReadContentAsBase64: case State.ReadContentAsBinHex: if ( !await FinishReadContentAsBinaryAsync().ConfigureAwait(false) ) { return false; } return await ReadAsync().ConfigureAwait(false); default: Debug.Assert( false ); return false; } } public override async Task SkipAsync() { switch ( state ) { case State.Initial: await ReadAsync().ConfigureAwait(false); return; case State.Interactive: curNsAttr = -1; useCurNode = false; reader.MoveToElement(); Debug.Assert( reader.Depth >= initialDepth ); if ( reader.Depth == initialDepth ) { if ( reader.NodeType == XmlNodeType.Element && !reader.IsEmptyElement ) { // we are on root of the subtree -> skip to the end element and set to Eof state if ( await reader.ReadAsync().ConfigureAwait(false) ) { while ( reader.NodeType != XmlNodeType.EndElement && reader.Depth > initialDepth ) { await reader.SkipAsync().ConfigureAwait(false); } } } Debug.Assert( reader.NodeType == XmlNodeType.EndElement || reader.NodeType == XmlNodeType.Element && reader.IsEmptyElement || reader.ReadState != ReadState.Interactive ); state = State.EndOfFile; SetEmptyNode(); return; } if ( reader.NodeType == XmlNodeType.Element && !reader.IsEmptyElement ) { nsManager.PopScope(); } await reader.SkipAsync().ConfigureAwait(false); ProcessNamespaces(); Debug.Assert( reader.Depth >= initialDepth ); return; case State.Closed: case State.EndOfFile: return; case State.PopNamespaceScope: nsManager.PopScope(); goto case State.ClearNsAttributes; case State.ClearNsAttributes: nsAttrCount = 0; state = State.Interactive; goto case State.Interactive; case State.ReadElementContentAsBase64: case State.ReadElementContentAsBinHex: if ( await FinishReadElementContentAsBinaryAsync().ConfigureAwait(false) ) { await SkipAsync().ConfigureAwait(false); } break; case State.ReadContentAsBase64: case State.ReadContentAsBinHex: if ( await FinishReadContentAsBinaryAsync().ConfigureAwait(false) ) { await SkipAsync().ConfigureAwait(false); } break; case State.Error: return; default: Debug.Assert( false ); return; } } public override async Task< object > ReadContentAsObjectAsync() { try { InitReadContentAsType( "ReadContentAsObject" ); object value = await reader.ReadContentAsObjectAsync().ConfigureAwait(false); FinishReadContentAsType(); return value; } catch { state = State.Error; throw; } } public override async Task< string > ReadContentAsStringAsync() { try { InitReadContentAsType( "ReadContentAsString" ); string value = await reader.ReadContentAsStringAsync().ConfigureAwait(false); FinishReadContentAsType(); return value; } catch { state = State.Error; throw; } } public override async Task< object > ReadContentAsAsync( Type returnType, IXmlNamespaceResolver namespaceResolver ) { try { InitReadContentAsType( "ReadContentAs" ); object value = await reader.ReadContentAsAsync( returnType, namespaceResolver ).ConfigureAwait(false); FinishReadContentAsType(); return value; } catch { state = State.Error; throw; } } public override async Task< int > ReadContentAsBase64Async( byte[] buffer, int index, int count ) { switch ( state ) { case State.Initial: case State.EndOfFile: case State.Closed: case State.Error: return 0; case State.ClearNsAttributes: case State.PopNamespaceScope: switch ( NodeType ) { case XmlNodeType.Element: throw CreateReadContentAsException( "ReadContentAsBase64" ); case XmlNodeType.EndElement: return 0; case XmlNodeType.Attribute: if ( curNsAttr != -1 && reader.CanReadBinaryContent ) { CheckBuffer( buffer, index, count ); if ( count == 0 ) { return 0; } if ( nsIncReadOffset == 0 ) { // called first time on this ns attribute if ( binDecoder != null && binDecoder is Base64Decoder ) { binDecoder.Reset(); } else { binDecoder = new Base64Decoder(); } } if ( nsIncReadOffset == curNode.value.Length ) { return 0; } binDecoder.SetNextOutputBuffer( buffer, index, count ); nsIncReadOffset += binDecoder.Decode( curNode.value, nsIncReadOffset, curNode.value.Length - nsIncReadOffset ); return binDecoder.DecodedCount; } goto case XmlNodeType.Text; case XmlNodeType.Text: Debug.Assert( AttributeCount > 0 ); return await reader.ReadContentAsBase64Async( buffer, index, count ).ConfigureAwait(false); default: Debug.Assert( false ); return 0; } case State.Interactive: state = State.ReadContentAsBase64; goto case State.ReadContentAsBase64; case State.ReadContentAsBase64: int read = await reader.ReadContentAsBase64Async( buffer, index, count ).ConfigureAwait(false); if ( read == 0 ) { state = State.Interactive; ProcessNamespaces(); } return read; case State.ReadContentAsBinHex: case State.ReadElementContentAsBase64: case State.ReadElementContentAsBinHex: throw new InvalidOperationException( Res.GetString( Res.Xml_MixingBinaryContentMethods ) ); default: Debug.Assert( false ); return 0; } } public override async Task< int > ReadElementContentAsBase64Async( byte[] buffer, int index, int count ) { switch (state) { case State.Initial: case State.EndOfFile: case State.Closed: case State.Error: return 0; case State.Interactive: case State.PopNamespaceScope: case State.ClearNsAttributes: if ( !await InitReadElementContentAsBinaryAsync( State.ReadElementContentAsBase64 ).ConfigureAwait(false) ) { return 0; } goto case State.ReadElementContentAsBase64; case State.ReadElementContentAsBase64: int read = await reader.ReadContentAsBase64Async( buffer, index, count ).ConfigureAwait(false); if ( read > 0 || count == 0 ) { return read; } if ( NodeType != XmlNodeType.EndElement ) { throw new XmlException(Res.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo); } // pop namespace scope state = State.Interactive; ProcessNamespaces(); // set eof state or move off the end element if ( reader.Depth == initialDepth ) { state = State.EndOfFile; SetEmptyNode(); } else { await ReadAsync().ConfigureAwait(false); } return 0; case State.ReadContentAsBase64: case State.ReadContentAsBinHex: case State.ReadElementContentAsBinHex: throw new InvalidOperationException( Res.GetString( Res.Xml_MixingBinaryContentMethods ) ); default: Debug.Assert( false ); return 0; } } public override async Task< int > ReadContentAsBinHexAsync( byte[] buffer, int index, int count ) { switch (state) { case State.Initial: case State.EndOfFile: case State.Closed: case State.Error: return 0; case State.ClearNsAttributes: case State.PopNamespaceScope: switch ( NodeType ) { case XmlNodeType.Element: throw CreateReadContentAsException( "ReadContentAsBinHex" ); case XmlNodeType.EndElement: return 0; case XmlNodeType.Attribute: if (curNsAttr != -1 && reader.CanReadBinaryContent) { CheckBuffer( buffer, index, count ); if ( count == 0 ) { return 0; } if ( nsIncReadOffset == 0 ) { // called first time on this ns attribute if ( binDecoder != null && binDecoder is BinHexDecoder ) { binDecoder.Reset(); } else { binDecoder = new BinHexDecoder(); } } if ( nsIncReadOffset == curNode.value.Length ) { return 0; } binDecoder.SetNextOutputBuffer( buffer, index, count ); nsIncReadOffset += binDecoder.Decode( curNode.value, nsIncReadOffset, curNode.value.Length - nsIncReadOffset ); return binDecoder.DecodedCount; } goto case XmlNodeType.Text; case XmlNodeType.Text: Debug.Assert( AttributeCount > 0 ); return await reader.ReadContentAsBinHexAsync( buffer, index, count ).ConfigureAwait(false); default: Debug.Assert( false ); return 0; } case State.Interactive: state = State.ReadContentAsBinHex; goto case State.ReadContentAsBinHex; case State.ReadContentAsBinHex: int read = await reader.ReadContentAsBinHexAsync( buffer, index, count ).ConfigureAwait(false); if ( read == 0 ) { state = State.Interactive; ProcessNamespaces(); } return read; case State.ReadContentAsBase64: case State.ReadElementContentAsBase64: case State.ReadElementContentAsBinHex: throw new InvalidOperationException( Res.GetString( Res.Xml_MixingBinaryContentMethods ) ); default: Debug.Assert( false ); return 0; } } public override async Task< int > ReadElementContentAsBinHexAsync( byte[] buffer, int index, int count ) { switch (state) { case State.Initial: case State.EndOfFile: case State.Closed: case State.Error: return 0; case State.Interactive: case State.PopNamespaceScope: case State.ClearNsAttributes: if ( !await InitReadElementContentAsBinaryAsync( State.ReadElementContentAsBinHex ).ConfigureAwait(false) ) { return 0; } goto case State.ReadElementContentAsBinHex; case State.ReadElementContentAsBinHex: int read = await reader.ReadContentAsBinHexAsync( buffer, index, count ).ConfigureAwait(false); if ( read > 0 || count == 0 ) { return read; } if ( NodeType != XmlNodeType.EndElement ) { throw new XmlException(Res.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo); } // pop namespace scope state = State.Interactive; ProcessNamespaces(); // set eof state or move off the end element if ( reader.Depth == initialDepth ) { state = State.EndOfFile; SetEmptyNode(); } else { await ReadAsync().ConfigureAwait(false); } return 0; case State.ReadContentAsBase64: case State.ReadContentAsBinHex: case State.ReadElementContentAsBase64: throw new InvalidOperationException( Res.GetString( Res.Xml_MixingBinaryContentMethods ) ); default: Debug.Assert( false ); return 0; } } public override Task< int > ReadValueChunkAsync( char[] buffer, int index, int count ) { switch (state) { case State.Initial: case State.EndOfFile: case State.Closed: case State.Error: return Task.FromResult(0); case State.ClearNsAttributes: case State.PopNamespaceScope: // ReadValueChunk implementation on added xmlns attributes if (curNsAttr != -1 && reader.CanReadValueChunk) { CheckBuffer( buffer, index, count ); int copyCount = curNode.value.Length - nsIncReadOffset; if ( copyCount > count ) { copyCount = count; } if ( copyCount > 0 ) { curNode.value.CopyTo( nsIncReadOffset, buffer, index, copyCount ); } nsIncReadOffset += copyCount; return Task.FromResult(copyCount); } // Otherwise fall back to the case State.Interactive. // No need to clean ns attributes or pop scope because the reader when ReadValueChunk is called // - on Element errors // - on EndElement errors // - on Attribute does not move // and that's all where State.ClearNsAttributes or State.PopnamespaceScope can be set goto case State.Interactive; case State.Interactive: return reader.ReadValueChunkAsync(buffer, index, count); case State.ReadElementContentAsBase64: case State.ReadElementContentAsBinHex: case State.ReadContentAsBase64: case State.ReadContentAsBinHex: throw new InvalidOperationException( Res.GetString( Res.Xml_MixingReadValueChunkWithBinary ) ); default: Debug.Assert( false ); return Task.FromResult(0); } } private async Task< bool > InitReadElementContentAsBinaryAsync( State binaryState ) { if ( NodeType != XmlNodeType.Element ) { throw reader.CreateReadElementContentAsException( "ReadElementContentAsBase64" ); } bool isEmpty = IsEmptyElement; // move to content or off the empty element if ( !await ReadAsync().ConfigureAwait(false) || isEmpty ) { return false; } // special-case child element and end element switch ( NodeType ) { case XmlNodeType.Element: throw new XmlException(Res.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo); case XmlNodeType.EndElement: // pop scope & move off end element ProcessNamespaces(); await ReadAsync().ConfigureAwait(false); return false; } Debug.Assert( state == State.Interactive ); state = binaryState; return true; } private async Task< bool > FinishReadElementContentAsBinaryAsync() { Debug.Assert( state == State.ReadElementContentAsBase64 || state == State.ReadElementContentAsBinHex ); byte[] bytes = new byte[256]; if ( state == State.ReadElementContentAsBase64 ) { while ( await reader.ReadContentAsBase64Async( bytes, 0, 256 ).ConfigureAwait(false) > 0 ) ; } else { while ( await reader.ReadContentAsBinHexAsync( bytes, 0, 256 ).ConfigureAwait(false) > 0 ) ; } if ( NodeType != XmlNodeType.EndElement ) { throw new XmlException(Res.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo); } // pop namespace scope state = State.Interactive; ProcessNamespaces(); // check eof if ( reader.Depth == initialDepth ) { state = State.EndOfFile; SetEmptyNode(); return false; } // move off end element return await ReadAsync().ConfigureAwait(false); } private async Task< bool > FinishReadContentAsBinaryAsync() { Debug.Assert( state == State.ReadContentAsBase64 || state == State.ReadContentAsBinHex ); byte[] bytes = new byte[256]; if ( state == State.ReadContentAsBase64 ) { while ( await reader.ReadContentAsBase64Async( bytes, 0, 256 ).ConfigureAwait(false) > 0 ) ; } else { while ( await reader.ReadContentAsBinHexAsync( bytes, 0, 256 ).ConfigureAwait(false) > 0 ) ; } state = State.Interactive; ProcessNamespaces(); // check eof if ( reader.Depth == initialDepth ) { state = State.EndOfFile; SetEmptyNode(); return false; } return true; } } }
using AnimationOrTween; using System; using System.Collections.Generic; using UnityEngine; public abstract class UITweener : MonoBehaviour { public enum Method { Linear, EaseIn, EaseOut, EaseInOut, BounceIn, BounceOut } public enum Style { Once, Loop, PingPong } public static UITweener current; [HideInInspector] public UITweener.Method method; [HideInInspector] public UITweener.Style style; [HideInInspector] public AnimationCurve animationCurve = new AnimationCurve(new Keyframe[] { new Keyframe(0f, 0f, 0f, 1f), new Keyframe(1f, 1f, 1f, 0f) }); [HideInInspector] public bool ignoreTimeScale = true; [HideInInspector] public float delay; [HideInInspector] public float duration = 1f; [HideInInspector] public bool steeperCurves; [HideInInspector] public int tweenGroup; [HideInInspector] public List<EventDelegate> onFinished = new List<EventDelegate>(); [HideInInspector] public GameObject eventReceiver; [HideInInspector] public string callWhenFinished; private bool mStarted; private float mStartTime; private float mDuration; private float mAmountPerDelta = 1000f; private float mFactor; private List<EventDelegate> mTemp; public float amountPerDelta { get { if (this.mDuration != this.duration) { this.mDuration = this.duration; this.mAmountPerDelta = Mathf.Abs((this.duration <= 0f) ? 1000f : (1f / this.duration)); } return this.mAmountPerDelta; } } public float tweenFactor { get { return this.mFactor; } set { this.mFactor = Mathf.Clamp01(value); } } public Direction direction { get { return (this.mAmountPerDelta >= 0f) ? Direction.Forward : Direction.Reverse; } } private void Reset() { if (!this.mStarted) { this.SetStartToCurrentValue(); this.SetEndToCurrentValue(); } } protected virtual void Start() { this.Update(); } private void Update() { float num = (!this.ignoreTimeScale) ? Time.deltaTime : RealTime.deltaTime; float num2 = (!this.ignoreTimeScale) ? Time.time : RealTime.time; if (!this.mStarted) { this.mStarted = true; this.mStartTime = num2 + this.delay; } if (num2 < this.mStartTime) { return; } this.mFactor += this.amountPerDelta * num; if (this.style == UITweener.Style.Loop) { if (this.mFactor > 1f) { this.mFactor -= Mathf.Floor(this.mFactor); } } else if (this.style == UITweener.Style.PingPong) { if (this.mFactor > 1f) { this.mFactor = 1f - (this.mFactor - Mathf.Floor(this.mFactor)); this.mAmountPerDelta = -this.mAmountPerDelta; } else if (this.mFactor < 0f) { this.mFactor = -this.mFactor; this.mFactor -= Mathf.Floor(this.mFactor); this.mAmountPerDelta = -this.mAmountPerDelta; } } if (this.style == UITweener.Style.Once && (this.duration == 0f || this.mFactor > 1f || this.mFactor < 0f)) { this.mFactor = Mathf.Clamp01(this.mFactor); this.Sample(this.mFactor, true); if (this.duration == 0f || (this.mFactor == 1f && this.mAmountPerDelta > 0f) || (this.mFactor == 0f && this.mAmountPerDelta < 0f)) { base.enabled = false; } UITweener.current = this; if (this.onFinished != null) { this.mTemp = this.onFinished; this.onFinished = new List<EventDelegate>(); EventDelegate.Execute(this.mTemp); for (int i = 0; i < this.mTemp.Count; i++) { EventDelegate eventDelegate = this.mTemp[i]; if (eventDelegate != null) { EventDelegate.Add(this.onFinished, eventDelegate, eventDelegate.oneShot); } } this.mTemp = null; } if (this.eventReceiver != null && !string.IsNullOrEmpty(this.callWhenFinished)) { this.eventReceiver.SendMessage(this.callWhenFinished, this, SendMessageOptions.DontRequireReceiver); } UITweener.current = null; } else { this.Sample(this.mFactor, false); } } public void OnDestroy() { if (this.onFinished != null && this.onFinished.Count > 0) { this.onFinished.Clear(); } } public void SetOnFinished(EventDelegate.Callback del) { EventDelegate.Set(this.onFinished, del); } public void SetOnFinished(EventDelegate del) { EventDelegate.Set(this.onFinished, del); } public void AddOnFinished(EventDelegate.Callback del) { EventDelegate.Add(this.onFinished, del); } public void AddOnFinished(EventDelegate del) { EventDelegate.Add(this.onFinished, del); } public void RemoveOnFinished(EventDelegate del) { if (this.onFinished != null) { this.onFinished.Remove(del); } if (this.mTemp != null) { this.mTemp.Remove(del); } } private void OnDisable() { this.mStarted = false; } public void Sample(float factor, bool isFinished) { float num = Mathf.Clamp01(factor); if (this.method == UITweener.Method.EaseIn) { num = 1f - Mathf.Sin(1.57079637f * (1f - num)); if (this.steeperCurves) { num *= num; } } else if (this.method == UITweener.Method.EaseOut) { num = Mathf.Sin(1.57079637f * num); if (this.steeperCurves) { num = 1f - num; num = 1f - num * num; } } else if (this.method == UITweener.Method.EaseInOut) { num -= Mathf.Sin(num * 6.28318548f) / 6.28318548f; if (this.steeperCurves) { num = num * 2f - 1f; float num2 = Mathf.Sign(num); num = 1f - Mathf.Abs(num); num = 1f - num * num; num = num2 * num * 0.5f + 0.5f; } } else if (this.method == UITweener.Method.BounceIn) { num = this.BounceLogic(num); } else if (this.method == UITweener.Method.BounceOut) { num = 1f - this.BounceLogic(1f - num); } this.OnUpdate((this.animationCurve == null) ? num : this.animationCurve.Evaluate(num), isFinished); } private float BounceLogic(float val) { if (val < 0.363636f) { val = 7.5685f * val * val; } else if (val < 0.727272f) { val = 7.5625f * (val -= 0.545454f) * val + 0.75f; } else if (val < 0.90909f) { val = 7.5625f * (val -= 0.818181f) * val + 0.9375f; } else { val = 7.5625f * (val -= 0.9545454f) * val + 0.984375f; } return val; } [Obsolete("Use PlayForward() instead")] public void Play() { this.Play(true); } public void PlayForward() { this.Play(true); } public void PlayReverse() { this.Play(false); } public void Play(bool forward) { this.mAmountPerDelta = Mathf.Abs(this.amountPerDelta); if (!forward) { this.mAmountPerDelta = -this.mAmountPerDelta; } base.enabled = true; this.Update(); } public void ResetToBeginning() { this.mStarted = false; this.mFactor = ((this.mAmountPerDelta >= 0f) ? 0f : 1f); this.Sample(this.mFactor, false); } public void Toggle() { if (this.mFactor > 0f) { this.mAmountPerDelta = -this.amountPerDelta; } else { this.mAmountPerDelta = Mathf.Abs(this.amountPerDelta); } base.enabled = true; } protected abstract void OnUpdate(float factor, bool isFinished); public static T Begin<T>(GameObject go, float duration) where T : UITweener { T t = go.GetComponent<T>(); if (t != null && t.tweenGroup != 0) { t = (T)((object)null); T[] components = go.GetComponents<T>(); int i = 0; int num = components.Length; while (i < num) { t = components[i]; if (t != null && t.tweenGroup == 0) { break; } t = (T)((object)null); i++; } } if (t == null) { t = go.AddComponent<T>(); } t.mStarted = false; t.duration = duration; t.mFactor = 0f; t.mAmountPerDelta = Mathf.Abs(t.mAmountPerDelta); t.style = UITweener.Style.Once; t.animationCurve = new AnimationCurve(new Keyframe[] { new Keyframe(0f, 0f, 0f, 1f), new Keyframe(1f, 1f, 1f, 0f) }); t.eventReceiver = null; t.callWhenFinished = null; t.enabled = true; if (duration <= 0f) { t.Sample(1f, true); t.enabled = false; } return t; } public virtual void SetStartToCurrentValue() { } public virtual void SetEndToCurrentValue() { } }
//#define ASTAR_POOL_DEBUG //@SHOWINEDITOR Enables debugging of path pooling. Will log warnings and info messages about paths not beeing pooled correctly. using UnityEngine; using System.Collections; using System.Collections.Generic; namespace Pathfinding { /** Provides additional traversal information to a path request. * \see \ref turnbased */ public interface ITraversalProvider { bool CanTraverse (Path path, GraphNode node); uint GetTraversalCost (Path path, GraphNode node); } /** Base class for all path types */ public abstract class Path : IPathInternals { /** Data for the thread calculating this path */ protected PathHandler pathHandler; /** Callback to call when the path is complete. * This is usually sent to the Seeker component which post processes the path and then calls a callback to the script which requested the path */ public OnPathDelegate callback; /** Immediate callback to call when the path is complete. * \warning This may be called from a separate thread. Usually you do not want to use this one. * * \see callback */ public OnPathDelegate immediateCallback; /** Returns the state of the path in the pathfinding pipeline */ internal PathState PipelineState { get; private set; } System.Object stateLock = new object(); /** Provides additional traversal information to a path request. * \see \ref turnbased */ public ITraversalProvider traversalProvider; /** Current state of the path */ public PathCompleteState CompleteState { get; protected set; } /** If the path failed, this is true. * \see #errorLog */ public bool error { get { return CompleteState == PathCompleteState.Error; } } /** Additional info on what went wrong. * \see #error */ private string _errorLog = ""; /** Log messages with info about any errors. */ public string errorLog { get { return _errorLog; } } /** Holds the path as a Node array. All nodes the path traverses. * This may not be the same nodes as the post processed path traverses. */ public List<GraphNode> path; /** Holds the (possibly post processed) path as a Vector3 list */ public List<Vector3> vectorPath; /** The node currently being processed */ protected PathNode currentR; /** How long it took to calculate this path in milliseconds */ internal float duration; /** Number of nodes this path has searched */ protected int searchedNodes; /** True if the path is currently pooled. * Do not set this value. Only read. It is used internally. * * \see PathPool * \version Was named 'recycled' in 3.7.5 and earlier. */ bool IPathInternals.Pooled { get; set; } /** True if the path is currently recycled (i.e in the path pool). * Do not set this value. Only read. It is used internally. * * \deprecated Has been renamed to 'pooled' to use more widely underestood terminology */ [System.Obsolete("Has been renamed to 'Pooled' to use more widely underestood terminology", true)] internal bool recycled { get { return false; } } /** True if the Reset function has been called. * Used to alert users when they are doing something wrong. */ protected bool hasBeenReset; /** Constraint for how to search for nodes */ public NNConstraint nnConstraint = PathNNConstraint.Default; /** Internal linked list implementation. * \warning This is used internally by the system. You should never change this. */ internal Path next; /** Determines which heuristic to use */ public Heuristic heuristic; /** Scale of the heuristic values. * \see AstarPath.heuristicScale */ public float heuristicScale = 1F; /** ID of this path. Used to distinguish between different paths */ internal ushort pathID { get; private set; } /** Target to use for H score calculation. Used alongside #hTarget. */ protected GraphNode hTargetNode; /** Target to use for H score calculations. \see Pathfinding.Node.H */ protected Int3 hTarget; /** Which graph tags are traversable. * This is a bitmask so -1 = all bits set = all tags traversable. * For example, to set bit 5 to true, you would do * \code myPath.enabledTags |= 1 << 5; \endcode * To set it to false, you would do * \code myPath.enabledTags &= ~(1 << 5); \endcode * * The Seeker has a popup field where you can set which tags to use. * \note If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath. * So you need to change the Seeker value via script, not set this value if you want to change it via script. * * \see CanTraverse */ public int enabledTags = -1; /** List of zeroes to use as default tag penalties */ static readonly int[] ZeroTagPenalties = new int[32]; /** The tag penalties that are actually used. * If manualTagPenalties is null, this will be ZeroTagPenalties * \see tagPenalties */ protected int[] internalTagPenalties; /** Tag penalties set by other scripts * \see tagPenalties */ protected int[] manualTagPenalties; /** Penalties for each tag. * Tag 0 which is the default tag, will have added a penalty of tagPenalties[0]. * These should only be positive values since the A* algorithm cannot handle negative penalties. * \note This array will never be null. If you try to set it to null or with a length which is not 32. It will be set to "new int[0]". * * \note If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath. * So you need to change the Seeker value via script, not set this value if you want to change it via script. * * \see Seeker.tagPenalties */ public int[] tagPenalties { get { return manualTagPenalties; } set { if (value == null || value.Length != 32) { manualTagPenalties = null; internalTagPenalties = ZeroTagPenalties; } else { manualTagPenalties = value; internalTagPenalties = value; } } } /** True for paths that want to search all nodes and not jump over nodes as optimizations. * This disables Jump Point Search when that is enabled to prevent e.g ConstantPath and FloodPath * to become completely useless. */ internal virtual bool FloodingPath { get { return false; } } /** Total Length of the path. * Calculates the total length of the #vectorPath. * Cache this rather than call this function every time since it will calculate the length every time, not just return a cached value. * \returns Total length of #vectorPath, if #vectorPath is null positive infinity is returned. */ public float GetTotalLength () { if (vectorPath == null) return float.PositiveInfinity; float tot = 0; for (int i = 0; i < vectorPath.Count-1; i++) tot += Vector3.Distance(vectorPath[i], vectorPath[i+1]); return tot; } /** Waits until this path has been calculated and returned. * Allows for very easy scripting. * \code * IEnumerator Start () { * var path = seeker.StartPath (transform.position, transform.position+transform.forward*10, OnPathComplete); * yield return StartCoroutine (path.WaitForPath()); * // The path is calculated no * } * \endcode * * \note Do not confuse this with AstarPath.WaitForPath. This one will wait using yield until it has been calculated * while AstarPath.WaitForPath will halt all operations until the path has been calculated. * * \throws System.InvalidOperationException if the path is not started. Send the path to Seeker.StartPath or AstarPath.StartPath before calling this function. * * \see BlockUntilCalculated */ public IEnumerator WaitForPath () { if (PipelineState == PathState.Created) throw new System.InvalidOperationException("This path has not been started yet"); while (PipelineState != PathState.Returned) yield return null; } /** Blocks until this path has been calculated and returned. * Normally it takes a few frames for a path to be calculated and returned. * This function will ensure that the path will be calculated when this function returns * and that the callback for that path has been called. * * Use this function only if you really need to. * There is a point to spreading path calculations out over several frames. * It smoothes out the framerate and makes sure requesting a large * number of paths at the same time does not cause lag. * * \note Graph updates and other callbacks might get called during the execution of this function. * * \code * Path p = seeker.StartPath (transform.position, transform.position + Vector3.forward * 10); * p.BlockUntilCalculated(); * // The path is calculated now * \endcode * * \see This is equivalent to calling AstarPath.BlockUntilCalculated(Path) * \see WaitForPath */ public void BlockUntilCalculated () { AstarPath.BlockUntilCalculated(this); } /** Estimated cost from the specified node to the target. * \see https://en.wikipedia.org/wiki/A*_search_algorithm */ internal uint CalculateHScore (GraphNode node) { uint h; switch (heuristic) { case Heuristic.Euclidean: h = (uint)(((GetHTarget() - node.position).costMagnitude)*heuristicScale); return h; case Heuristic.Manhattan: Int3 p2 = node.position; h = (uint)((System.Math.Abs(hTarget.x-p2.x) + System.Math.Abs(hTarget.y-p2.y) + System.Math.Abs(hTarget.z-p2.z))*heuristicScale); return h; case Heuristic.DiagonalManhattan: Int3 p = GetHTarget() - node.position; p.x = System.Math.Abs(p.x); p.y = System.Math.Abs(p.y); p.z = System.Math.Abs(p.z); int diag = System.Math.Min(p.x, p.z); int diag2 = System.Math.Max(p.x, p.z); h = (uint)((((14*diag)/10) + (diag2-diag) + p.y) * heuristicScale); return h; } return 0U; } /** Returns penalty for the given tag. * \param tag A value between 0 (inclusive) and 32 (exclusive). */ internal uint GetTagPenalty (int tag) { return (uint)internalTagPenalties[tag]; } internal Int3 GetHTarget () { return hTarget; } /** Returns if the node can be traversed. * This per default equals to if the node is walkable and if the node's tag is included in #enabledTags */ internal bool CanTraverse (GraphNode node) { // Use traversal provider if set, otherwise fall back on default behaviour // This method is hot, but this branch is extremely well predicted so it // doesn't affect performance much (profiling indicates it is just above // the noise level, somewhere around 0%-0.3%) if (traversalProvider != null) return traversalProvider.CanTraverse(this, node); unchecked { return node.Walkable && (enabledTags >> (int)node.Tag & 0x1) != 0; } } internal uint GetTraversalCost (GraphNode node) { #if ASTAR_NO_TRAVERSAL_COST return 0; #else // Use traversal provider if set, otherwise fall back on default behaviour if (traversalProvider != null) return traversalProvider.GetTraversalCost(this, node); unchecked { return GetTagPenalty((int)node.Tag) + node.Penalty; } #endif } /** May be called by graph nodes to get a special cost for some connections. * Nodes may call it when PathNode.flag2 is set to true, for example mesh nodes, which have * a very large area can be marked on the start and end nodes, this method will be called * to get the actual cost for moving from the start position to its neighbours instead * of as would otherwise be the case, from the start node's position to its neighbours. * The position of a node and the actual start point on the node can vary quite a lot. * * The default behaviour of this method is to return the previous cost of the connection, * essentiall making no change at all. * * This method should return the same regardless of the order of a and b. * That is f(a,b) == f(b,a) should hold. * * \param a Moving from this node * \param b Moving to this node * \param currentCost The cost of moving between the nodes. Return this value if there is no meaningful special cost to return. */ internal virtual uint GetConnectionSpecialCost (GraphNode a, GraphNode b, uint currentCost) { return currentCost; } /** Returns if this path is done calculating. * \returns If CompleteState is not PathCompleteState.NotCalculated. * * \note The callback for the path might not have been called yet. * * \since Added in 3.0.8 * * \see Seeker.IsDone */ public bool IsDone () { return CompleteState != PathCompleteState.NotCalculated; } /** Threadsafe increment of the state */ void IPathInternals.AdvanceState (PathState s) { lock (stateLock) { PipelineState = (PathState)System.Math.Max((int)PipelineState, (int)s); } } /** Returns the state of the path in the pathfinding pipeline. * \deprecated Use the #Pathfinding.Path.PipelineState property instead */ [System.Obsolete("Use the 'PipelineState' property instead")] public PathState GetState () { return PipelineState; } /** Appends \a msg to #errorLog and logs \a msg to the console. * Debug.Log call is only made if AstarPath.logPathResults is not equal to None and not equal to InGame. * Consider calling Error() along with this call. */ // Ugly Code Inc. wrote the below code :D // What it does is that it disables the LogError function if ASTAR_NO_LOGGING is enabled // since the DISABLED define will never be enabled // Ugly way of writing Conditional("!ASTAR_NO_LOGGING") internal void LogError (string msg) { #if !UNITY_EDITOR // Optimize for release builds // If no path logging is enabled // don't append to the error log string // to reduce allocations if (AstarPath.active.logPathResults != PathLog.None) { _errorLog += msg; } #else _errorLog += msg; #endif if (AstarPath.active.logPathResults != PathLog.None && AstarPath.active.logPathResults != PathLog.InGame) { Debug.LogWarning(msg); } } /** Logs an error and calls Error(). * This is called only if something is very wrong or the user is doing something he/she really should not be doing. */ internal void ForceLogError (string msg) { Error(); _errorLog += msg; Debug.LogError(msg); } /** Appends a message to the #errorLog. * Nothing is logged to the console. * * \note If AstarPath.logPathResults is PathLog.None and this is a standalone player, nothing will be logged as an optimization. */ internal void Log (string msg) { #if !UNITY_EDITOR // Optimize for release builds // If no path logging is enabled // don't append to the error log string // to reduce allocations if (AstarPath.active.logPathResults != PathLog.None) { _errorLog += msg; } #endif } /** Aborts the path because of an error. * Sets #error to true. * This function is called when an error has ocurred (e.g a valid path could not be found). * \see LogError */ public void Error () { CompleteState = PathCompleteState.Error; } /** Does some error checking. * Makes sure the user isn't using old code paths and that no major errors have been done. * * \throws An exception if any errors are found */ private void ErrorCheck () { if (!hasBeenReset) throw new System.Exception("The path has never been reset. Use the static Construct call, do not use the normal constructors."); if (((IPathInternals)this).Pooled) throw new System.Exception("The path is currently in a path pool. Are you sending the path for calculation twice?"); if (pathHandler == null) throw new System.Exception("Field pathHandler is not set. Please report this bug."); if (PipelineState > PathState.Processing) throw new System.Exception("This path has already been processed. Do not request a path with the same path object twice."); } /** Called when the path enters the pool. * This method should release e.g pooled lists and other pooled resources * The base version of this method releases vectorPath and path lists. * Reset() will be called after this function, not before. * \warning Do not call this function manually. */ protected virtual void OnEnterPool () { if (vectorPath != null) Pathfinding.Util.ListPool<Vector3>.Release(vectorPath); if (path != null) Pathfinding.Util.ListPool<GraphNode>.Release(path); vectorPath = null; path = null; // Clear the callback to remove a potential memory leak // while the path is in the pool (which it could be for a long time). callback = null; immediateCallback = null; traversalProvider = null; } /** Reset all values to their default values. * * \note All inheriting path types (e.g ConstantPath, RandomPath, etc.) which declare their own variables need to * override this function, resetting ALL their variables to enable pooling of paths. * If this is not done, trying to use that path type for pooling could result in weird behaviour. * The best way is to reset to default values the variables declared in the extended path type and then * call the base function in inheriting types with base.Reset(). */ protected virtual void Reset () { if (System.Object.ReferenceEquals(AstarPath.active, null)) throw new System.NullReferenceException("No AstarPath object found in the scene. " + "Make sure there is one or do not create paths in Awake"); hasBeenReset = true; PipelineState = (int)PathState.Created; releasedNotSilent = false; pathHandler = null; callback = null; immediateCallback = null; _errorLog = ""; CompleteState = PathCompleteState.NotCalculated; path = Pathfinding.Util.ListPool<GraphNode>.Claim(); vectorPath = Pathfinding.Util.ListPool<Vector3>.Claim(); currentR = null; duration = 0; searchedNodes = 0; nnConstraint = PathNNConstraint.Default; next = null; heuristic = AstarPath.active.heuristic; heuristicScale = AstarPath.active.heuristicScale; enabledTags = -1; tagPenalties = null; pathID = AstarPath.active.GetNextPathID(); hTarget = Int3.zero; hTargetNode = null; traversalProvider = null; } /** List of claims on this path with reference objects */ private List<System.Object> claimed = new List<System.Object>(); /** True if the path has been released with a non-silent call yet. * * \see Release * \see Claim */ private bool releasedNotSilent; /** Claim this path (pooling). * A claim on a path will ensure that it is not pooled. * If you are using a path, you will want to claim it when you first get it and then release it when you will not * use it anymore. When there are no claims on the path, it will be reset and put in a pool. * * This is essentially just reference counting. * * The object passed to this method is merely used as a way to more easily detect when pooling is not done correctly. * It can be any object, when used from a movement script you can just pass "this". This class will throw an exception * if you try to call Claim on the same path twice with the same object (which is usually not what you want) or * if you try to call Release with an object that has not been used in a Claim call for that path. * The object passed to the Claim method needs to be the same as the one you pass to this method. * * \see Release * \see Pool * \see \ref pooling * \see https://en.wikipedia.org/wiki/Reference_counting */ public void Claim (System.Object o) { if (System.Object.ReferenceEquals(o, null)) throw new System.ArgumentNullException("o"); for (int i = 0; i < claimed.Count; i++) { // Need to use ReferenceEquals because it might be called from another thread if (System.Object.ReferenceEquals(claimed[i], o)) throw new System.ArgumentException("You have already claimed the path with that object ("+o+"). Are you claiming the path with the same object twice?"); } claimed.Add(o); } /** Releases the path silently (pooling). * \deprecated Use Release(o, true) instead */ [System.Obsolete("Use Release(o, true) instead")] internal void ReleaseSilent (System.Object o) { Release(o, true); } /** Releases a path claim (pooling). * Removes the claim of the path by the specified object. * When the claim count reaches zero, the path will be pooled, all variables will be cleared and the path will be put in a pool to be used again. * This is great for memory since less allocations are made. * * If the silent parameter is true, this method will remove the claim by the specified object * but the path will not be pooled if the claim count reches zero unless a Release call (not silent) has been made earlier. * This is used by the internal pathfinding components such as Seeker and AstarPath so that they will not cause paths to be pooled. * This enables users to skip the claim/release calls if they want without the path being pooled by the Seeker or AstarPath and * thus causing strange bugs. * * \see Claim * \see PathPool */ public void Release (System.Object o, bool silent = false) { if (o == null) throw new System.ArgumentNullException("o"); for (int i = 0; i < claimed.Count; i++) { // Need to use ReferenceEquals because it might be called from another thread if (System.Object.ReferenceEquals(claimed[i], o)) { claimed.RemoveAt(i); if (!silent) { releasedNotSilent = true; } if (claimed.Count == 0 && releasedNotSilent) { PathPool.Pool(this); } return; } } if (claimed.Count == 0) { throw new System.ArgumentException("You are releasing a path which is not claimed at all (most likely it has been pooled already). " + "Are you releasing the path with the same object ("+o+") twice?" + "\nCheck out the documentation on path pooling for help."); } throw new System.ArgumentException("You are releasing a path which has not been claimed with this object ("+o+"). " + "Are you releasing the path with the same object twice?\n" + "Check out the documentation on path pooling for help."); } /** Traces the calculated path from the end node to the start. * This will build an array (#path) of the nodes this path will pass through and also set the #vectorPath array to the #path arrays positions. * Assumes the #vectorPath and #path are empty and not null (which will be the case for a correctly initialized path). */ protected virtual void Trace (PathNode from) { // Current node we are processing PathNode c = from; int count = 0; while (c != null) { c = c.parent; count++; if (count > 2048) { Debug.LogWarning("Infinite loop? >2048 node path. Remove this message if you really have that long paths (Path.cs, Trace method)"); break; } } // Ensure capacities for lists AstarProfiler.StartProfile("Check List Capacities"); if (path.Capacity < count) path.Capacity = count; if (vectorPath.Capacity < count) vectorPath.Capacity = count; AstarProfiler.EndProfile(); c = from; for (int i = 0; i < count; i++) { path.Add(c.node); c = c.parent; } // Reverse int half = count/2; for (int i = 0; i < half; i++) { var tmp = path[i]; path[i] = path[count-i-1]; path[count - i - 1] = tmp; } for (int i = 0; i < count; i++) { vectorPath.Add((Vector3)path[i].position); } } /** Writes text shared for all overrides of DebugString to the string builder. * \see DebugString */ protected void DebugStringPrefix (PathLog logMode, System.Text.StringBuilder text) { text.Append(error ? "Path Failed : " : "Path Completed : "); text.Append("Computation Time "); text.Append(duration.ToString(logMode == PathLog.Heavy ? "0.000 ms " : "0.00 ms ")); text.Append("Searched Nodes ").Append(searchedNodes); if (!error) { text.Append(" Path Length "); text.Append(path == null ? "Null" : path.Count.ToString()); } } /** Writes text shared for all overrides of DebugString to the string builder. * \see DebugString */ protected void DebugStringSuffix (PathLog logMode, System.Text.StringBuilder text) { if (error) { text.Append("\nError: ").Append(errorLog); } // Can only print this from the Unity thread // since otherwise an exception might be thrown if (logMode == PathLog.Heavy && !AstarPath.active.IsUsingMultithreading) { text.Append("\nCallback references "); if (callback != null) text.Append(callback.Target.GetType().FullName).AppendLine(); else text.AppendLine("NULL"); } text.Append("\nPath Number ").Append(pathID).Append(" (unique id)"); } /** Returns a string with information about it. * More information is emitted when logMode == Heavy. * An empty string is returned if logMode == None * or logMode == OnlyErrors and this path did not fail. */ internal virtual string DebugString (PathLog logMode) { if (logMode == PathLog.None || (!error && logMode == PathLog.OnlyErrors)) { return ""; } // Get a cached string builder for this thread System.Text.StringBuilder text = pathHandler.DebugStringBuilder; text.Length = 0; DebugStringPrefix(logMode, text); DebugStringSuffix(logMode, text); return text.ToString(); } /** Calls callback to return the calculated path. \see #callback */ protected virtual void ReturnPath () { if (callback != null) { callback(this); } } /** Prepares low level path variables for calculation. * Called before a path search will take place. * Always called before the Prepare, Initialize and CalculateStep functions */ protected void PrepareBase (PathHandler pathHandler) { //Path IDs have overflowed 65K, cleanup is needed //Since pathIDs are handed out sequentially, we can do this if (pathHandler.PathID > pathID) { pathHandler.ClearPathIDs(); } //Make sure the path has a reference to the pathHandler this.pathHandler = pathHandler; //Assign relevant path data to the pathHandler pathHandler.InitializeForPath(this); // Make sure that internalTagPenalties is an array which has the length 32 if (internalTagPenalties == null || internalTagPenalties.Length != 32) internalTagPenalties = ZeroTagPenalties; try { ErrorCheck(); } catch (System.Exception e) { ForceLogError("Exception in path "+pathID+"\n"+e); } } /** Called before the path is started. * Called right before Initialize */ protected abstract void Prepare (); /** Always called after the path has been calculated. * Guaranteed to be called before other paths have been calculated on * the same thread. * Use for cleaning up things like node tagging and similar. */ protected virtual void Cleanup () {} /** Initializes the path. * Sets up the open list and adds the first node to it */ protected abstract void Initialize (); /** Calculates the until it is complete or the time has progressed past \a targetTick */ protected abstract void CalculateStep (long targetTick); PathHandler IPathInternals.PathHandler { get { return pathHandler; } } void IPathInternals.OnEnterPool () { OnEnterPool(); } void IPathInternals.Reset () { Reset(); } void IPathInternals.ReturnPath () { ReturnPath(); } void IPathInternals.PrepareBase (PathHandler handler) { PrepareBase(handler); } void IPathInternals.Prepare () { Prepare(); } void IPathInternals.Cleanup () { Cleanup(); } void IPathInternals.Initialize () { Initialize(); } void IPathInternals.CalculateStep (long targetTick) { CalculateStep(targetTick); } } /** Used for hiding internal methods of the Path class */ internal interface IPathInternals { PathHandler PathHandler { get; } bool Pooled { get; set; } void AdvanceState (PathState s); void OnEnterPool (); void Reset (); void ReturnPath (); void PrepareBase (PathHandler handler); void Prepare (); void Initialize (); void Cleanup (); void CalculateStep (long targetTick); } }
// dnlib: See LICENSE.txt for more info using System; using System.Reflection; using dnlib.DotNet.Writer; namespace dnlib.DotNet { /// <summary> /// <see cref="ILogger"/> events /// </summary> public enum LoggerEvent { /// <summary> /// An error was detected. An exception should normally be thrown but the error /// can be ignored. /// </summary> Error, /// <summary> /// Just a warning and can be ignored. /// </summary> Warning, /// <summary> /// A normal message /// </summary> Info, /// <summary> /// A verbose message /// </summary> Verbose, /// <summary> /// A very verbose message /// </summary> VeryVerbose, } /// <summary> /// Simple logger /// </summary> public interface ILogger { /// <summary> /// Log something /// </summary> /// <param name="sender">Caller or <c>null</c></param> /// <param name="loggerEvent">Logger event</param> /// <param name="format">Format</param> /// <param name="args">Arguments</param> void Log(object sender, LoggerEvent loggerEvent, string format, params object[] args); /// <summary> /// <c>true</c> if this event is ignored. If the event is ignored, the caller can /// choose not to call <see cref="Log"/>. This is useful if it can take time to /// prepare the message. /// </summary> /// <param name="loggerEvent">The logger event</param> bool IgnoresEvent(LoggerEvent loggerEvent); } public static partial class Extensions { /// <summary> /// Log an error message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> public static void Error(this ILogger logger, object sender, string message) => logger.Log(sender, LoggerEvent.Error, "{0}", message); /// <summary> /// Log an error message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> public static void Error(this ILogger logger, object sender, string message, object arg1) => logger.Log(sender, LoggerEvent.Error, message, arg1); /// <summary> /// Log an error message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> public static void Error(this ILogger logger, object sender, string message, object arg1, object arg2) => logger.Log(sender, LoggerEvent.Error, message, arg1, arg2); /// <summary> /// Log an error message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> public static void Error(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3) => logger.Log(sender, LoggerEvent.Error, message, arg1, arg2, arg3); /// <summary> /// Log an error message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> /// <param name="arg4">Message arg #4</param> public static void Error(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3, object arg4) => logger.Log(sender, LoggerEvent.Error, message, arg1, arg2, arg3, arg4); /// <summary> /// Log an error message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="args">Message arguments</param> public static void Error(this ILogger logger, object sender, string message, params object[] args) => logger.Log(sender, LoggerEvent.Error, message, args); /// <summary> /// Log a warning message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> public static void Warning(this ILogger logger, object sender, string message) => logger.Log(sender, LoggerEvent.Warning, "{0}", message); /// <summary> /// Log a warning message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> public static void Warning(this ILogger logger, object sender, string message, object arg1) => logger.Log(sender, LoggerEvent.Warning, message, arg1); /// <summary> /// Log a warning message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> public static void Warning(this ILogger logger, object sender, string message, object arg1, object arg2) => logger.Log(sender, LoggerEvent.Warning, message, arg1, arg2); /// <summary> /// Log a warning message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> public static void Warning(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3) => logger.Log(sender, LoggerEvent.Warning, message, arg1, arg2, arg3); /// <summary> /// Log a warning message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> /// <param name="arg4">Message arg #4</param> public static void Warning(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3, object arg4) => logger.Log(sender, LoggerEvent.Warning, message, arg1, arg2, arg3, arg4); /// <summary> /// Log a warning message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="args">Message arguments</param> public static void Warning(this ILogger logger, object sender, string message, params object[] args) => logger.Log(sender, LoggerEvent.Warning, message, args); /// <summary> /// Log an info message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> public static void Info(this ILogger logger, object sender, string message) => logger.Log(sender, LoggerEvent.Info, "{0}", message); /// <summary> /// Log an info message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> public static void Info(this ILogger logger, object sender, string message, object arg1) => logger.Log(sender, LoggerEvent.Info, message, arg1); /// <summary> /// Log an info message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> public static void Info(this ILogger logger, object sender, string message, object arg1, object arg2) => logger.Log(sender, LoggerEvent.Info, message, arg1, arg2); /// <summary> /// Log an info message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> public static void Info(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3) => logger.Log(sender, LoggerEvent.Info, message, arg1, arg2, arg3); /// <summary> /// Log an info message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> /// <param name="arg4">Message arg #4</param> public static void Info(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3, object arg4) => logger.Log(sender, LoggerEvent.Info, message, arg1, arg2, arg3, arg4); /// <summary> /// Log an info message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="args">Message arguments</param> public static void Info(this ILogger logger, object sender, string message, params object[] args) => logger.Log(sender, LoggerEvent.Info, message, args); /// <summary> /// Log a verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> public static void Verbose(this ILogger logger, object sender, string message) => logger.Log(sender, LoggerEvent.Verbose, "{0}", message); /// <summary> /// Log a verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> public static void Verbose(this ILogger logger, object sender, string message, object arg1) => logger.Log(sender, LoggerEvent.Verbose, message, arg1); /// <summary> /// Log a verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> public static void Verbose(this ILogger logger, object sender, string message, object arg1, object arg2) => logger.Log(sender, LoggerEvent.Verbose, message, arg1, arg2); /// <summary> /// Log a verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> public static void Verbose(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3) => logger.Log(sender, LoggerEvent.Verbose, message, arg1, arg2, arg3); /// <summary> /// Log a verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> /// <param name="arg4">Message arg #4</param> public static void Verbose(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3, object arg4) => logger.Log(sender, LoggerEvent.Verbose, message, arg1, arg2, arg3, arg4); /// <summary> /// Log a verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="args">Message arguments</param> public static void Verbose(this ILogger logger, object sender, string message, params object[] args) => logger.Log(sender, LoggerEvent.Verbose, message, args); /// <summary> /// Log a very verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> public static void VeryVerbose(this ILogger logger, object sender, string message) => logger.Log(sender, LoggerEvent.VeryVerbose, "{0}", message); /// <summary> /// Log a very verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> public static void VeryVerbose(this ILogger logger, object sender, string message, object arg1) => logger.Log(sender, LoggerEvent.VeryVerbose, message, arg1); /// <summary> /// Log a very verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> public static void VeryVerbose(this ILogger logger, object sender, string message, object arg1, object arg2) => logger.Log(sender, LoggerEvent.VeryVerbose, message, arg1, arg2); /// <summary> /// Log a very verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> public static void VeryVerbose(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3) => logger.Log(sender, LoggerEvent.VeryVerbose, message, arg1, arg2, arg3); /// <summary> /// Log a very verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> /// <param name="arg4">Message arg #4</param> public static void VeryVerbose(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3, object arg4) => logger.Log(sender, LoggerEvent.VeryVerbose, message, arg1, arg2, arg3, arg4); /// <summary> /// Log a very verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="args">Message arguments</param> public static void VeryVerbose(this ILogger logger, object sender, string message, params object[] args) => logger.Log(sender, LoggerEvent.VeryVerbose, message, args); } /// <summary> /// Dummy logger which ignores all messages, but can optionally throw on errors. /// </summary> public sealed class DummyLogger : ILogger { ConstructorInfo ctor; /// <summary> /// It ignores everything and doesn't throw anything. /// </summary> public static readonly DummyLogger NoThrowInstance = new DummyLogger(); /// <summary> /// Throws a <see cref="ModuleWriterException"/> on errors, but ignores anything else. /// </summary> public static readonly DummyLogger ThrowModuleWriterExceptionOnErrorInstance = new DummyLogger(typeof(ModuleWriterException)); DummyLogger() { } /// <summary> /// Constructor /// </summary> /// <param name="exceptionToThrow">If non-<c>null</c>, this exception type is thrown on /// errors. It must have a public constructor that takes a <see cref="string"/> as the only /// argument.</param> public DummyLogger(Type exceptionToThrow) { if (exceptionToThrow is not null) { if (!exceptionToThrow.IsSubclassOf(typeof(Exception))) throw new ArgumentException($"Not a System.Exception sub class: {exceptionToThrow.GetType()}"); ctor = exceptionToThrow.GetConstructor(new Type[] { typeof(string) }); if (ctor is null) throw new ArgumentException($"Exception type {exceptionToThrow.GetType()} doesn't have a public constructor that takes a string as the only argument"); } } /// <inheritdoc/> public void Log(object sender, LoggerEvent loggerEvent, string format, params object[] args) { if (loggerEvent == LoggerEvent.Error && ctor is not null) throw (Exception)ctor.Invoke(new object[] { string.Format(format, args) }); } /// <inheritdoc/> public bool IgnoresEvent(LoggerEvent loggerEvent) { if (ctor is null) return true; return loggerEvent != LoggerEvent.Error; } } }
// 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; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using Internal.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { #region ConditionalWeakTable public sealed class ConditionalWeakTable<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>> where TKey : class where TValue : class { #region Constructors public ConditionalWeakTable() { _container = new Container(this); _lock = new Lock(); } #endregion #region Public Members //-------------------------------------------------------------------------------------------- // key: key of the value to find. Cannot be null. // value: if the key is found, contains the value associated with the key upon method return. // if the key is not found, contains default(TValue). // // Method returns "true" if key was found, "false" otherwise. // // Note: The key may get garbaged collected during the TryGetValue operation. If so, TryGetValue // may at its discretion, return "false" and set "value" to the default (as if the key was not present.) //-------------------------------------------------------------------------------------------- public bool TryGetValue(TKey key, out TValue value) { if (key == null) { throw new ArgumentNullException(nameof(key)); } return _container.TryGetValueWorker(key, out value); } //-------------------------------------------------------------------------------------------- // key: key to add. May not be null. // value: value to associate with key. // // If the key is already entered into the dictionary, this method throws an exception. // // Note: The key may get garbage collected during the Add() operation. If so, Add() // has the right to consider any prior entries successfully removed and add a new entry without // throwing an exception. //-------------------------------------------------------------------------------------------- public void Add(TKey key, TValue value) { if (key == null) { throw new ArgumentNullException(nameof(key)); } using (LockHolder.Hold(_lock)) { object otherValue; int entryIndex = _container.FindEntry(key, out otherValue); if (entryIndex != -1) { throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key)); } CreateEntry(key, value); } } //-------------------------------------------------------------------------------------------- // key: key to add or update. May not be null. // value: value to associate with key. // // If the key is already entered into the dictionary, this method will update the value associated with key. //-------------------------------------------------------------------------------------------- public void AddOrUpdate(TKey key, TValue value) { if (key == null) { throw new ArgumentNullException(nameof(key)); } using (LockHolder.Hold(_lock)) { object otherValue; int entryIndex = _container.FindEntry(key, out otherValue); // if we found a key we should just update, if no we should create a new entry. if (entryIndex != -1) { _container.UpdateValue(entryIndex, value); } else { CreateEntry(key, value); } } } //-------------------------------------------------------------------------------------------- // key: key to remove. May not be null. // // Returns true if the key is found and removed. Returns false if the key was not in the dictionary. // // Note: The key may get garbage collected during the Remove() operation. If so, // Remove() will not fail or throw, however, the return value can be either true or false // depending on who wins the race. //-------------------------------------------------------------------------------------------- public bool Remove(TKey key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } using (LockHolder.Hold(_lock)) { return _container.Remove(key); } } //-------------------------------------------------------------------------------------------- // Clear all the key/value pairs //-------------------------------------------------------------------------------------------- public void Clear() { using (LockHolder.Hold(_lock)) { // To clear, we would prefer to simply drop the existing container // and replace it with an empty one, as that's overall more efficient. // However, if there are any active enumerators, we don't want to do // that as it will end up removing all of the existing entries and // allowing new items to be added at the same indices when the container // is filled and replaced, and one of the guarantees we try to make with // enumeration is that new items added after enumeration starts won't be // included in the enumeration. As such, if there are active enumerators, // we simply use the container's removal functionality to remove all of the // keys; then when the table is resized, if there are still active enumerators, // these empty slots will be maintained. if (_activeEnumeratorRefCount > 0) { _container.RemoveAllKeys(); } else { _container = new Container(this); } } } //-------------------------------------------------------------------------------------------- // key: key of the value to find. Cannot be null. // createValueCallback: callback that creates value for key. Cannot be null. // // Atomically tests if key exists in table. If so, returns corresponding value. If not, // invokes createValueCallback() passing it the key. The returned value is bound to the key in the table // and returned as the result of GetValue(). // // If multiple threads race to initialize the same key, the table may invoke createValueCallback // multiple times with the same key. Exactly one of these calls will "win the race" and the returned // value of that call will be the one added to the table and returned by all the racing GetValue() calls. // // This rule permits the table to invoke createValueCallback outside the internal table lock // to prevent deadlocks. //-------------------------------------------------------------------------------------------- public TValue GetValue(TKey key, CreateValueCallback createValueCallback) { // Our call to TryGetValue() validates key so no need for us to. // // if (key == null) // { // ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); // } if (createValueCallback == null) { throw new ArgumentNullException(nameof(createValueCallback)); } TValue existingValue; if (TryGetValue(key, out existingValue)) { return existingValue; } return GetValueLocked(key, createValueCallback); } private TValue GetValueLocked(TKey key, CreateValueCallback createValueCallback) { // If we got here, the key was not in the table. Invoke the callback (outside the lock) // to generate the new value for the key. TValue newValue = createValueCallback(key); using (LockHolder.Hold(_lock)) { // Now that we've taken the lock, must recheck in case we lost a race to add the key. TValue existingValue; if (_container.TryGetValueWorker(key, out existingValue)) { return existingValue; } else { // Verified in-lock that we won the race to add the key. Add it now. CreateEntry(key, newValue); return newValue; } } } //-------------------------------------------------------------------------------------------- // key: key of the value to find. Cannot be null. // // Helper method to call GetValue without passing a creation delegate. Uses Activator.CreateInstance // to create new instances as needed. If TValue does not have a default constructor, this will // throw. //-------------------------------------------------------------------------------------------- public TValue GetOrCreateValue(TKey key) { return GetValue(key, k => Activator.CreateInstance<TValue>()); } public delegate TValue CreateValueCallback(TKey key); //-------------------------------------------------------------------------------------------- // Gets an enumerator for the table. The returned enumerator will not extend the lifetime of // any object pairs in the table, other than the one that's Current. It will not return entries // that have already been collected, nor will it return entries added after the enumerator was // retrieved. It may not return all entries that were present when the enumerat was retrieved, // however, such as not returning entries that were collected or removed after the enumerator // was retrieved but before they were enumerated. //-------------------------------------------------------------------------------------------- IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { using (LockHolder.Hold(_lock)) { Container c = _container; return c == null || c.FirstFreeEntry == 0 ? ((IEnumerable<KeyValuePair<TKey, TValue>>)Array.Empty<KeyValuePair<TKey, TValue>>()).GetEnumerator() : new Enumerator(this); } } IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<KeyValuePair<TKey, TValue>>)this).GetEnumerator(); /// <summary>Provides an enumerator for the table.</summary> private sealed class Enumerator : IEnumerator<KeyValuePair<TKey, TValue>> { // The enumerator would ideally hold a reference to the Container and the end index within that // container. However, the safety of the CWT depends on the only reference to the Container being // from the CWT itself; the Container then employs a two-phase finalization scheme, where the first // phase nulls out that parent CWT's reference, guaranteeing that the second time it's finalized there // can be no other existing references to it in use that would allow for concurrent usage of the // native handles with finalization. We would break that if we allowed this Enumerator to hold a // reference to the Container. Instead, the Enumerator holds a reference to the CWT rather than to // the Container, and it maintains the CWT._activeEnumeratorRefCount field to track whether there // are outstanding enumerators that have yet to be disposed/finalized. If there aren't any, the CWT // behaves as it normally does. If there are, certain operations are affected, in particular resizes. // Normally when the CWT is resized, it enumerates the contents of the table looking for indices that // contain entries which have been collected or removed, and it frees those up, effectively moving // down all subsequent entries in the container (not in the existing container, but in a replacement). // This, however, would cause the enumerator's understanding of indices to break. So, as long as // there is any outstanding enumerator, no compaction is performed. private ConditionalWeakTable<TKey, TValue> _table; // parent table, set to null when disposed private readonly int _maxIndexInclusive; // last index in the container that should be enumerated private int _currentIndex = -1; // the current index into the container private KeyValuePair<TKey, TValue> _current; // the current entry set by MoveNext and returned from Current public Enumerator(ConditionalWeakTable<TKey, TValue> table) { Debug.Assert(table != null, "Must provide a valid table"); Debug.Assert(table._lock.IsAcquired, "Must hold the _lock lock to construct the enumerator"); Debug.Assert(table._container != null, "Should not be used on a finalized table"); Debug.Assert(table._container.FirstFreeEntry > 0, "Should have returned an empty enumerator instead"); // Store a reference to the parent table and increase its active enumerator count. _table = table; Debug.Assert(table._activeEnumeratorRefCount >= 0, "Should never have a negative ref count before incrementing"); table._activeEnumeratorRefCount++; // Store the max index to be enumerated. _maxIndexInclusive = table._container.FirstFreeEntry - 1; _currentIndex = -1; } ~Enumerator() { Dispose(); } public void Dispose() { // Use an interlocked operation to ensure that only one thread can get access to // the _table for disposal and thus only decrement the ref count once. ConditionalWeakTable<TKey, TValue> table = Interlocked.Exchange(ref _table, null); if (table != null) { // Ensure we don't keep the last current alive unnecessarily _current = default(KeyValuePair<TKey, TValue>); // Decrement the ref count that was incremented when constructed using (LockHolder.Hold(table._lock)) { table._activeEnumeratorRefCount--; Debug.Assert(table._activeEnumeratorRefCount >= 0, "Should never have a negative ref count after decrementing"); } // Finalization is purely to decrement the ref count. We can suppress it now. GC.SuppressFinalize(this); } } public bool MoveNext() { // Start by getting the current table. If it's already been disposed, it will be null. ConditionalWeakTable<TKey, TValue> table = _table; if (table != null) { // Once have the table, we need to lock to synchronize with other operations on // the table, like adding. using (LockHolder.Hold(table._lock)) { // From the table, we have to get the current container. This could have changed // since we grabbed the enumerator, but the index-to-pair mapping should not have // due to there being at least one active enumerator. If the table (or rather its // container at the time) has already been finalized, this will be null. Container c = table._container; if (c != null) { // We have the container. Find the next entry to return, if there is one. // We need to loop as we may try to get an entry that's already been removed // or collected, in which case we try again. while (_currentIndex < _maxIndexInclusive) { _currentIndex++; TKey key; TValue value; if (c.TryGetEntry(_currentIndex, out key, out value)) { _current = new KeyValuePair<TKey, TValue>(key, value); return true; } } } } } // Nothing more to enumerate. return false; } public KeyValuePair<TKey, TValue> Current { get { if (_currentIndex < 0) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _current; } } object IEnumerator.Current => Current; public void Reset() { } } #endregion #region Private Members //---------------------------------------------------------------------------------------- // Worker for adding a new key/value pair. // Will resize the container if it is full // // Preconditions: // Must hold _lock. // Key already validated as non-null and not already in table. //---------------------------------------------------------------------------------------- private void CreateEntry(TKey key, TValue value) { Debug.Assert(_lock.IsAcquired); Container c = _container; if (!c.HasCapacity) { c = _container = c.Resize(); } c.CreateEntryNoResize(key, value); } private static bool IsPowerOfTwo(int value) { return (value > 0) && ((value & (value - 1)) == 0); } #endregion #region Private Data Members //-------------------------------------------------------------------------------------------- // Entry can be in one of four states: // // - Unused (stored with an index _firstFreeEntry and above) // depHnd.IsAllocated == false // hashCode == <dontcare> // next == <dontcare>) // // - Used with live key (linked into a bucket list where _buckets[hashCode & (_buckets.Length - 1)] points to first entry) // depHnd.IsAllocated == true, depHnd.GetPrimary() != null // hashCode == RuntimeHelpers.GetHashCode(depHnd.GetPrimary()) & Int32.MaxValue // next links to next Entry in bucket. // // - Used with dead key (linked into a bucket list where _buckets[hashCode & (_buckets.Length - 1)] points to first entry) // depHnd.IsAllocated == true, depHnd.GetPrimary() == null // hashCode == <notcare> // next links to next Entry in bucket. // // - Has been removed from the table (by a call to Remove) // depHnd.IsAllocated == true, depHnd.GetPrimary() == <notcare> // hashCode == -1 // next links to next Entry in bucket. // // The only difference between "used with live key" and "used with dead key" is that // depHnd.GetPrimary() returns null. The transition from "used with live key" to "used with dead key" // happens asynchronously as a result of normal garbage collection. The dictionary itself // receives no notification when this happens. // // When the dictionary grows the _entries table, it scours it for expired keys and does not // add those to the new container. //-------------------------------------------------------------------------------------------- private struct Entry { public DependentHandle depHnd; // Holds key and value using a weak reference for the key and a strong reference // for the value that is traversed only if the key is reachable without going through the value. public int hashCode; // Cached copy of key's hashcode public int next; // Index of next entry, -1 if last } // // Container holds the actual data for the table. A given instance of Container always has the same capacity. When we need // more capacity, we create a new Container, copy the old one into the new one, and discard the old one. This helps enable lock-free // reads from the table, as readers never need to deal with motion of entries due to rehashing. // private sealed class Container { internal Container(ConditionalWeakTable<TKey, TValue> parent) { Debug.Assert(parent != null); Debug.Assert(IsPowerOfTwo(InitialCapacity)); int size = InitialCapacity; _buckets = new int[size]; for (int i = 0; i < _buckets.Length; i++) { _buckets[i] = -1; } _entries = new Entry[size]; // Only store the parent after all of the allocations have happened successfully. // Otherwise, as part of growing or clearing the container, we could end up allocating // a new Container that fails (OOMs) part way through construction but that gets finalized // and ends up clearing out some other container present in the associated CWT. _parent = parent; } private Container(ConditionalWeakTable<TKey, TValue> parent, int[] buckets, Entry[] entries, int firstFreeEntry) { Debug.Assert(parent != null); _parent = parent; _buckets = buckets; _entries = entries; _firstFreeEntry = firstFreeEntry; } internal bool HasCapacity { get { return _firstFreeEntry < _entries.Length; } } internal int FirstFreeEntry => _firstFreeEntry; //---------------------------------------------------------------------------------------- // Worker for adding a new key/value pair. // Preconditions: // Container must NOT be full //---------------------------------------------------------------------------------------- internal void CreateEntryNoResize(TKey key, TValue value) { Debug.Assert(HasCapacity); VerifyIntegrity(); _invalid = true; int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue; int newEntry = _firstFreeEntry++; _entries[newEntry].hashCode = hashCode; _entries[newEntry].depHnd = new DependentHandle(key, value); int bucket = hashCode & (_buckets.Length - 1); _entries[newEntry].next = _buckets[bucket]; // This write must be volatile, as we may be racing with concurrent readers. If they see // the new entry, they must also see all of the writes earlier in this method. Volatile.Write(ref _buckets[bucket], newEntry); _invalid = false; } //---------------------------------------------------------------------------------------- // Worker for finding a key/value pair // // Preconditions: // Must hold _lock. // Key already validated as non-null //---------------------------------------------------------------------------------------- internal bool TryGetValueWorker(TKey key, out TValue value) { object secondary; int entryIndex = FindEntry(key, out secondary); value = Unsafe.As<TValue>(secondary); return (entryIndex != -1); } //---------------------------------------------------------------------------------------- // Returns -1 if not found (if key expires during FindEntry, this can be treated as "not found.") // // Preconditions: // Must hold _lock, or be prepared to retry the search while holding _lock. // Key already validated as non-null. //---------------------------------------------------------------------------------------- internal int FindEntry(TKey key, out object value) { int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue; int bucket = hashCode & (_buckets.Length - 1); for (int entriesIndex = Volatile.Read(ref _buckets[bucket]); entriesIndex != -1; entriesIndex = _entries[entriesIndex].next) { if (_entries[entriesIndex].hashCode == hashCode && _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out value) == key) { GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. return entriesIndex; } } GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. value = null; return -1; } //---------------------------------------------------------------------------------------- // Gets the entry at the specified entry index. //---------------------------------------------------------------------------------------- internal bool TryGetEntry(int index, out TKey key, out TValue value) { if (index < _entries.Length) { object oValue; object oKey = _entries[index].depHnd.GetPrimaryAndSecondary(out oValue); GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. if (oKey != null) { key = Unsafe.As<TKey>(oKey); value = Unsafe.As<TValue>(oValue); return true; } } key = default(TKey); value = default(TValue); return false; } //---------------------------------------------------------------------------------------- // Removes all of the keys in the table. //---------------------------------------------------------------------------------------- internal void RemoveAllKeys() { for (int i = 0; i < _firstFreeEntry; i++) { RemoveIndex(i); } } //---------------------------------------------------------------------------------------- // Removes the specified key from the table, if it exists. //---------------------------------------------------------------------------------------- internal bool Remove(TKey key) { VerifyIntegrity(); object value; int entryIndex = FindEntry(key, out value); if (entryIndex != -1) { RemoveIndex(entryIndex); return true; } return false; } private void RemoveIndex(int entryIndex) { Debug.Assert(entryIndex >= 0 && entryIndex < _firstFreeEntry); ref Entry entry = ref _entries[entryIndex]; // // We do not free the handle here, as we may be racing with readers who already saw the hash code. // Instead, we simply overwrite the entry's hash code, so subsequent reads will ignore it. // The handle will be free'd in Container's finalizer, after the table is resized or discarded. // Volatile.Write(ref entry.hashCode, -1); // Also, clear the key to allow GC to collect objects pointed to by the entry entry.depHnd.SetPrimary(null); } internal void UpdateValue(int entryIndex, TValue newValue) { Debug.Assert(entryIndex != -1); VerifyIntegrity(); _invalid = true; _entries[entryIndex].depHnd.SetSecondary(newValue); _invalid = false; } //---------------------------------------------------------------------------------------- // This does two things: resize and scrub expired keys off bucket lists. // // Precondition: // Must hold _lock. // // Postcondition: // _firstEntry is less than _entries.Length on exit, that is, the table has at least one free entry. //---------------------------------------------------------------------------------------- internal Container Resize() { Debug.Assert(!HasCapacity); bool hasExpiredEntries = false; int newSize = _buckets.Length; if (_parent == null || _parent._activeEnumeratorRefCount == 0) { // If any expired or removed keys exist, we won't resize. // If there any active enumerators, though, we don't want // to compact and thus have no expired entries. for (int entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++) { ref Entry entry = ref _entries[entriesIndex]; if (entry.hashCode == -1) { // the entry was removed hasExpiredEntries = true; break; } if (entry.depHnd.IsAllocated && entry.depHnd.GetPrimary() == null) { // the entry has expired hasExpiredEntries = true; break; } } } if (!hasExpiredEntries) { // Not necessary to check for overflow here, the attempt to allocate new arrays will throw newSize = _buckets.Length * 2; } return Resize(newSize); } internal Container Resize(int newSize) { Debug.Assert(newSize >= _buckets.Length); Debug.Assert(IsPowerOfTwo(newSize)); // Reallocate both buckets and entries and rebuild the bucket and entries from scratch. // This serves both to scrub entries with expired keys and to put the new entries in the proper bucket. int[] newBuckets = new int[newSize]; for (int bucketIndex = 0; bucketIndex < newBuckets.Length; bucketIndex++) { newBuckets[bucketIndex] = -1; } Entry[] newEntries = new Entry[newSize]; int newEntriesIndex = 0; bool activeEnumerators = _parent != null && _parent._activeEnumeratorRefCount > 0; // Migrate existing entries to the new table. if (activeEnumerators) { // There's at least one active enumerator, which means we don't want to // remove any expired/removed entries, in order to not affect existing // entries indices. Copy over the entries while rebuilding the buckets list, // as the buckets are dependent on the buckets list length, which is changing. for (; newEntriesIndex < _entries.Length; newEntriesIndex++) { ref Entry oldEntry = ref _entries[newEntriesIndex]; ref Entry newEntry = ref newEntries[newEntriesIndex]; int hashCode = oldEntry.hashCode; newEntry.hashCode = hashCode; newEntry.depHnd = oldEntry.depHnd; int bucket = hashCode & (newBuckets.Length - 1); newEntry.next = newBuckets[bucket]; newBuckets[bucket] = newEntriesIndex; } } else { // There are no active enumerators, which means we want to compact by // removing expired/removed entries. for (int entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++) { ref Entry oldEntry = ref _entries[entriesIndex]; int hashCode = oldEntry.hashCode; DependentHandle depHnd = oldEntry.depHnd; if (hashCode != -1 && depHnd.IsAllocated) { if (depHnd.GetPrimary() != null) { ref Entry newEntry = ref newEntries[newEntriesIndex]; // Entry is used and has not expired. Link it into the appropriate bucket list. newEntry.hashCode = hashCode; newEntry.depHnd = depHnd; int bucket = hashCode & (newBuckets.Length - 1); newEntry.next = newBuckets[bucket]; newBuckets[bucket] = newEntriesIndex; newEntriesIndex++; } else { // Pretend the item was removed, so that this container's finalizer // will clean up this dependent handle. Volatile.Write(ref oldEntry.hashCode, -1); } } } } // Create the new container. We want to transfer the responsibility of freeing the handles from // the old container to the new container, and also ensure that the new container isn't finalized // while the old container may still be in use. As such, we store a reference from the old container // to the new one, which will keep the new container alive as long as the old one is. var newContainer = new Container(_parent, newBuckets, newEntries, newEntriesIndex); if (activeEnumerators) { // If there are active enumerators, both the old container and the new container may be storing // the same entries with -1 hash codes, which the finalizer will clean up even if the container // is not the active container for the table. To prevent that, we want to stop the old container // from being finalized, as it no longer has any responsibility for any cleanup. GC.SuppressFinalize(this); } _oldKeepAlive = newContainer; // once this is set, the old container's finalizer will not free transferred dependent handles GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. return newContainer; } //---------------------------------------------------------------------------------------- // Precondition: // Must hold _lock. //---------------------------------------------------------------------------------------- private void VerifyIntegrity() { if (_invalid) { throw new InvalidOperationException(SR.CollectionCorrupted); } } //---------------------------------------------------------------------------------------- // Finalizer. //---------------------------------------------------------------------------------------- ~Container() { // We're just freeing per-appdomain unmanaged handles here. If we're already shutting down the AD, // don't bother. // // (Despite its name, Environment.HasShutdownStart also returns true if the current AD is finalizing.) if (Environment.HasShutdownStarted) { return; } //We also skip doing anything if the container is invalid, including if someone // the container object was allocated but its associated table never set. if (_invalid || _parent == null) { return; } // It's possible that the ConditionalWeakTable could have been resurrected, in which case code could // be accessing this Container as it's being finalized. We don't support usage after finalization, // but we also don't want to potentially corrupt state by allowing dependency handles to be used as // or after they've been freed. To avoid that, if it's at all possible that another thread has a // reference to this container via the CWT, we remove such a reference and then re-register for // finalization: the next time around, we can be sure that no references remain to this and we can // clean up the dependency handles without fear of corruption. if (!_finalized) { _finalized = true; using (LockHolder.Hold(_parent._lock)) { if (_parent._container == this) { _parent._container = null; } } GC.ReRegisterForFinalize(this); // next time it's finalized, we'll be sure there are no remaining refs return; } Entry[] entries = _entries; _invalid = true; _entries = null; _buckets = null; if (entries != null) { for (int entriesIndex = 0; entriesIndex < entries.Length; entriesIndex++) { // We need to free handles in two cases: // - If this container still owns the dependency handle (meaning ownership hasn't been transferred // to another container that replaced this one), then it should be freed. // - If this container had the entry removed, then even if in general ownership was transferred to // another container, removed entries are not, therefore this container must free them. if (_oldKeepAlive == null || entries[entriesIndex].hashCode == -1) { entries[entriesIndex].depHnd.Free(); } } } } private readonly ConditionalWeakTable<TKey, TValue> _parent; // the ConditionalWeakTable with which this container is associated private int[] _buckets; // _buckets[hashcode & (_buckets.Length - 1)] contains index of the first entry in bucket (-1 if empty) private Entry[] _entries; // the table entries containing the stored dependency handles private int _firstFreeEntry; // _firstFreeEntry < _entries.Length => table has capacity, entries grow from the bottom of the table. private bool _invalid; // flag detects if OOM or other background exception threw us out of the lock. private bool _finalized; // set to true when initially finalized private volatile object _oldKeepAlive; // used to ensure the next allocated container isn't finalized until this one is GC'd } private volatile Container _container; private readonly Lock _lock; // This lock protects all mutation of data in the table. Readers do not take this lock. private int _activeEnumeratorRefCount; // The number of outstanding enumerators on the table private const int InitialCapacity = 8; // Must be a power of two #endregion } #endregion #region DependentHandle //========================================================================================= // This struct collects all operations on native DependentHandles. The DependentHandle // merely wraps an IntPtr so this struct serves mainly as a "managed typedef." // // DependentHandles exist in one of two states: // // IsAllocated == false // No actual handle is allocated underneath. Illegal to call GetPrimary // or GetPrimaryAndSecondary(). Ok to call Free(). // // Initializing a DependentHandle using the nullary ctor creates a DependentHandle // that's in the !IsAllocated state. // (! Right now, we get this guarantee for free because (IntPtr)0 == NULL unmanaged handle. // ! If that assertion ever becomes false, we'll have to add an _isAllocated field // ! to compensate.) // // // IsAllocated == true // There's a handle allocated underneath. You must call Free() on this eventually // or you cause a native handle table leak. // // This struct intentionally does no self-synchronization. It's up to the caller to // to use DependentHandles in a thread-safe way. //========================================================================================= internal struct DependentHandle { #region Constructors public DependentHandle(Object primary, Object secondary) { _handle = RuntimeImports.RhHandleAllocDependent(primary, secondary); } #endregion #region Public Members public bool IsAllocated { get { return _handle != (IntPtr)0; } } // Getting the secondary object is more expensive than getting the first so // we provide a separate primary-only accessor for those times we only want the // primary. public Object GetPrimary() { return RuntimeImports.RhHandleGet(_handle); } public object GetPrimaryAndSecondary(out object secondary) { return RuntimeImports.RhHandleGetDependent(_handle, out secondary); } public void SetPrimary(object primary) { RuntimeImports.RhHandleSet(_handle, primary); } public void SetSecondary(object secondary) { RuntimeImports.RhHandleSetDependentSecondary(_handle, secondary); } //---------------------------------------------------------------------- // Forces dependentHandle back to non-allocated state (if not already there) // and frees the handle if needed. //---------------------------------------------------------------------- public void Free() { if (_handle != (IntPtr)0) { IntPtr handle = _handle; _handle = (IntPtr)0; RuntimeImports.RhHandleFree(handle); } } #endregion #region Private Data Member private IntPtr _handle; #endregion } // struct DependentHandle #endregion }
// // Copyright 2010, Novell, Inc. // Copyright 2010, Duane Wandless. // // 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. // // TODO: // API: QTSampleBuffer.h expose a couple of AudioBufferList methods // API: QTMovie needs low-level access to some methods // API: Expose the individual QTMovie*Attribute as C# properties // API: "Media" from QuickTime is not bound, so we expose as IntPtr in QTMedia // API: some stuff missing for QTTime.h and QTTimeRange // // QTCaptureDecompressedAudioOutput.h // QTCaptureVideoPreviewOutput.h // QTError.h -- Missing the NSString keys // // Need to strongly type/provide accessors in QTCaptureDevice for // [Field ("QTCaptureDeviceLinkedDevicesAttribute")] // [Field ("QTCaptureDeviceAvailableInputSourcesAttribute")] // [Field ("QTCaptureDeviceInputSourceIdentifierAttribute")] // [Field ("QTCaptureDeviceLegacySequenceGrabberAttribute")] using System; using MonoMac.Foundation; using MonoMac.ObjCRuntime; using MonoMac.AppKit; using System.Drawing; using MonoMac.CoreAnimation; using MonoMac.CoreVideo; using MonoMac.CoreImage; namespace MonoMac.QTKit { [BaseType (typeof (QTCaptureOutput))] interface QTCaptureAudioPreviewOutput { [Export ("outputDeviceUniqueID")] string OutputDeviceUniqueID { get; set; } [Export ("volume")] float Volume { get; set; } } [BaseType (typeof (NSObject))] interface QTCaptureConnection { [Export ("owner")] NSObject Owner { get; } [Export ("mediaType")] string MediaType { get; } [Export ("formatDescription")] QTFormatDescription FormatDescription { get; } [Export ("attributeIsReadOnly:")] bool IsAttributeReadOnly (string attributeKey); [Export ("attributeForKey:")] NSObject GetAttribute (string attributeKey); [Export ("setAttribute:forKey:")] void SetAttribute (NSObject attribute, string key); //Detected properties [Export ("enabled")] bool Enabled { [Bind ("isEnabled")]get; set; } [Export ("connectionAttributes")] NSDictionary ConnectionAttributes { get; set; } [Field ("QTCaptureConnectionFormatDescriptionWillChangeNotification")] NSString FormatDescriptionWillChangeNotification { get; } [Field ("QTCaptureConnectionFormatDescriptionDidChangeNotification")] NSString FormatDescriptionDidChangeNotification { get; } [Field ("QTCaptureConnectionAttributeWillChangeNotification")] NSString AttributeWillChangeNotification { get; } [Field ("QTCaptureConnectionAttributeDidChangeNotification")] NSString AttributeDidChangeNotification { get; } [Field ("QTCaptureConnectionChangedAttributeKey")] NSString ChangedAttributeKey { get; } [Field ("QTCaptureConnectionAudioAveragePowerLevelsAttribute")] NSString AudioAveragePowerLevelsAttribute { get; } [Field ("QTCaptureConnectionAudioPeakHoldLevelsAttribute")] NSString AudioPeakHoldLevelsAttribute { get; } [Field ("QTCaptureConnectionAudioMasterVolumeAttribute")] NSString AudioMasterVolumeAttribute { get; } [Field ("QTCaptureConnectionAudioVolumesAttribute")] NSString AudioVolumesAttribute { get; } [Field ("QTCaptureConnectionEnabledAudioChannelsAttribute")] NSString EnabledAudioChannelsAttribute { get; } } [BaseType (typeof (QTCaptureOutput), Delegates=new string [] { "Delegate" }, Events=new Type [] { typeof (QTCaptureDecompressedVideoOutputDelegate)})] interface QTCaptureDecompressedVideoOutput { [Export ("outputVideoFrame:withSampleBuffer:fromConnection:")] void OutputVideoFrame (CVImageBuffer videoFrame, QTSampleBuffer sampleBuffer, QTCaptureConnection connection); //Detected properties [Export ("pixelBufferAttributes")] NSDictionary PixelBufferAttributes { get; set; } [Export ("minimumVideoFrameInterval")] double MinimumVideoFrameInterval { get; set; } [Export ("automaticallyDropsLateVideoFrames")] bool AutomaticallyDropsLateVideoFrames { get; set; } [Export ("delegate"), NullAllowed] NSObject WeakDelegate { get; set; } [Wrap ("WeakDelegate")] QTCaptureDecompressedVideoOutputDelegate Delegate { get; set; } } [BaseType (typeof (NSObject), Name="QTCaptureDecompressedVideoOutput_Delegate")] [Model] interface QTCaptureDecompressedVideoOutputDelegate { [Export ("captureOutput:didOutputVideoFrame:withSampleBuffer:fromConnection:"), EventArgs ("QTCaptureVideoFrame")] void DidOutputVideoFrame (QTCaptureOutput captureOutput, CVImageBuffer videoFrame, QTSampleBuffer sampleBuffer, QTCaptureConnection connection); [Export ("captureOutput:didDropVideoFrameWithSampleBuffer:fromConnection:"), EventArgs ("QTCaptureVideoDropped")] void DidDropVideoFrame (QTCaptureOutput captureOutput, QTSampleBuffer sampleBuffer, QTCaptureConnection connection); } [BaseType (typeof (NSObject))] [DisableDefaultCtor] // An uncaught exception was raised: Cannot instantiate a QTCaptureDevice directly. interface QTCaptureDevice { [Static] [Export ("inputDevices")] QTCaptureDevice [] InputDevices { get; } [Static] [Internal, Export ("inputDevicesWithMediaType:")] QTCaptureDevice [] _GetInputDevices (NSString forMediaType); [Static] [Internal,Export ("defaultInputDeviceWithMediaType:")] QTCaptureDevice _GetDefaultInputDevice (NSString forMediaType); [Static] [Export ("deviceWithUniqueID:")] QTCaptureDevice FromUniqueID (string deviceUniqueID); [Export ("uniqueID")] string UniqueID { get; } [Export ("modelUniqueID")] string ModelUniqueID { get; } [Export ("localizedDisplayName")] string LocalizedDisplayName { get; } [Export ("formatDescriptions")] QTFormatDescription [] FormatDescriptions { get; } [Export ("hasMediaType:"), Internal] bool _HasMediaType (string mediaType); [Export ("attributeIsReadOnly:")] bool IsAttributeReadOnly (string attributeKey); [Export ("attributeForKey:")] NSObject GetAttribute (string attributeKey); [Export ("setAttribute:forKey:")] void SetAttribute (NSObject attribute, string attributeKey); [Export ("isConnected")] bool IsConnected { get; } [Export ("isInUseByAnotherApplication")] bool IsInUseByAnotherApplication { get; } [Export ("isOpen")] bool IsOpen { get; } [Export ("open:")] bool Open (out NSError error); [Export ("close")] void Close (); //Detected properties [Export ("deviceAttributes")] NSDictionary DeviceAttributes { get; set; } [Field ("QTCaptureDeviceWasConnectedNotification")] NSString WasConnectedNotification { get; } [Field ("QTCaptureDeviceWasDisconnectedNotification")] NSString WasDisconnectedNotification { get; } [Field ("QTCaptureDeviceFormatDescriptionsWillChangeNotification")] NSString FormatDescriptionsWillChangeNotification { get; } [Field ("QTCaptureDeviceFormatDescriptionsDidChangeNotification")] NSString FormatDescriptionsDidChangeNotification { get; } [Field ("QTCaptureDeviceAttributeWillChangeNotification")] NSString AttributeWillChangeNotification { get; } [Field ("QTCaptureDeviceAttributeDidChangeNotification")] NSString AttributeDidChangeNotification { get; } [Field ("QTCaptureDeviceChangedAttributeKey")] NSString ChangedAttributeKey { get; } [Field ("QTCaptureDeviceLinkedDevicesAttribute")] NSString LinkedDevicesAttribute { get; } [Field ("QTCaptureDeviceAvailableInputSourcesAttribute")] NSString AvailableInputSourcesAttribute { get; } [Field ("QTCaptureDeviceInputSourceIdentifierAttribute")] NSString InputSourceIdentifierAttribute { get; } [Field ("QTCaptureDeviceInputSourceIdentifierKey")] NSString InputSourceIdentifierKey { get; } [Field ("QTCaptureDeviceInputSourceLocalizedDisplayNameKey")] NSString InputSourceLocalizedDisplayNameKey { get; } [Field ("QTCaptureDeviceLegacySequenceGrabberAttribute")] NSString LegacySequenceGrabberAttribute { get; } [Internal, Field ("QTCaptureDeviceAVCTransportControlsAttribute")] NSString AVCTransportControlsAttribute { get; } [Internal, Field ("QTCaptureDeviceAVCTransportControlsPlaybackModeKey")] NSString AVCTransportControlsPlaybackModeKey { get; } [Internal, Field ("QTCaptureDeviceAVCTransportControlsSpeedKey")] NSString AVCTransportControlsSpeedKey { get; } [Internal,Field ("QTCaptureDeviceSuspendedAttribute")] NSString SuspendedAttribute { get; } } [BaseType (typeof (QTCaptureInput))] [DisableDefaultCtor] // crash without warning interface QTCaptureDeviceInput { [Static] [Export ("deviceInputWithDevice:")] QTCaptureDeviceInput FromDevice (QTCaptureDevice device); [Export ("initWithDevice:")] IntPtr Constructor (QTCaptureDevice device); [Export ("device")] QTCaptureDevice Device { get; } } [BaseType (typeof (QTCaptureOutput), Delegates=new string [] { "Delegate" }, Events=new Type [] { typeof (QTCaptureFileOutputDelegate)})] [DisableDefaultCtor] // crash without warning interface QTCaptureFileOutput { [Export ("outputFileURL")] NSUrl OutputFileUrl { get; } [Export ("recordToOutputFileURL:")] void RecordToOutputFile ([NullAllowed] NSUrl url); [Export ("recordToOutputFileURL:bufferDestination:")] void RecordToOutputFile ([NullAllowed] NSUrl url, QTCaptureDestination bufferDestination); [Export ("isRecordingPaused")] bool IsRecordingPaused { get; } [Export ("pauseRecording")] void PauseRecording (); [Export ("resumeRecording")] void ResumeRecording (); [Export ("compressionOptionsForConnection:")] QTCompressionOptions GetCompressionOptions (QTCaptureConnection forConnection); [Export ("setCompressionOptions:forConnection:")] void SetCompressionOptions (QTCompressionOptions compressionOptions, QTCaptureConnection forConnection); [Export ("recordedDuration")] QTTime RecordedDuration { get; } [Export ("recordedFileSize")] UInt64 RecordedFileSize { get; } //Detected properties [Export ("maximumVideoSize")] SizeF MaximumVideoSize { get; set; } [Export ("minimumVideoFrameInterval")] double MinimumVideoFrameInterval { get; set; } [Export ("maximumRecordedDuration")] QTTime MaximumRecordedDuration { get; set; } [Export ("maximumRecordedFileSize")] UInt64 MaximumRecordedFileSize { get; set; } [Export ("delegate"), NullAllowed] NSObject WeakDelegate { get; set; } [Wrap ("WeakDelegate")] QTCaptureFileOutputDelegate Delegate { get; set; } } [BaseType (typeof (NSObject), Name="QTCaptureFileOutput_Delegate")] [Model] interface QTCaptureFileOutputDelegate { [Export ("captureOutput:didOutputSampleBuffer:fromConnection:"), EventArgs ("QTCaptureFileSample")] void DidOutputSampleBuffer (QTCaptureFileOutput captureOutput, QTSampleBuffer sampleBuffer, QTCaptureConnection connection); [Export ("captureOutput:willStartRecordingToOutputFileAtURL:forConnections:"), EventArgs ("QTCaptureFileUrl")] void WillStartRecording (QTCaptureFileOutput captureOutput, NSUrl fileUrl, QTCaptureConnection [] connections); [Export ("captureOutput:didStartRecordingToOutputFileAtURL:forConnections:"), EventArgs ("QTCaptureFileUrl")] void DidStartRecording (QTCaptureFileOutput captureOutput, NSUrl fileUrl, QTCaptureConnection [] connections); [Export ("captureOutput:shouldChangeOutputFileAtURL:forConnections:dueToError:"), DelegateName ("QTCaptureFileError"), DefaultValue (true)] bool ShouldChangeOutputFile (QTCaptureFileOutput captureOutput, NSUrl outputFileURL, QTCaptureConnection [] connections, NSError reason); [Export ("captureOutput:mustChangeOutputFileAtURL:forConnections:dueToError:"), EventArgs ("QTCaptureFileError")] void MustChangeOutputFile (QTCaptureFileOutput captureOutput, NSUrl outputFileURL, QTCaptureConnection [] connections, NSError reason); [Export ("captureOutput:willFinishRecordingToOutputFileAtURL:forConnections:dueToError:"), EventArgs ("QTCaptureFileError")] void WillFinishRecording (QTCaptureFileOutput captureOutput, NSUrl outputFileURL, QTCaptureConnection [] connections, NSError reason); [Export ("captureOutput:didFinishRecordingToOutputFileAtURL:forConnections:dueToError:"), EventArgs ("QTCaptureFileError")] void DidFinishRecording (QTCaptureFileOutput captureOutput, NSUrl outputFileURL, QTCaptureConnection [] connections, NSError reason); [Export ("captureOutput:didPauseRecordingToOutputFileAtURL:forConnections:"), EventArgs ("QTCaptureFileUrl")] void DidPauseRecording (QTCaptureFileOutput captureOutput, NSUrl fileUrl, QTCaptureConnection [] connections); [Export ("captureOutput:didResumeRecordingToOutputFileAtURL:forConnections:"), EventArgs ("QTCaptureFileUrl")] void DidResumeRecording (QTCaptureFileOutput captureOutput, NSUrl fileUrl, QTCaptureConnection [] connections); } [BaseType (typeof (NSObject))] [DisableDefaultCtor] // An uncaught exception was raised: Cannot instantiate QTCaptureInput because it is an abstract superclass. interface QTCaptureInput { [Export ("connections")] QTCaptureConnection [] Connections { get; } } [BaseType (typeof (CALayer))] interface QTCaptureLayer { [Static, Export ("layerWithSession:")] NSObject FromSession (QTCaptureSession session); [Export ("initWithSession:")] IntPtr Constructor (QTCaptureSession session); //Detected properties [Export ("session")] QTCaptureSession Session { get; set; } } [BaseType (typeof (QTCaptureFileOutput))] interface QTCaptureMovieFileOutput { // Empty } [BaseType (typeof (NSObject))] [DisableDefaultCtor] // An uncaught exception was raised: Cannot instantiate QTCaptureOutput because it is an abstract superclass. interface QTCaptureOutput { [Export ("connections")] QTCaptureConnection [] Connections { get; } } [BaseType (typeof (NSObject))] interface QTCaptureSession { [Export ("inputs")] QTCaptureInput [] Inputs { get; } [Export ("addInput:error:")] bool AddInput (QTCaptureInput input, out NSError error); [Export ("removeInput:")] void RemoveInput (QTCaptureInput input); [Export ("outputs")] QTCaptureOutput [] Outputs { get; } [Export ("addOutput:error:")] bool AddOutput (QTCaptureOutput output, out NSError error); [Export ("removeOutput:")] void RemoveOutput (QTCaptureOutput output); [Export ("isRunning")] bool IsRunning { get; } [Export ("startRunning")] void StartRunning (); [Export ("stopRunning")] void StopRunning (); [Field ("QTCaptureSessionRuntimeErrorNotification")] NSString RuntimeErrorNotification { get; } [Field ("QTCaptureSessionErrorKey")] NSString ErrorKey { get; } } [BaseType (typeof (NSView), Delegates=new string [] { "Delegate" }, Events=new Type [] { typeof (QTCaptureViewDelegate)})] interface QTCaptureView { [Export ("availableVideoPreviewConnections")] QTCaptureConnection [] AvailableVideoPreviewConnections { get; } [Export ("previewBounds")] RectangleF PreviewBounds { get; } //Detected properties [Export ("captureSession")] QTCaptureSession CaptureSession { get; set; } [Export ("videoPreviewConnection")] QTCaptureConnection VideoPreviewConnection { get; set; } [Export ("fillColor")] NSColor FillColor { get; set; } [Export ("preservesAspectRatio")] bool PreservesAspectRatio { get; set; } [Export ("delegate"), NullAllowed] NSObject WeakDelegate { get; set; } [Wrap ("WeakDelegate")] QTCaptureViewDelegate Delegate { get; set; } } [BaseType (typeof (NSObject), Name="QTCaptureView_Delegate")] [Model] interface QTCaptureViewDelegate { [Export ("view:willDisplayImage:"), DelegateName ("QTCaptureImageEvent"), DefaultValueFromArgument ("image")] CIImage WillDisplayImage (QTCaptureView view, CIImage image); } [BaseType (typeof (NSObject))] interface QTCompressionOptions { [Static] [Export ("compressionOptionsIdentifiersForMediaType:")] string [] GetCompressionOptionsIdentifiers (string forMediaType); [Static] [Export ("compressionOptionsWithIdentifier:")] NSObject FromIdentifier (string identifier); [Export ("mediaType")] string MediaType { get; } [Export ("localizedDisplayName")] string LocalizedDisplayName { get; } [Export ("localizedCompressionOptionsSummary")] string LocalizedCompressionOptionsSummary { get; } [Export ("isEqualToCompressionOptions:")] bool IsEqualToCompressionOptions (QTCompressionOptions compressionOptions); } [BaseType (typeof (NSObject))] interface QTDataReference { [Static] [Export ("dataReferenceWithDataRefData:type:")] NSObject FromDataRefData (NSData dataRefData, string type); [Static] [Export ("dataReferenceWithReferenceToFile:")] NSObject FromReference (string fileName); [Static] [Export ("dataReferenceWithReferenceToURL:")] NSObject FromReference (NSUrl url); [Static] [Export ("dataReferenceWithReferenceToData:")] NSObject FromDataReference (NSData data); [Static] [Export ("dataReferenceWithReferenceToData:name:MIMEType:")] NSObject FromReference (NSData data, string name, string mimeType); [Export ("dataRefData")] NSData DataRefData { get; } [Export ("referenceFile")] string ReferenceFile { get; } [Export ("referenceURL")] NSUrl ReferenceUrl { get; } [Export ("referenceData")] NSData ReferenceData { get; } [Export ("name")] string Name { get; } [Export ("MIMEType")] string MimeType { get; } //Detected properties //[Export ("dataRef")] //IntPtr DataRef { get; set; } [Export ("dataRefType")] string DataRefType { get; set; } } [BaseType (typeof (NSObject))] interface QTFormatDescription { [Export ("mediaType")] string MediaType { get; } [Export ("formatType")] UInt32 FormatType { get; } [Export ("localizedFormatSummary")] string LocalizedFormatSummary { get; } [Export ("quickTimeSampleDescription")] NSData QuickTimeSampleDescription { get; } [Export ("formatDescriptionAttributes")] NSDictionary FormatDescriptionAttributes { get; } [Export ("attributeForKey:")] NSObject AttributeForKey (string key); [Export ("isEqualToFormatDescription:")] bool IsEqualToFormatDescription (QTFormatDescription formatDescription); } [BaseType (typeof (NSObject))] interface QTMedia { [Static, Export ("mediaWithQuickTimeMedia:error:")] NSObject FromQuickTimeMedia (IntPtr quicktimeMedia, out NSError error); [Export ("initWithQuickTimeMedia:error:")] IntPtr Conditions (IntPtr quicktimeMedia, out NSError error); [Export ("track")] QTTrack Track { get; } [Export ("attributeForKey:")] NSObject GetAttribute (string attributeKey); [Export ("setAttribute:forKey:")] void SetAttribute (NSObject value, string attributeKey); [Export ("hasCharacteristic:")] bool HasCharacteristic (string characteristic); [Export ("quickTimeMedia")] IntPtr QuickTimeMedia { get; } //Detected properties [Export ("mediaAttributes")] NSDictionary MediaAttributes { get; set; } // Constants [Internal, Field ("QTMediaTypeVideo")] NSString TypeVideo { get; } [Internal, Field ("QTMediaTypeSound")] NSString TypeSound { get; } [Internal, Field ("QTMediaTypeText")] NSString TypeText { get; } [Internal, Field ("QTMediaTypeBase")] NSString TypeBase { get; } [Internal, Field ("QTMediaTypeMPEG")] NSString TypeMpeg { get; } [Internal, Field ("QTMediaTypeMusic")] NSString TypeMusic { get; } [Internal, Field ("QTMediaTypeTimeCode")] NSString TypeTimeCode { get; } [Internal, Field ("QTMediaTypeSprite")] NSString TypeSprite { get; } [Internal, Field ("QTMediaTypeFlash")] NSString TypeFlash { get; } [Internal, Field ("QTMediaTypeMovie")] NSString TypeMovie { get; } [Internal, Field ("QTMediaTypeTween")] NSString TypeTween { get; } [Internal, Field ("QTMediaType3D")] NSString Type3D { get; } [Internal, Field ("QTMediaTypeSkin")] NSString TypeSkin { get; } [Internal, Field ("QTMediaTypeQTVR")] NSString TypeQTVR { get; } [Internal, Field ("QTMediaTypeHint")] NSString TypeHint { get; } [Internal, Field ("QTMediaTypeStream")] NSString TypeStream { get; } [Internal, Field ("QTMediaTypeMuxed")] NSString TypeMuxed { get; } [Internal, Field ("QTMediaTypeQuartzComposer")] NSString TypeQuartzComposer { get; } [Field ("QTMediaCharacteristicVisual")] NSString CharacteristicVisual { get; } [Field ("QTMediaCharacteristicAudio")] NSString CharacteristicAudio { get; } [Field ("QTMediaCharacteristicCanSendVideo")] NSString CharacteristicCanSendVideo { get; } [Field ("QTMediaCharacteristicProvidesActions")] NSString CharacteristicProvidesActions { get; } [Field ("QTMediaCharacteristicNonLinear")] NSString CharacteristicNonLinear { get; } [Field ("QTMediaCharacteristicCanStep")] NSString CharacteristicCanStep { get; } [Field ("QTMediaCharacteristicHasNoDuration")] NSString CharacteristicHasNoDuration { get; } [Field ("QTMediaCharacteristicHasSkinData")] NSString CharacteristicHasSkinData { get; } [Field ("QTMediaCharacteristicProvidesKeyFocus")] NSString CharacteristicProvidesKeyFocus { get; } [Field ("QTMediaCharacteristicHasVideoFrameRate")] NSString CharacteristicHasVideoFrameRate { get; } [Field ("QTMediaCreationTimeAttribute")] NSString CreationTimeAttribute { get; } [Field ("QTMediaDurationAttribute")] NSString DurationAttribute { get; } [Field ("QTMediaModificationTimeAttribute")] NSString ModificationTimeAttribute { get; } [Field ("QTMediaSampleCountAttribute")] NSString SampleCountAttribute { get; } [Field ("QTMediaQualityAttribute")] NSString QualityAttribute { get; } [Field ("QTMediaTimeScaleAttribute")] NSString TimeScaleAttribute { get; } [Field ("QTMediaTypeAttribute")] NSString TypeAttribute { get; } } [BaseType (typeof (CALayer))] interface QTMovieLayer { [Static, Export ("layerWithMovie:")] QTMovieLayer FromMovie (QTMovie movie); [Export ("initWithMovie:")] IntPtr Constructor (QTMovie movie); //Detected properties [Export ("movie")] QTMovie Movie { get; set; } } [BaseType (typeof (NSView))] interface QTMovieView { [Export ("movie")] QTMovie Movie { get; set; } [Export ("isControllerVisible")] bool IsControllerVisible { get; [Bind("setControllerVisible:")] set; } [Export ("isEditable")] bool Editable { get; [Bind("setEditable:")] set; } [Export ("controllerBarHeight")] float ControllerBarHeight { get; } [Export ("preservesAspectRatio")] bool PreservesAspectRatio { get; set; } [Export ("fillColor")] NSColor FillColor { get; set; } [Export ("movieBounds")] RectangleF MovieBounds { get; } [Export ("movieControllerBounds")] RectangleF MovieControllerBounds { get; } [Export ("setShowsResizeIndicator:")] void SetShowsResizeIndicator (bool show); [Export ("play:")] void Play (NSObject sender); [Export ("pause:")] void Pause (NSObject sender); [Export ("gotoBeginning:")] void GotoBeginning (NSObject sender); [Export ("gotoEnd:")] void GotoEnd (NSObject sender); [Export ("gotoNextSelectionPoint:")] void GotoNextSelectionPoint (NSObject sender); [Export ("gotoPreviousSelectionPoint:")] void GotoPreviousSelectionPoint (NSObject sender); [Export ("gotoPosterFrame:")] void GotoPosterFrame (NSObject sender); [Export ("stepForward:")] void StepForward (NSObject sender); [Export ("stepBackward:")] void StepBackward (NSObject sender); [Export ("cut:")] void Cut (NSObject sender); [Export ("copy:")] void Copy (NSObject sender); [Export ("paste:")] void Paste (NSObject sender); [Export ("selectAll:")] void SelectAll (NSObject sender); [Export ("selectNone:")] void SelectNone (NSObject sender); [Export ("delete:")] void Delete (NSObject sender); [Export ("add:")] void Add (NSObject sender); [Export ("addScaled:")] void AddScaled (NSObject sender); [Export ("replace:")] void Replace (NSObject sender); [Export ("trim:")] void Trim (NSObject sender); [Export ("backButtonVisible")] bool BackButtonVisible { [Bind ("isBackButtonVisible")] get; set; } [Export ("customButtonVisible")] bool CustomButtonVisible { [Bind ("isCustomButtonVisible")] get; set; } [Export ("hotSpotButtonVisible")] bool HotSpotButtonVisible { [Bind ("isHotSpotButtonVisible")] get; set; } [Export ("stepButtonsVisible")] bool SetStepButtonsVisible { [Bind ("areStepButtonsVisible")] get; set; } [Export ("translateButtonVisible")] bool TranslateButtonVisible { [Bind ("isTranslateButtonVisible")] get; set; } [Export ("volumeButtonVisible")] bool VolumeButtonVisible { [Bind ("isVolumeButtonVisible")] get; set; } [Export ("zoomButtonsVisible")] bool ZoomButtonsVisible { [Bind ("areZoomButtonsVisible")] get; set; } [Export ("delegate"), NullAllowed] NSObject WeakDelegate { get; set; } [Wrap ("WeakDelegate")] QTMovieViewDelegate Delegate { get; set; } } [BaseType (typeof (NSObject))] [Model] interface QTMovieViewDelegate { [Export ("view:willDisplayImage:")] CIImage ViewWillDisplayImage (QTMovieView view, CIImage image); } [BaseType (typeof (NSObject))] interface QTMovie { [Export ("duration")] QTTime Duration { get; } [Static, Export ("canInitWithPasteboard:")] bool CanInitWithPasteboard (NSPasteboard pasteboard); [Static, Export ("canInitWithFile:")] bool CanInitWithFile (string fileName); [Static, Export ("canInitWithURL:")] bool CanInitWithUrl (NSUrl url); //[Static, Export ("canInitWithDataReference:")] //bool CanInitWithDataReference (QTDataReference dataReference); [Static, Export ("movieFileTypes:")] string[] MovieFileTypes (QTMovieFileTypeOptions types); [Static, Export ("movieUnfilteredFileTypes")] string[] MovieUnfilteredFileTypes (); //+ (NSArray *)movieUnfilteredPasteboardTypes; [Static, Export ("movieUnfilteredPasteboardTypes")] string[] MovieUnfilteredPasteboardTypes (); [Static, Export ("movieTypesWithOptions:")] string[] MovieTypesWithOptions (QTMovieFileTypeOptions types); [Static, Export ("movie")] QTMovie Movie { get; } [Static, Export ("movieWithFile:error:")] QTMovie FromFile (string fileName, out NSError error); [Static, Export ("movieWithURL:error:")] QTMovie FromUrl (NSUrl url, out NSError error); //[Static, Export ("movieWithDataReference:error:")] //QTMovie MovieWithDataReferenceError (QTDataReference dataReference, out NSError error); [Static, Export ("movieWithPasteboard:error:")] QTMovie FromPasteboard (NSPasteboard pasteboard, out NSError error); [Static, Export ("movieWithData:error:")] QTMovie FromData (NSData data, out NSError error); // [Static, Export ("movieWithQuickTimeMovie:disposeWhenDone:error:")] // QTMovie MovieWithQuickTimeMovieDisposeWhenDone (Movie movie, bool dispose, out NSError error); [Static, Export ("movieWithAttributes:error:")] QTMovie FromAttributes (NSDictionary attributes, out NSError error); [Static, Export ("movieNamed:error:")] QTMovie FromMovieNamed (string name, out NSError error); [Export ("initWithFile:error:")] IntPtr Constructor (string fileName, out NSError error); [Export ("initWithURL:error:")] IntPtr Constructor (NSUrl url, out NSError error); [Export ("initWithDataReference:error:")] IntPtr Constructor (QTDataReference dataReference, out NSError error); [Export ("initWithPasteboard:error:")] IntPtr Constructor (NSPasteboard pasteboard, out NSError error); [Export ("initWithData:error:")] IntPtr Constructor (NSData data, out NSError error); [Export ("initWithMovie:timeRange:error:")] IntPtr Constructor (QTMovie movie, QTTimeRange range, out NSError error); //- (id)initWithQuickTimeMovie:(Movie)movie disposeWhenDone:(BOOL)dispose error:(NSError **)errorPtr; // [Export ("initWithQuickTimeMovie:disposeWhenDone:error:")] // IntPtr Constructor ([Movie movie, bool dispose, out NSError error); [Export ("initWithAttributes:error:")] IntPtr Constructor (NSDictionary attributes, out NSError error); // non-static, it's a ctor that does not start with `init` [Export ("movieWithTimeRange:error:")] IntPtr Constructor (QTTimeRange range, out NSError error); // [Export ("initToWritableFile:error:")] // IntPtr Constructor (string filename, out NSError error); [Export ("initToWritableData:error:")] IntPtr Constructor (NSMutableData data, out NSError error); //- (id)initToWritableDataReference:(QTDataReference *)dataReference error:(NSError **)errorPtr; // [Export ("initToWritableDataReference:error:")] // IntPtr Constructor (QTDataReference dataReference, out NSError error); [Export ("invalidate")] void Invalidate (); [Export ("currentTime")] QTTime CurrentTime { get; set; } [Export ("rate")] float Rate { get; set; } [Export ("volume")] float Volume { get; set; } [Export ("muted")] bool Muted { get; set; } [Export ("movieAttributes")] NSDictionary MovieAttributes { get; set; } [Export ("attributeForKey:")] NSObject GetAttribute (string attributeKey); [Export ("setAttribute:forKey:")] void SetAttribute (NSObject value, string attributeKey); [Export ("tracks")] QTTrack[] Tracks { get; } [Export ("tracksOfMediaType:")] QTTrack[] TracksOfMediaType (string type); [Export ("posterImage")] NSImage PosterImage { get; } [Export ("currentFrameImage")] NSImage CurrentFrameImage { get; } [Export ("frameImageAtTime:")] NSImage FrameImageAtTime (QTTime time); [Export ("frameImageAtTime:withAttributes:error:")] IntPtr FrameImageAtTime (QTTime time, NSDictionary attributes, out NSError error); [Export ("movieFormatRepresentation")] NSData MovieFormatRepresentation (); [Export ("writeToFile:withAttributes:")] bool SaveTo (string fileName, NSDictionary attributes); [Export ("writeToFile:withAttributes:error:")] bool SaveTo (string fileName, NSDictionary attributes, out NSError error); [Export ("canUpdateMovieFile")] bool CanUpdateMovieFile { get; } [Export ("updateMovieFile")] bool UpdateMovieFile (); [Export ("autoplay")] void Autoplay (); [Export ("play")] void Play (); [Export ("stop")] void Stop (); [Export ("gotoBeginning")] void GotoBeginning (); [Export ("gotoEnd")] void GotoEnd (); [Export ("gotoNextSelectionPoint")] void GotoNextSelectionPoint (); [Export ("gotoPreviousSelectionPoint")] void GotoPreviousSelectionPoint (); [Export ("gotoPosterTime")] void GotoPosterTime (); [Export ("stepForward")] void StepForward (); [Export ("stepBackward")] void StepBackward (); [Export ("setSelection:")] void SetSelection (QTTimeRange selection); [Export ("selectionStart")] QTTime SelectionStart (); [Export ("selectionEnd")] QTTime SelectionEnd (); [Export ("selectionDuration")] QTTime SelectionDuration (); [Export ("replaceSelectionWithSelectionFromMovie:")] void ReplaceSelectionWithSelectionFromMovie (QTMovie movie); [Export ("appendSelectionFromMovie:")] void AppendSelectionFromMovie (QTMovie movie); [Export ("insertSegmentOfMovie:timeRange:atTime:")] void InsertSegmentOfMovieTimeRange (QTMovie movie, QTTimeRange range, QTTime time); [Export ("insertSegmentOfMovie:fromRange:scaledToRange:")] void InsertSegmentOfMovieFromRange (QTMovie movie, QTTimeRange srcRange, QTTimeRange dstRange); [Export ("insertEmptySegmentAt:")] void InsertEmptySegmentAt (QTTimeRange range); [Export ("deleteSegment:")] void DeleteSegment (QTTimeRange segment); [Export ("scaleSegment:newDuration:")] void ScaleSegmentNewDuration (QTTimeRange segment, QTTime newDuration); [Export ("addImage:forDuration:withAttributes:")] void AddImage (NSImage image, QTTime duration, NSDictionary attributes); [Export ("insertSegmentOfTrack:timeRange:atTime:")] QTTrack InsertSegmentOfTrackTimeRange (QTTrack track, QTTimeRange range, QTTime time); [Export ("insertSegmentOfTrack:fromRange:scaledToRange:")] QTTrack InsertSegmentOfTrackFromRange (QTTrack track, QTTimeRange srcRange, QTTimeRange dstRange); [Export ("removeTrack:")] void RemoveTrack (QTTrack track); [Export ("delegate"), NullAllowed] NSObject WeakDelegate { get; set; } //[Wrap ("WeakDelegate")] //QTMovieDelegate Delegate { get; set; } //- (Movie)quickTimeMovie; // [Export ("quickTimeMovie")] // Movie QuickTimeMovie (); //- (MovieController)quickTimeMovieController; // [Export ("quickTimeMovieController")] // MovieController QuickTimeMovieController (); //- (void)generateApertureModeDimensions; [Export ("generateApertureModeDimensions")] void GenerateApertureModeDimensions (); //- (void)removeApertureModeDimensions; [Export ("removeApertureModeDimensions")] void RemoveApertureModeDimensions (); //- (QTVisualContextRef)visualContext; // [Export ("visualContext")] // QTVisualContextRef VisualContext (); [Static, Export ("enterQTKitOnThread")] void EnterQTKitOnThread (); [Static, Export ("enterQTKitOnThreadDisablingThreadSafetyProtection")] void EnterQTKitOnThreadDisablingThreadSafetyProtection (); [Static, Export ("exitQTKitOnThread")] void ExitQTKitOnThread (); [Export ("attachToCurrentThread")] bool AttachToCurrentThread (); [Export ("detachFromCurrentThread")] bool DetachFromCurrentThread (); [Export ("isIdling")] bool Idling { get; } [Export ("hasChapters")] bool HasChapters { get; } [Export ("chapterCount")] int ChapterCount { get; } [Export ("chapters")] NSDictionary[] Chapters (); // [Export ("addChapters:withAttributes:error:")] // void AddChaptersWithAttributes (NSArray chapters, NSDictionary attributes, out NSError error); [Export ("removeChapters")] bool RemoveChapters (); [Export ("startTimeOfChapter:")] QTTime StartTimeOfChapter (int chapterIndex); [Export ("chapterIndexForTime:")] int ChapterIndexForTime (QTTime time); // // Pasteboard type // [Field ("QTMoviePasteboardType")] NSString PasteboardType { get; } // // Notifications // [Field ("QTMovieEditabilityDidChangeNotification")] NSString EditabilityDidChangeNotification { get; } [Field ("QTMovieEditedNotification")] NSString EditedNotification { get; } [Field ("QTMovieLoadStateDidChangeNotification")] NSString LoadStateDidChangeNotification { get; } [Field ("QTMovieLoopModeDidChangeNotification")] NSString LoopModeDidChangeNotification { get; } [Field ("QTMovieMessageStringPostedNotification")] NSString MessageStringPostedNotification { get; } [Field ("QTMovieRateDidChangeNotification")] NSString RateDidChangeNotification { get; } [Field ("QTMovieSelectionDidChangeNotification")] NSString SelectionDidChangeNotification { get; } [Field ("QTMovieSizeDidChangeNotification")] NSString SizeDidChangeNotification { get; } [Field ("QTMovieStatusStringPostedNotification")] NSString StatusStringPostedNotification { get; } [Field ("QTMovieTimeDidChangeNotification")] NSString TimeDidChangeNotification { get; } [Field ("QTMovieVolumeDidChangeNotification")] NSString VolumeDidChangeNotification { get; } [Field ("QTMovieDidEndNotification")] NSString DidEndNotification { get; } [Field ("QTMovieChapterDidChangeNotification")] NSString ChapterDidChangeNotification { get; } [Field ("QTMovieChapterListDidChangeNotification")] NSString ChapterListDidChangeNotification { get; } [Field ("QTMovieEnterFullScreenRequestNotification")] NSString EnterFullScreenRequestNotification { get; } [Field ("QTMovieExitFullScreenRequestNotification")] NSString ExitFullScreenRequestNotification { get; } [Field ("QTMovieCloseWindowRequestNotification")] NSString CloseWindowRequestNotification { get; } [Field ("QTMovieApertureModeDidChangeNotification")] NSString ApertureModeDidChangeNotification { get; } // Notification parameters [Field ("QTMovieMessageNotificationParameter")] NSString MessageNotificationParameter { get; } [Field ("QTMovieRateDidChangeNotificationParameter")] NSString RateDidChangeNotificationParameter { get; } [Field ("QTMovieStatusFlagsNotificationParameter")] NSString StatusFlagsNotificationParameter { get; } [Field ("QTMovieStatusCodeNotificationParameter")] NSString StatusCodeNotificationParameter { get; } [Field ("QTMovieStatusStringNotificationParameter")] NSString StatusStringNotificationParameter { get; } [Field ("QTMovieTargetIDNotificationParameter")] NSString TargetIDNotificationParameter { get; } [Field ("QTMovieTargetNameNotificationParameter")] NSString TargetNameNotificationParameter { get; } // WriteToFile parameters [Internal, Field ("QTMovieExport")] // NSNumber Bool NSString KeyExport { get; } [Internal, Field ("QTMovieExportType")] // NSNumber long NSString KeyExportType { get; } [Internal, Field ("QTMovieFlatten")] // NSNumber bool NSString KeyFlatten { get; } [Internal, Field ("QTMovieExportSettings")] // NSData (QTAtomContainer) NSString KeyExportSettings { get; } [Internal, Field ("QTMovieExportManufacturer")] // NSNumber (long) NSString KeyExportManufacturer { get; } // // Add Image // [Internal, Field ("QTAddImageCodecType")] // nsstring NSString ImageCodecType { get; } [Internal, Field ("QTAddImageCodecQuality")] // nsnumber NSString ImageCodecQuality { get; } // data locators for FromAttributes [Field ("QTMovieDataReferenceAttribute")] NSString DataReferenceAttribute { get; } [Field ("QTMoviePasteboardAttribute")] NSString PasteboardAttribute { get; } [Field ("QTMovieDataAttribute")] NSString DataAttribute { get; } // Instantiation options [Field ("QTMovieFileOffsetAttribute")] NSString FileOffsetAttribute { get; } [Field ("QTMovieResolveDataRefsAttribute")] NSString ResolveDataRefsAttribute { get; } [Field ("QTMovieAskUnresolvedDataRefsAttribute")] NSString AskUnresolvedDataRefsAttribute { get; } [Field ("QTMovieOpenAsyncOKAttribute")] NSString OpenAsyncOKAttribute { get; } // movie attributes [Field ("QTMovieApertureModeAttribute")] NSString ApertureModeAttribute { get; } [Field ("QTMovieActiveSegmentAttribute")] NSString ActiveSegmentAttribute { get; } [Field ("QTMovieAutoAlternatesAttribute")] NSString AutoAlternatesAttribute { get; } [Field ("QTMovieCopyrightAttribute")] NSString CopyrightAttribute { get; } [Field ("QTMovieCreationTimeAttribute")] NSString CreationTimeAttribute { get; } [Field ("QTMovieCurrentSizeAttribute")] NSString CurrentSizeAttribute { get; } [Field ("QTMovieCurrentTimeAttribute")] NSString CurrentTimeAttribute { get; } [Field ("QTMovieDataSizeAttribute")] NSString DataSizeAttribute { get; } [Field ("QTMovieDelegateAttribute")] NSString DelegateAttribute { get; } [Field ("QTMovieDisplayNameAttribute")] NSString DisplayNameAttribute { get; } [Field ("QTMovieDontInteractWithUserAttribute")] NSString DontInteractWithUserAttribute { get; } [Field ("QTMovieDurationAttribute")] NSString DurationAttribute { get; } [Field ("QTMovieEditableAttribute")] NSString EditableAttribute { get; } [Field ("QTMovieFileNameAttribute")] NSString FileNameAttribute { get; } [Field ("QTMovieHasApertureModeDimensionsAttribute")] NSString HasApertureModeDimensionsAttribute { get; } [Field ("QTMovieHasAudioAttribute")] NSString HasAudioAttribute { get; } [Field ("QTMovieHasDurationAttribute")] NSString HasDurationAttribute { get; } [Field ("QTMovieHasVideoAttribute")] NSString HasVideoAttribute { get; } [Field ("QTMovieIsActiveAttribute")] NSString IsActiveAttribute { get; } [Field ("QTMovieIsInteractiveAttribute")] NSString IsInteractiveAttribute { get; } [Field ("QTMovieIsLinearAttribute")] NSString IsLinearAttribute { get; } [Field ("QTMovieIsSteppableAttribute")] NSString IsSteppableAttribute { get; } [Field ("QTMovieLoadStateAttribute")] NSString LoadStateAttribute { get; } [Field ("QTMovieLoopsAttribute")] NSString LoopsAttribute { get; } [Field ("QTMovieLoopsBackAndForthAttribute")] NSString LoopsBackAndForthAttribute { get; } [Field ("QTMovieModificationTimeAttribute")] NSString ModificationTimeAttribute { get; } [Field ("QTMovieMutedAttribute")] NSString MutedAttribute { get; } [Field ("QTMovieNaturalSizeAttribute")] NSString NaturalSizeAttribute { get; } [Field ("QTMoviePlaysAllFramesAttribute")] NSString PlaysAllFramesAttribute { get; } [Field ("QTMoviePlaysSelectionOnlyAttribute")] NSString PlaysSelectionOnlyAttribute { get; } [Field ("QTMoviePosterTimeAttribute")] NSString PosterTimeAttribute { get; } [Field ("QTMoviePreferredMutedAttribute")] NSString PreferredMutedAttribute { get; } [Field ("QTMoviePreferredRateAttribute")] NSString PreferredRateAttribute { get; } [Field ("QTMoviePreferredVolumeAttribute")] NSString PreferredVolumeAttribute { get; } [Field ("QTMoviePreviewModeAttribute")] NSString PreviewModeAttribute { get; } [Field ("QTMoviePreviewRangeAttribute")] NSString PreviewRangeAttribute { get; } [Field ("QTMovieRateAttribute")] NSString RateAttribute { get; } [Field ("QTMovieSelectionAttribute")] NSString SelectionAttribute { get; } [Field ("QTMovieTimeScaleAttribute")] NSString TimeScaleAttribute { get; } [Field ("QTMovieURLAttribute")] NSString URLAttribute { get; } [Field ("QTMovieVolumeAttribute")] NSString VolumeAttribute { get; } [Field ("QTMovieRateChangesPreservePitchAttribute")] NSString RateChangesPreservePitchAttribute { get; } [Field ("QTMovieApertureModeClassic")] NSString ApertureModeClassic { get; } [Field ("QTMovieApertureModeClean")] NSString ApertureModeClean { get; } [Field ("QTMovieApertureModeProduction")] NSString ApertureModeProduction { get; } [Field ("QTMovieApertureModeEncodedPixels")] NSString ApertureModeEncodedPixels { get; } [Field ("QTMovieFrameImageSize")] NSString FrameImageSize { get; } [Field ("QTMovieFrameImageType")] NSString FrameImageType { get; } [Field ("QTMovieFrameImageTypeNSImage")] NSString FrameImageTypeNSImage { get; } [Field ("QTMovieFrameImageTypeCGImageRef")] NSString FrameImageTypeCGImageRef { get; } [Field ("QTMovieFrameImageTypeCIImage")] NSString FrameImageTypeCIImage { get; } [Field ("QTMovieFrameImageTypeCVPixelBufferRef")] NSString FrameImageTypeCVPixelBufferRef { get; } [Field ("QTMovieFrameImageTypeCVOpenGLTextureRef")] NSString FrameImageTypeCVOpenGLTextureRef { get; } [Field ("QTMovieFrameImageOpenGLContext")] NSString FrameImageOpenGLContext { get; } [Field ("QTMovieFrameImagePixelFormat")] NSString FrameImagePixelFormat { get; } [Field ("QTMovieFrameImageRepresentationsType")] NSString FrameImageRepresentationsType { get; } [Field ("QTMovieFrameImageDeinterlaceFields")] NSString FrameImageDeinterlaceFields { get; } [Field ("QTMovieFrameImageHighQuality")] NSString FrameImageHighQuality { get; } [Field ("QTMovieFrameImageSingleField")] NSString FrameImageSingleField { get; } [Field ("QTMovieUneditableException")] NSString UneditableException { get; } [Field ("QTMovieChapterName")] NSString ChapterName { get; } [Field ("QTMovieChapterStartTime")] NSString ChapterStartTime { get; } [Field ("QTMovieChapterTargetTrackAttribute")] NSString ChapterTargetTrackAttribute { get; } } [BaseType (typeof (NSObject))] [DisableDefaultCtor] // invalid handle returned interface QTSampleBuffer { [Export ("bytesForAllSamples")] IntPtr BytesForAllSamples { get; } [Export ("lengthForAllSamples")] uint LengthForAllSamples { get; } [Export ("formatDescription")] QTFormatDescription FormatDescription { get; } [Export ("duration")] QTTime Duration { get; } [Export ("decodeTime")] QTTime DecodeTime { get; } [Export ("presentationTime")] QTTime PresentationTime { get; } [Export ("numberOfSamples")] int SampleCount { get; } [Export ("sampleBufferAttributes")] NSDictionary SampleBufferAttributes { get; } [Export ("attributeForKey:")] NSObject GetAttribute (string key); [Export ("sampleUseCount")] int SampleUseCount { get; } [Export ("incrementSampleUseCount")] void IncrementSampleUseCount (); [Export ("decrementSampleUseCount")] void DecrementSampleUseCount (); //[Export ("audioBufferListWithOptions:")] //AudioBufferList AudioBufferListWithOptions (QTSampleBufferAudioBufferListOptions options); //[Export ("getAudioStreamPacketDescriptions:inRange:")] //bool GetAudioStreamPacketDescriptionsinRange (AudioStreamPacketDescription audioStreamPacketDescriptions, NSRange range); } [BaseType (typeof (NSObject))] interface QTTrack { [Static, Export ("trackWithQuickTimeTrack:error:")] NSObject FromQuickTimeTrack (IntPtr quicktimeTrack, out NSError error); [Export ("initWithQuickTimeTrack:error:")] IntPtr Constructor (IntPtr quicktimeTrack, out NSError error); [Export ("movie")] QTMovie Movie { get; } [Export ("media")] QTMedia Media { get; } [Export ("attributeForKey:")] NSObject GetAttribute (string attributeKey); [Export ("setAttribute:forKey:")] void SetAttribute (NSObject value, string attributeKey); [Export ("quickTimeTrack")] IntPtr QuickTimeTrack { get; } [Export ("insertSegmentOfTrack:timeRange:atTime:")] void InsertSegmentOfTrack (QTTrack track, QTTimeRange timeRange, QTTime atTime); [Export ("insertSegmentOfTrack:fromRange:scaledToRange:")] void InsertSegmentOfTrack (QTTrack track, QTTimeRange fromRange, QTTimeRange scaledToRange); [Export ("insertEmptySegmentAt:")] void InsertEmptySegment (QTTimeRange range); [Export ("deleteSegment:")] void DeleteSegment (QTTimeRange segment); [Export ("scaleSegment:newDuration:")] void ScaleSegmentnewDuration (QTTimeRange segment, QTTime newDuration); [Export ("addImage:forDuration:withAttributes:")] void AddImage (NSImage image, QTTime forDuration, NSDictionary attributes); //Detected properties [Export ("enabled")] bool Enabled { [Bind ("isEnabled")]get; set; } [Export ("volume")] float Volume { get; set; } [Export ("trackAttributes")] NSDictionary TrackAttributes { get; set; } [Export ("apertureModeDimensionsForMode:")] SizeF ApertureModeDimensionsForMode (string mode); [Export ("setApertureModeDimensions:forMode:")] void SetApertureModeDimensionsforMode (SizeF dimensions, string mode); [Export ("generateApertureModeDimensions")] void GenerateApertureModeDimensions (); [Export ("removeApertureModeDimensions")] void RemoveApertureModeDimensions (); [Field ("QTTrackBoundsAttribute")] NSString BoundsAttribute { get; } [Field ("QTTrackCreationTimeAttribute")] NSString CreationTimeAttribute { get; } [Field ("QTTrackDimensionsAttribute")] NSString DimensionsAttribute { get; } [Field ("QTTrackDisplayNameAttribute")] NSString DisplayNameAttribute { get; } [Field ("QTTrackEnabledAttribute")] NSString EnabledAttribute { get; } [Field ("QTTrackFormatSummaryAttribute")] NSString FormatSummaryAttribute { get; } [Field ("QTTrackIsChapterTrackAttribute")] NSString IsChapterTrackAttribute { get; } [Field ("QTTrackHasApertureModeDimensionsAttribute")] NSString HasApertureModeDimensionsAttribute { get; } [Field ("QTTrackIDAttribute")] NSString IDAttribute { get; } [Field ("QTTrackLayerAttribute")] NSString LayerAttribute { get; } [Field ("QTTrackMediaTypeAttribute")] NSString MediaTypeAttribute { get; } [Field ("QTTrackModificationTimeAttribute")] NSString ModificationTimeAttribute { get; } [Field ("QTTrackRangeAttribute")] NSString RangeAttribute { get; } [Field ("QTTrackTimeScaleAttribute")] NSString TimeScaleAttribute { get; } [Field ("QTTrackUsageInMovieAttribute")] NSString UsageInMovieAttribute { get; } [Field ("QTTrackUsageInPosterAttribute")] NSString UsageInPosterAttribute { get; } [Field ("QTTrackUsageInPreviewAttribute")] NSString UsageInPreviewAttribute { get; } [Field ("QTTrackVolumeAttribute")] NSString VolumeAttribute { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.WindowsRuntime.Internal; using System.Security; using System.Threading; using Windows.Foundation; using Windows.Storage.Streams; namespace System.Runtime.InteropServices.WindowsRuntime { /// <summary> /// Contains an implementation of the WinRT IBuffer interface that conforms to all requirements on classes that implement that interface, /// such as implementing additional interfaces. /// </summary> public sealed class WindowsRuntimeBuffer : IBuffer, IBufferByteAccess, IMarshal, IAgileObject { #region Constants private const String WinTypesDLL = "WinTypes.dll"; private enum MSHCTX : int { Local = 0, NoSharedMem = 1, DifferentMachine = 2, InProc = 3, CrossCtx = 4 } private enum MSHLFLAGS : int { Normal = 0, TableStrong = 1, TableWeak = 2, NoPing = 4 } #endregion Constants #region Static factory methods [CLSCompliant(false)] public static IBuffer Create(Int32 capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity)); Contract.Ensures(Contract.Result<IBuffer>() != null); Contract.Ensures(Contract.Result<IBuffer>().Length == unchecked((UInt32)0)); Contract.Ensures(Contract.Result<IBuffer>().Capacity == unchecked((UInt32)capacity)); Contract.EndContractBlock(); return new WindowsRuntimeBuffer(capacity); } [CLSCompliant(false)] public static IBuffer Create(Byte[] data, Int32 offset, Int32 length, Int32 capacity) { if (data == null) throw new ArgumentNullException(nameof(data)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length)); if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity)); if (data.Length - offset < length) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); if (data.Length - offset < capacity) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); if (capacity < length) throw new ArgumentException(SR.Argument_InsufficientBufferCapacity); Contract.Ensures(Contract.Result<IBuffer>() != null); Contract.Ensures(Contract.Result<IBuffer>().Length == unchecked((UInt32)length)); Contract.Ensures(Contract.Result<IBuffer>().Capacity == unchecked((UInt32)capacity)); Contract.EndContractBlock(); Byte[] underlyingData = new Byte[capacity]; Buffer.BlockCopy(data, offset, underlyingData, 0, length); return new WindowsRuntimeBuffer(underlyingData, 0, length, capacity); } #endregion Static factory methods #region Static fields and helpers // This object handles IMarshal calls for us: [ThreadStatic] private static IMarshal s_winRtMarshalProxy = null; private static void EnsureHasMarshalProxy() { if (s_winRtMarshalProxy != null) return; try { IMarshal proxy; Int32 hr = Interop.mincore.RoGetBufferMarshaler(out proxy); s_winRtMarshalProxy = proxy; if (hr != HResults.S_OK) { Exception ex = new Exception(String.Format("{0} ({1}!RoGetBufferMarshaler)", SR.WinRtCOM_Error, WinTypesDLL)); ex.SetErrorCode(hr); throw ex; } if (proxy == null) throw new NullReferenceException(String.Format("{0} ({1}!RoGetBufferMarshaler)", SR.WinRtCOM_Error, WinTypesDLL)); } catch (DllNotFoundException ex) { throw new NotImplementedException(SR.Format(SR.NotImplemented_NativeRoutineNotFound, String.Format("{0}!RoGetBufferMarshaler", WinTypesDLL)), ex); } } #endregion Static fields and helpers #region Fields private Byte[] _data = null; private Int32 _dataStartOffs = 0; private Int32 _usefulDataLength = 0; private Int32 _maxDataCapacity = 0; private GCHandle _pinHandle; // Pointer to data[dataStartOffs] when data is pinned: private IntPtr _dataPtr = IntPtr.Zero; #endregion Fields #region Constructors internal WindowsRuntimeBuffer(Int32 capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity)); Contract.EndContractBlock(); _data = new Byte[capacity]; _dataStartOffs = 0; _usefulDataLength = 0; _maxDataCapacity = capacity; _dataPtr = IntPtr.Zero; } internal WindowsRuntimeBuffer(Byte[] data, Int32 offset, Int32 length, Int32 capacity) { if (data == null) throw new ArgumentNullException(nameof(data)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length)); if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity)); if (data.Length - offset < length) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); if (data.Length - offset < capacity) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); if (capacity < length) throw new ArgumentException(SR.Argument_InsufficientBufferCapacity); Contract.EndContractBlock(); _data = data; _dataStartOffs = offset; _usefulDataLength = length; _maxDataCapacity = capacity; _dataPtr = IntPtr.Zero; } #endregion Constructors #region Helpers internal void GetUnderlyingData(out Byte[] underlyingDataArray, out Int32 underlyingDataArrayStartOffset) { underlyingDataArray = _data; underlyingDataArrayStartOffset = _dataStartOffs; } private unsafe Byte* PinUnderlyingData() { GCHandle gcHandle = default(GCHandle); bool ptrWasStored = false; IntPtr buffPtr; try { } finally { try { // Pin the the data array: gcHandle = GCHandle.Alloc(_data, GCHandleType.Pinned); buffPtr = gcHandle.AddrOfPinnedObject() + _dataStartOffs; // Store the pin IFF it has not been assigned: ptrWasStored = (Interlocked.CompareExchange(ref _dataPtr, buffPtr, IntPtr.Zero) == IntPtr.Zero); } finally { if (!ptrWasStored) { // There is a race with another thread also trying to create a pin and they were first // in assigning to data pin. That's ok, just give it up. // Unpin again (the pin from the other thread remains): gcHandle.Free(); } else { if (_pinHandle.IsAllocated) _pinHandle.Free(); // Make sure we keep track of the handle _pinHandle = gcHandle; } } } // Ok, now all is good: return (Byte*)buffPtr; } ~WindowsRuntimeBuffer() { if (_pinHandle.IsAllocated) _pinHandle.Free(); } #endregion Helpers #region Implementation of Windows.Foundation.IBuffer UInt32 IBuffer.Capacity { get { return unchecked((UInt32)_maxDataCapacity); } } UInt32 IBuffer.Length { get { return unchecked((UInt32)_usefulDataLength); } set { if (value > ((IBuffer)this).Capacity) { ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException(nameof(value), SR.Argument_BufferLengthExceedsCapacity); ex.SetErrorCode(HResults.E_BOUNDS); throw ex; } // Capacity is ensured to not exceed Int32.MaxValue, so Length is within this limit and this cast is safe: Debug.Assert(((IBuffer)this).Capacity <= Int32.MaxValue); _usefulDataLength = unchecked((Int32)value); } } #endregion Implementation of Windows.Foundation.IBuffer #region Implementation of IBufferByteAccess unsafe IntPtr IBufferByteAccess.GetBuffer() { // Get pin handle: IntPtr buffPtr = Volatile.Read(ref _dataPtr); // If we are already pinned, return the pointer and have a nice day: if (buffPtr != IntPtr.Zero) return buffPtr; // Ok, we we are not yet pinned. Let's do it. return new IntPtr(PinUnderlyingData()); } #endregion Implementation of IBufferByteAccess #region Implementation of IMarshal void IMarshal.DisconnectObject(UInt32 dwReserved) { EnsureHasMarshalProxy(); s_winRtMarshalProxy.DisconnectObject(dwReserved); } void IMarshal.GetMarshalSizeMax(ref Guid riid, IntPtr pv, UInt32 dwDestContext, IntPtr pvDestContext, UInt32 mshlflags, out UInt32 pSize) { EnsureHasMarshalProxy(); s_winRtMarshalProxy.GetMarshalSizeMax(ref riid, pv, dwDestContext, pvDestContext, mshlflags, out pSize); } void IMarshal.GetUnmarshalClass(ref Guid riid, IntPtr pv, UInt32 dwDestContext, IntPtr pvDestContext, UInt32 mshlFlags, out Guid pCid) { EnsureHasMarshalProxy(); s_winRtMarshalProxy.GetUnmarshalClass(ref riid, pv, dwDestContext, pvDestContext, mshlFlags, out pCid); } void IMarshal.MarshalInterface(IntPtr pStm, ref Guid riid, IntPtr pv, UInt32 dwDestContext, IntPtr pvDestContext, UInt32 mshlflags) { EnsureHasMarshalProxy(); s_winRtMarshalProxy.MarshalInterface(pStm, ref riid, pv, dwDestContext, pvDestContext, mshlflags); } void IMarshal.ReleaseMarshalData(IntPtr pStm) { EnsureHasMarshalProxy(); s_winRtMarshalProxy.ReleaseMarshalData(pStm); } void IMarshal.UnmarshalInterface(IntPtr pStm, ref Guid riid, out IntPtr ppv) { EnsureHasMarshalProxy(); s_winRtMarshalProxy.UnmarshalInterface(pStm, ref riid, out ppv); } #endregion Implementation of IMarshal } // class WindowsRuntimeBuffer } // namespace // WindowsRuntimeBuffer.cs
namespace Ferric.Text.WordNet.Migrations { using System; using System.Data.Entity.Migrations; public partial class InitialCreate : DbMigration { public override void Up() { CreateTable( "dbo.SemanticClasses", c => new { SemanticClassId = c.Int(nullable: false, identity: true), ClassType = c.Int(nullable: false), }) .PrimaryKey(t => t.SemanticClassId); CreateTable( "dbo.WordSenses", c => new { WordSenseId = c.Int(nullable: false, identity: true), WordNum = c.Int(nullable: false), Lemma = c.String(nullable: false, maxLength: 200), SenseNumber = c.Int(nullable: false), TagCount = c.Int(), SenseKey = c.String(maxLength: 200), Syntax = c.Int(), Frame = c.Int(), SynsetId = c.Int(), }) .PrimaryKey(t => t.WordSenseId) .ForeignKey("dbo.Synsets", t => t.SynsetId) .Index(t => t.SynsetId); CreateTable( "dbo.Synsets", c => new { SynsetId = c.Int(nullable: false, identity: true), WordNetId = c.Int(nullable: false), SynsetType = c.Int(nullable: false), Gloss = c.String(maxLength: 1000), }) .PrimaryKey(t => t.SynsetId); CreateTable( "dbo.Antonyms", c => new { FirstWordSenseId = c.Int(nullable: false), SecondWordSenseId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstWordSenseId, t.SecondWordSenseId }) .ForeignKey("dbo.WordSenses", t => t.FirstWordSenseId) .ForeignKey("dbo.WordSenses", t => t.SecondWordSenseId) .Index(t => t.FirstWordSenseId) .Index(t => t.SecondWordSenseId); CreateTable( "dbo.Derivations", c => new { FirstWordSenseId = c.Int(nullable: false), SecondWordSenseId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstWordSenseId, t.SecondWordSenseId }) .ForeignKey("dbo.WordSenses", t => t.FirstWordSenseId) .ForeignKey("dbo.WordSenses", t => t.SecondWordSenseId) .Index(t => t.FirstWordSenseId) .Index(t => t.SecondWordSenseId); CreateTable( "dbo.Participles", c => new { FirstWordSenseId = c.Int(nullable: false), SecondWordSenseId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstWordSenseId, t.SecondWordSenseId }) .ForeignKey("dbo.WordSenses", t => t.FirstWordSenseId) .ForeignKey("dbo.WordSenses", t => t.SecondWordSenseId) .Index(t => t.FirstWordSenseId) .Index(t => t.SecondWordSenseId); CreateTable( "dbo.PertainsTo", c => new { FirstWordSenseId = c.Int(nullable: false), SecondWordSenseId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstWordSenseId, t.SecondWordSenseId }) .ForeignKey("dbo.WordSenses", t => t.FirstWordSenseId) .ForeignKey("dbo.WordSenses", t => t.SecondWordSenseId) .Index(t => t.FirstWordSenseId) .Index(t => t.SecondWordSenseId); CreateTable( "dbo.SeeAlsos", c => new { FirstWordSenseId = c.Int(nullable: false), SecondWordSenseId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstWordSenseId, t.SecondWordSenseId }) .ForeignKey("dbo.WordSenses", t => t.FirstWordSenseId) .ForeignKey("dbo.WordSenses", t => t.SecondWordSenseId) .Index(t => t.FirstWordSenseId) .Index(t => t.SecondWordSenseId); CreateTable( "dbo.Attributes", c => new { FirstSynsetId = c.Int(nullable: false), SecondSynsetId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstSynsetId, t.SecondSynsetId }) .ForeignKey("dbo.Synsets", t => t.FirstSynsetId) .ForeignKey("dbo.Synsets", t => t.SecondSynsetId) .Index(t => t.FirstSynsetId) .Index(t => t.SecondSynsetId); CreateTable( "dbo.Causes", c => new { FirstSynsetId = c.Int(nullable: false), SecondSynsetId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstSynsetId, t.SecondSynsetId }) .ForeignKey("dbo.Synsets", t => t.FirstSynsetId) .ForeignKey("dbo.Synsets", t => t.SecondSynsetId) .Index(t => t.FirstSynsetId) .Index(t => t.SecondSynsetId); CreateTable( "dbo.Entailments", c => new { FirstSynsetId = c.Int(nullable: false), SecondSynsetId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstSynsetId, t.SecondSynsetId }) .ForeignKey("dbo.Synsets", t => t.FirstSynsetId) .ForeignKey("dbo.Synsets", t => t.SecondSynsetId) .Index(t => t.FirstSynsetId) .Index(t => t.SecondSynsetId); CreateTable( "dbo.Groups", c => new { FirstSynsetId = c.Int(nullable: false), SecondSynsetId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstSynsetId, t.SecondSynsetId }) .ForeignKey("dbo.Synsets", t => t.FirstSynsetId) .ForeignKey("dbo.Synsets", t => t.SecondSynsetId) .Index(t => t.FirstSynsetId) .Index(t => t.SecondSynsetId); CreateTable( "dbo.Hypernyms", c => new { FirstSynsetId = c.Int(nullable: false), SecondSynsetId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstSynsetId, t.SecondSynsetId }) .ForeignKey("dbo.Synsets", t => t.FirstSynsetId) .ForeignKey("dbo.Synsets", t => t.SecondSynsetId) .Index(t => t.FirstSynsetId) .Index(t => t.SecondSynsetId); CreateTable( "dbo.Hyponyms", c => new { FirstSynsetId = c.Int(nullable: false), SecondSynsetId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstSynsetId, t.SecondSynsetId }) .ForeignKey("dbo.Synsets", t => t.FirstSynsetId) .ForeignKey("dbo.Synsets", t => t.SecondSynsetId) .Index(t => t.FirstSynsetId) .Index(t => t.SecondSynsetId); CreateTable( "dbo.Instances", c => new { FirstSynsetId = c.Int(nullable: false), SecondSynsetId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstSynsetId, t.SecondSynsetId }) .ForeignKey("dbo.Synsets", t => t.FirstSynsetId) .ForeignKey("dbo.Synsets", t => t.SecondSynsetId) .Index(t => t.FirstSynsetId) .Index(t => t.SecondSynsetId); CreateTable( "dbo.MemberHolonyms", c => new { FirstSynsetId = c.Int(nullable: false), SecondSynsetId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstSynsetId, t.SecondSynsetId }) .ForeignKey("dbo.Synsets", t => t.FirstSynsetId) .ForeignKey("dbo.Synsets", t => t.SecondSynsetId) .Index(t => t.FirstSynsetId) .Index(t => t.SecondSynsetId); CreateTable( "dbo.MemberMeronyms", c => new { FirstSynsetId = c.Int(nullable: false), SecondSynsetId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstSynsetId, t.SecondSynsetId }) .ForeignKey("dbo.Synsets", t => t.FirstSynsetId) .ForeignKey("dbo.Synsets", t => t.SecondSynsetId) .Index(t => t.FirstSynsetId) .Index(t => t.SecondSynsetId); CreateTable( "dbo.PartHolonyms", c => new { FirstSynsetId = c.Int(nullable: false), SecondSynsetId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstSynsetId, t.SecondSynsetId }) .ForeignKey("dbo.Synsets", t => t.FirstSynsetId) .ForeignKey("dbo.Synsets", t => t.SecondSynsetId) .Index(t => t.FirstSynsetId) .Index(t => t.SecondSynsetId); CreateTable( "dbo.PartMeronyms", c => new { FirstSynsetId = c.Int(nullable: false), SecondSynsetId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstSynsetId, t.SecondSynsetId }) .ForeignKey("dbo.Synsets", t => t.FirstSynsetId) .ForeignKey("dbo.Synsets", t => t.SecondSynsetId) .Index(t => t.FirstSynsetId) .Index(t => t.SecondSynsetId); CreateTable( "dbo.Prototypes", c => new { FirstSynsetId = c.Int(nullable: false), SecondSynsetId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstSynsetId, t.SecondSynsetId }) .ForeignKey("dbo.Synsets", t => t.FirstSynsetId) .ForeignKey("dbo.Synsets", t => t.SecondSynsetId) .Index(t => t.FirstSynsetId) .Index(t => t.SecondSynsetId); CreateTable( "dbo.Satellites", c => new { FirstSynsetId = c.Int(nullable: false), SecondSynsetId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstSynsetId, t.SecondSynsetId }) .ForeignKey("dbo.Synsets", t => t.FirstSynsetId) .ForeignKey("dbo.Synsets", t => t.SecondSynsetId) .Index(t => t.FirstSynsetId) .Index(t => t.SecondSynsetId); CreateTable( "dbo.SubstanceHolonyms", c => new { FirstSynsetId = c.Int(nullable: false), SecondSynsetId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstSynsetId, t.SecondSynsetId }) .ForeignKey("dbo.Synsets", t => t.FirstSynsetId) .ForeignKey("dbo.Synsets", t => t.SecondSynsetId) .Index(t => t.FirstSynsetId) .Index(t => t.SecondSynsetId); CreateTable( "dbo.SubstanceMeronyms", c => new { FirstSynsetId = c.Int(nullable: false), SecondSynsetId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.FirstSynsetId, t.SecondSynsetId }) .ForeignKey("dbo.Synsets", t => t.FirstSynsetId) .ForeignKey("dbo.Synsets", t => t.SecondSynsetId) .Index(t => t.FirstSynsetId) .Index(t => t.SecondSynsetId); CreateTable( "dbo.SemanticClassHeads", c => new { SemanticClassId = c.Int(nullable: false), WordSenseId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.SemanticClassId, t.WordSenseId }) .ForeignKey("dbo.SemanticClasses", t => t.SemanticClassId, cascadeDelete: true) .ForeignKey("dbo.WordSenses", t => t.WordSenseId, cascadeDelete: true) .Index(t => t.SemanticClassId) .Index(t => t.WordSenseId); CreateTable( "dbo.SemanticClassMembers", c => new { SemanticClassId = c.Int(nullable: false), WordSenseId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.SemanticClassId, t.WordSenseId }) .ForeignKey("dbo.SemanticClasses", t => t.SemanticClassId, cascadeDelete: true) .ForeignKey("dbo.WordSenses", t => t.WordSenseId, cascadeDelete: true) .Index(t => t.SemanticClassId) .Index(t => t.WordSenseId); } public override void Down() { DropForeignKey("dbo.SemanticClassMembers", "WordSenseId", "dbo.WordSenses"); DropForeignKey("dbo.SemanticClassMembers", "SemanticClassId", "dbo.SemanticClasses"); DropForeignKey("dbo.SemanticClassHeads", "WordSenseId", "dbo.WordSenses"); DropForeignKey("dbo.SemanticClassHeads", "SemanticClassId", "dbo.SemanticClasses"); DropForeignKey("dbo.SubstanceMeronyms", "SecondSynsetId", "dbo.Synsets"); DropForeignKey("dbo.SubstanceMeronyms", "FirstSynsetId", "dbo.Synsets"); DropForeignKey("dbo.SubstanceHolonyms", "SecondSynsetId", "dbo.Synsets"); DropForeignKey("dbo.SubstanceHolonyms", "FirstSynsetId", "dbo.Synsets"); DropForeignKey("dbo.WordSenses", "SynsetId", "dbo.Synsets"); DropForeignKey("dbo.Satellites", "SecondSynsetId", "dbo.Synsets"); DropForeignKey("dbo.Satellites", "FirstSynsetId", "dbo.Synsets"); DropForeignKey("dbo.Prototypes", "SecondSynsetId", "dbo.Synsets"); DropForeignKey("dbo.Prototypes", "FirstSynsetId", "dbo.Synsets"); DropForeignKey("dbo.PartMeronyms", "SecondSynsetId", "dbo.Synsets"); DropForeignKey("dbo.PartMeronyms", "FirstSynsetId", "dbo.Synsets"); DropForeignKey("dbo.PartHolonyms", "SecondSynsetId", "dbo.Synsets"); DropForeignKey("dbo.PartHolonyms", "FirstSynsetId", "dbo.Synsets"); DropForeignKey("dbo.MemberMeronyms", "SecondSynsetId", "dbo.Synsets"); DropForeignKey("dbo.MemberMeronyms", "FirstSynsetId", "dbo.Synsets"); DropForeignKey("dbo.MemberHolonyms", "SecondSynsetId", "dbo.Synsets"); DropForeignKey("dbo.MemberHolonyms", "FirstSynsetId", "dbo.Synsets"); DropForeignKey("dbo.Instances", "SecondSynsetId", "dbo.Synsets"); DropForeignKey("dbo.Instances", "FirstSynsetId", "dbo.Synsets"); DropForeignKey("dbo.Hyponyms", "SecondSynsetId", "dbo.Synsets"); DropForeignKey("dbo.Hyponyms", "FirstSynsetId", "dbo.Synsets"); DropForeignKey("dbo.Hypernyms", "SecondSynsetId", "dbo.Synsets"); DropForeignKey("dbo.Hypernyms", "FirstSynsetId", "dbo.Synsets"); DropForeignKey("dbo.Groups", "SecondSynsetId", "dbo.Synsets"); DropForeignKey("dbo.Groups", "FirstSynsetId", "dbo.Synsets"); DropForeignKey("dbo.Entailments", "SecondSynsetId", "dbo.Synsets"); DropForeignKey("dbo.Entailments", "FirstSynsetId", "dbo.Synsets"); DropForeignKey("dbo.Causes", "SecondSynsetId", "dbo.Synsets"); DropForeignKey("dbo.Causes", "FirstSynsetId", "dbo.Synsets"); DropForeignKey("dbo.Attributes", "SecondSynsetId", "dbo.Synsets"); DropForeignKey("dbo.Attributes", "FirstSynsetId", "dbo.Synsets"); DropForeignKey("dbo.SeeAlsos", "SecondWordSenseId", "dbo.WordSenses"); DropForeignKey("dbo.SeeAlsos", "FirstWordSenseId", "dbo.WordSenses"); DropForeignKey("dbo.PertainsTo", "SecondWordSenseId", "dbo.WordSenses"); DropForeignKey("dbo.PertainsTo", "FirstWordSenseId", "dbo.WordSenses"); DropForeignKey("dbo.Participles", "SecondWordSenseId", "dbo.WordSenses"); DropForeignKey("dbo.Participles", "FirstWordSenseId", "dbo.WordSenses"); DropForeignKey("dbo.Derivations", "SecondWordSenseId", "dbo.WordSenses"); DropForeignKey("dbo.Derivations", "FirstWordSenseId", "dbo.WordSenses"); DropForeignKey("dbo.Antonyms", "SecondWordSenseId", "dbo.WordSenses"); DropForeignKey("dbo.Antonyms", "FirstWordSenseId", "dbo.WordSenses"); DropIndex("dbo.SemanticClassMembers", new[] { "WordSenseId" }); DropIndex("dbo.SemanticClassMembers", new[] { "SemanticClassId" }); DropIndex("dbo.SemanticClassHeads", new[] { "WordSenseId" }); DropIndex("dbo.SemanticClassHeads", new[] { "SemanticClassId" }); DropIndex("dbo.SubstanceMeronyms", new[] { "SecondSynsetId" }); DropIndex("dbo.SubstanceMeronyms", new[] { "FirstSynsetId" }); DropIndex("dbo.SubstanceHolonyms", new[] { "SecondSynsetId" }); DropIndex("dbo.SubstanceHolonyms", new[] { "FirstSynsetId" }); DropIndex("dbo.Satellites", new[] { "SecondSynsetId" }); DropIndex("dbo.Satellites", new[] { "FirstSynsetId" }); DropIndex("dbo.Prototypes", new[] { "SecondSynsetId" }); DropIndex("dbo.Prototypes", new[] { "FirstSynsetId" }); DropIndex("dbo.PartMeronyms", new[] { "SecondSynsetId" }); DropIndex("dbo.PartMeronyms", new[] { "FirstSynsetId" }); DropIndex("dbo.PartHolonyms", new[] { "SecondSynsetId" }); DropIndex("dbo.PartHolonyms", new[] { "FirstSynsetId" }); DropIndex("dbo.MemberMeronyms", new[] { "SecondSynsetId" }); DropIndex("dbo.MemberMeronyms", new[] { "FirstSynsetId" }); DropIndex("dbo.MemberHolonyms", new[] { "SecondSynsetId" }); DropIndex("dbo.MemberHolonyms", new[] { "FirstSynsetId" }); DropIndex("dbo.Instances", new[] { "SecondSynsetId" }); DropIndex("dbo.Instances", new[] { "FirstSynsetId" }); DropIndex("dbo.Hyponyms", new[] { "SecondSynsetId" }); DropIndex("dbo.Hyponyms", new[] { "FirstSynsetId" }); DropIndex("dbo.Hypernyms", new[] { "SecondSynsetId" }); DropIndex("dbo.Hypernyms", new[] { "FirstSynsetId" }); DropIndex("dbo.Groups", new[] { "SecondSynsetId" }); DropIndex("dbo.Groups", new[] { "FirstSynsetId" }); DropIndex("dbo.Entailments", new[] { "SecondSynsetId" }); DropIndex("dbo.Entailments", new[] { "FirstSynsetId" }); DropIndex("dbo.Causes", new[] { "SecondSynsetId" }); DropIndex("dbo.Causes", new[] { "FirstSynsetId" }); DropIndex("dbo.Attributes", new[] { "SecondSynsetId" }); DropIndex("dbo.Attributes", new[] { "FirstSynsetId" }); DropIndex("dbo.SeeAlsos", new[] { "SecondWordSenseId" }); DropIndex("dbo.SeeAlsos", new[] { "FirstWordSenseId" }); DropIndex("dbo.PertainsTo", new[] { "SecondWordSenseId" }); DropIndex("dbo.PertainsTo", new[] { "FirstWordSenseId" }); DropIndex("dbo.Participles", new[] { "SecondWordSenseId" }); DropIndex("dbo.Participles", new[] { "FirstWordSenseId" }); DropIndex("dbo.Derivations", new[] { "SecondWordSenseId" }); DropIndex("dbo.Derivations", new[] { "FirstWordSenseId" }); DropIndex("dbo.Antonyms", new[] { "SecondWordSenseId" }); DropIndex("dbo.Antonyms", new[] { "FirstWordSenseId" }); DropIndex("dbo.WordSenses", new[] { "SynsetId" }); DropTable("dbo.SemanticClassMembers"); DropTable("dbo.SemanticClassHeads"); DropTable("dbo.SubstanceMeronyms"); DropTable("dbo.SubstanceHolonyms"); DropTable("dbo.Satellites"); DropTable("dbo.Prototypes"); DropTable("dbo.PartMeronyms"); DropTable("dbo.PartHolonyms"); DropTable("dbo.MemberMeronyms"); DropTable("dbo.MemberHolonyms"); DropTable("dbo.Instances"); DropTable("dbo.Hyponyms"); DropTable("dbo.Hypernyms"); DropTable("dbo.Groups"); DropTable("dbo.Entailments"); DropTable("dbo.Causes"); DropTable("dbo.Attributes"); DropTable("dbo.SeeAlsos"); DropTable("dbo.PertainsTo"); DropTable("dbo.Participles"); DropTable("dbo.Derivations"); DropTable("dbo.Antonyms"); DropTable("dbo.Synsets"); DropTable("dbo.WordSenses"); DropTable("dbo.SemanticClasses"); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using System.Text; using Microsoft.Research.DataStructures; using System.CodeDom.Compiler; using System.Diagnostics.Contracts; namespace Microsoft.Research.CodeAnalysis { /// <summary> /// Filters output based on an existing baseline. If an outcome is in the baseline, it is not emitted. /// </summary> class XmlBaseLineComparer<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> : XmlBaseLine<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>, IOutputFullResults<Method, Assembly> where Type : IEquatable<Type> { private readonly SwallowedBuckets swallowedCounter; int additionalErrors; int methodsUnmatched; XElement baseLineRoot; CacheManager<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue> cacheManager; public XmlBaseLineComparer(IOutputFullResults<Method, Assembly> output, GeneralOptions options, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder, CacheManager<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue> cacheManager, string xmlBaseLineFile) : base(output, options, mdDecoder) { this.cacheManager = cacheManager; try { this.baseLineRoot = XElement.Load(xmlBaseLineFile); // gets pool of *all* expected outcomes (currently, does not distinguish by method) expectedAssemblyOutcomes = BaseLineOutcomes.GetOutcomes(this.GetAssemblyRoots(), this.options.baseLineStrategy); } catch (System.Xml.XmlException) { output.WriteLine("Error: baseline file {0} is corrupted", xmlBaseLineFile); Environment.Exit(-1); } this.swallowedCounter = new SwallowedBuckets(); } #region IOutputFullResults<Method> Members public string Name { get { return this.output.Name; } } public int SwallowedMessagesCount(ProofOutcome outcome) { return this.swallowedCounter.GetCounter(outcome); } Assembly currentAssembly; Method currentMethod; BaseLineOutcomes expectedMethodOutcomes; // initialied when entering a method BaseLineOutcomes expectedAssemblyOutcomes; // initialized during entire run public void StartAssembly(Assembly assembly) { output.StartAssembly(assembly); this.currentAssembly = assembly; } public void EndAssembly() { this.currentAssembly = default(Assembly); output.EndAssembly(); } public void StartMethod(Method method) { output.StartMethod(method); IEnumerable<XElement> methodRoots = this.GetMethodRoots(method); if (!methodRoots.Any()) { //output.WriteLine("No matches for method {0} ", mdDecoder.FullName(method)); methodsUnmatched++; } else { //output.WriteLine("Found baseline for method {0} ", mdDecoder.FullName(method)); } expectedMethodOutcomes = BaseLineOutcomes.GetOutcomesForMethod(methodRoots, this.options.baseLineStrategy); //BaseLineOutcomes.GetOutcomes(methodRoots, this.options.baseLineStrategy); this.currentMethod = method; } public void EndMethod(APC methodEntry, bool ignoreMethodEntryAPC = false) { if (!expectedMethodOutcomes.Passed) { output.WriteLine("Method {0} has new failures", mdDecoder.FullName(this.currentMethod)); } this.additionalErrors += expectedMethodOutcomes.Errors; output.EndMethod(methodEntry, ignoreMethodEntryAPC); expectedMethodOutcomes = null; } public bool IsMasked(Witness witness) { return this.output.IsMasked(witness); } public void WriteLine(string format, params object[] args) { output.WriteLine(format, args); } public void Statistic(string format, params object[] args) { output.Statistic(format, args); } public void FinalStatistic(string assemblyName, string msg) { output.FinalStatistic(assemblyName, msg); } public void Suggestion(ClousotSuggestion.Kind type, string kind, APC pc, string suggestion, List<uint> causes, ClousotSuggestion.ExtraSuggestionInfo extraInfo) { int primaryILOffset, methodILOffset; GetILOffsets(pc, this.currentMethod, out primaryILOffset, out methodILOffset); if (!this.expectedMethodOutcomes.CheckOutcome(WarningKind.Informational, output, this.currentMethod, ProofOutcome.Bottom, suggestion, primaryILOffset, methodILOffset, this.mdDecoder, this.cacheManager)) { // show suggestion output.Suggestion(type, kind, pc, suggestion, causes, extraInfo); // don't count as an error } } public bool EmitOutcome(Witness witness, string format, params object[] args) { string message = String.Format(format, args); int primaryILOffset, methodILOffset; GetILOffsets(witness.PC, this.currentMethod, out primaryILOffset, out methodILOffset); // if (!this.expectedMethodOutcomes.CheckOutcome(witness.WarningKind, output, this.currentMethod, witness.Outcome, message, primaryILOffset, methodILOffset, this.mdDecoder)) if (!this.expectedMethodOutcomes.CheckOutcome(witness.WarningKind, output, this.currentMethod, witness.Outcome, message, primaryILOffset, methodILOffset, this.mdDecoder, this.cacheManager)) { // show outcome var result = output.EmitOutcome(witness, format, args); if (!result) { this.swallowedCounter.UpdateCounter(witness.Outcome); } return result; } else { this.swallowedCounter.UpdateCounter(witness.Outcome); return false; } } public bool EmitOutcomeAndRelated(Witness witness, string format, params object[] args) { string message = String.Format(format, args); int primaryILOffset, methodILOffset; GetILOffsets(witness.PC, this.currentMethod, out primaryILOffset, out methodILOffset); if (!this.expectedMethodOutcomes.CheckOutcome(witness.WarningKind, output, this.currentMethod, witness.Outcome, message, primaryILOffset, methodILOffset, this.mdDecoder, this.cacheManager)) { // show outcome var result = output.EmitOutcomeAndRelated(witness, format, args); if (!result) { this.swallowedCounter.UpdateCounter(witness.Outcome); } return result; } else { this.swallowedCounter.UpdateCounter(witness.Outcome); return false; } } private static void GetILOffsets(APC pc, Method method, out int primaryILOffset, out int methodILOffset) { primaryILOffset = pc.ILOffset; if (pc.Block.Subroutine.IsMethod) { methodILOffset = 0; return; } // look through context FList<STuple<CFGBlock, CFGBlock, string>> context = pc.SubroutineContext; while (context != null) { if (context.Head.One.Subroutine.IsMethod) { methodILOffset = context.Head.Two.First.ILOffset; if (methodILOffset == 0) { methodILOffset = context.Head.One.PriorLast.ILOffset; } return; } context = context.Tail; } methodILOffset = primaryILOffset; } public void EmitError(System.CodeDom.Compiler.CompilerError error) { if (this.expectedAssemblyOutcomes == null) { throw new ApplicationException("got error but assembly outcomes not initialized"); } else { if (this.expectedMethodOutcomes != null) { // we are inside a method if (!this.expectedMethodOutcomes.CheckOutcome(error)) { // show outcome output.EmitError(error); } } else { if (!this.expectedAssemblyOutcomes.CheckOutcome(error)) { // show outcome output.EmitError(error); } } } } public void Close() { output.Close(); } public int RegressionErrors() { int localAdditionalErrors = additionalErrors + expectedAssemblyOutcomes.Errors; int total = localAdditionalErrors; if (total == 0) { output.WriteLine("No failures in addition to baseline."); } else { output.WriteLine("Run has {0} additional failures over baseline. New errors in {1}", localAdditionalErrors.ToString(), output.Name); output.WriteLine("Failed to match {0} methods", methodsUnmatched); } return total; } IFrameworkLogOptions IOutput.LogOptions { get { return this.options; } } public ILogOptions LogOptions { get { return this.options; } } public bool ErrorsWereEmitted { get { return this.output.ErrorsWereEmitted; } } #endregion #region Locating all method outcomes private IEnumerable<XElement> GetMethodRoots(Method method) { string canonicalMethodName = CanonicalMethodName(method, this.mdDecoder); IEnumerable<XElement> result = from elem in baseLineRoot.Descendants("Method") where (string)elem.Attribute("Name") == canonicalMethodName select elem; return result; } #endregion #region Locating assembly outcomes private IEnumerable<XElement> GetAssemblyRoots() { yield return baseLineRoot; } #endregion private class BaseLineOutcomes { Set<string> expectedOutcomes; Set<string> actualOutcomes = new Set<string>(); int errorCount = 0; // string representation of the Clousot hash of the current method string methodHash; // hack to prevent multiple counting of method hash match failures. has to be done because when we construct the baseline outcomes for a method, we haven't computed its hash yet... bool checkedHashMatch = false; BaseLiningOptions baselineStrategy; public BaseLineOutcomes(Set<string> outcomes, BaseLiningOptions baselineStrategy) { this.expectedOutcomes = outcomes; this.baselineStrategy = baselineStrategy; } public BaseLineOutcomes(Set<string> outcomes, BaseLiningOptions baselineStrategy, string methodHash) { this.expectedOutcomes = outcomes; this.baselineStrategy = baselineStrategy; this.methodHash = methodHash; } /* public bool MatchesMethodHash(string otherHash) { return methodHash == otherHash; } */ public static BaseLineOutcomes GetOutcomesForMethod(IEnumerable<XElement> methodElements, BaseLiningOptions baselineStrategy) { Set<string> outcomes = new Set<string>(); string hash = null; Contract.Assert(methodElements.Count() < 2, string.Format("Not sure what to do with {0} method elements ", methodElements.Count())); // TODO: make more LINQ-y and concise foreach (XElement methodElement in methodElements) { // save the hash of this element so we can check if it has changed in the current version var hashElem = methodElement.Attribute("Hash"); hash = hashElem != null ? hashElem.Value : "NONE"; foreach (XElement outcomeElement in methodElement.Elements("Outcome")) { outcomes.Add(Canonicalize(methodElement.FirstAttribute.Value, outcomeElement, baselineStrategy)); } } return new BaseLineOutcomes(outcomes, baselineStrategy, hash); } public static BaseLineOutcomes GetOutcomes(IEnumerable<XElement> methodElements, BaseLiningOptions baselineStrategy) { /* IEnumerable<string> outcomeStrings = from o in methodElements.Elements("Outcome") select Canonicalize(o, baselineStrategy); */ Set<string> outcomes = new Set<string>(); // TODO: make more LINQ-y and concise foreach (XElement methodElement in methodElements) { var outcomeElems = methodElement.Elements("Outcome"); if (methodElement.FirstAttribute != null) { // get method name if the elements are associated with a particular method, else they are associated with the assembly as a whole string methodName = methodElement.FirstAttribute != null ? methodElement.FirstAttribute.Value : "Assembly"; foreach (XElement outcomeElement in outcomeElems) { outcomes.Add(Canonicalize(methodName, outcomeElement, baselineStrategy)); } } } return new BaseLineOutcomes(outcomes, baselineStrategy); } static string Canonicalize(String methodName, XElement outcomeElement, BaseLiningOptions baselineStrategy) { var outcomeKind = (string)outcomeElement.Attribute("Outcome"); if (outcomeKind != null) { ProofOutcome outcome = (ProofOutcome)Enum.Parse(typeof(ProofOutcome), (string)outcomeElement.Attribute("Outcome"), true); WarningKind kind = (WarningKind)Enum.Parse(typeof(WarningKind), (string)outcomeElement.Attribute("Kind"), true); string message = (string)outcomeElement.Attribute("Message"); int primaryILOffset = Int32.Parse((string)outcomeElement.Attribute("PrimaryILOffset"), System.Globalization.NumberStyles.HexNumber); int methodILOffset = Int32.Parse((string)outcomeElement.Attribute("MethodILOffset"), System.Globalization.NumberStyles.HexNumber); return CanonicalFormat(methodName, kind, outcome, message, primaryILOffset, methodILOffset, baselineStrategy); } else { return (string)outcomeElement.Attribute("Message"); } } static string CanonicalFormat(string methodName, WarningKind kind, ProofOutcome outcome, string message, int primaryILOffset, int methodILOffset, BaseLiningOptions baselineStrategy) { switch (baselineStrategy) { case BaseLiningOptions.ilBased: return String.Format("{0}:{1} PrimaryIL={2} MethodIL={3}", methodName, message, primaryILOffset, methodILOffset); case BaseLiningOptions.typeBased: return String.Format("{0}:{1}", methodName, kind.ToString()); case BaseLiningOptions.mixed: default: switch (kind) { case WarningKind.Invariant: case WarningKind.Assert: case WarningKind.Requires: case WarningKind.Ensures: return String.Format("{0} PrimaryIL={1}", message, primaryILOffset); default: return message; } } } public bool CheckOutcome(CompilerError error) { string canonical = error.ErrorText; this.actualOutcomes.Add(canonical); if (!this.expectedOutcomes.Contains(canonical)) { errorCount++; return false; } return true; } public bool CheckOutcome(WarningKind kind, IOutput output, Method method, ProofOutcome outcome, string message, int primaryILOffset, int methodILOffset, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder, CacheManager<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue> cacheManager) { string canonicalMethodName = XmlBaseLine<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>.CanonicalMethodName(method, mdDecoder); string canonical = CanonicalFormat(canonicalMethodName, kind, outcome, message, primaryILOffset, methodILOffset, baselineStrategy); this.actualOutcomes.Add(canonical); // HACK to avoid modifying tons of Clousot code if (cacheManager != null && !checkedHashMatch) { if (this.methodHash != cacheManager.MethodHashAsString()) { // the method names match, but their hashes do not. this means the programmer has changed the method *without* renaming it //TextWriter errorWriter = Console.Error; //errorWriter.WriteLine(string.Format("<Hash/Name Discrepancy>{0}</HashName Discrepancy>", method)); //Console.WriteLine(string.Format("<Hash/Name Discrepancy>{0}</HashName Discrepancy>", method)); } checkedHashMatch = true; } if (!this.expectedOutcomes.Contains(canonical)) { if (kind != WarningKind.Informational) { errorCount++; } return false; } return true; } public bool Passed { get { if (this.errorCount == 0) { #if CheckForExtraneousOutcomes if (this.actualOutcomes.Count < this.expectedOutcomes.Count) { this.errorCount++; } #endif } return this.errorCount == 0; } } public void ReportRegressions(IOutput output) { Set<string> expectedDiff = this.expectedOutcomes.Difference(this.actualOutcomes); Set<string> actualDiff = this.actualOutcomes.Difference(this.expectedOutcomes); output.WriteLine("---Actual outcomes---"); foreach (string actual in actualDiff) { output.WriteLine(actual); } output.WriteLine("---Expected outcomes---"); foreach (string expected in expectedDiff) { output.WriteLine(expected); } output.WriteLine("-----------------------"); } public int Errors { get { return this.errorCount; } } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading; using System.Xml; using log4net; using Nini.Config; using OpenSim.Framework; namespace OpenSim { /// <summary> /// Loads the Configuration files into nIni /// </summary> public class ConfigurationLoader { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Various Config settings the region needs to start /// Physics Engine, Mesh Engine, GridMode, PhysicsPrim allowed, Neighbor, /// StorageDLL, Storage Connection String, Estate connection String, Client Stack /// Standalone settings. /// </summary> protected ConfigSettings m_configSettings; /// <summary> /// A source of Configuration data /// </summary> protected OpenSimConfigSource m_config; /// <summary> /// Grid Service Information. This refers to classes and addresses of the grid service /// </summary> protected NetworkServersInfo m_networkServersInfo; /// <summary> /// Loads the region configuration /// </summary> /// <param name="argvSource">Parameters passed into the process when started</param> /// <param name="configSettings"></param> /// <param name="networkInfo"></param> /// <returns>A configuration that gets passed to modules</returns> public OpenSimConfigSource LoadConfigSettings( IConfigSource argvSource, out ConfigSettings configSettings, out NetworkServersInfo networkInfo) { m_configSettings = configSettings = new ConfigSettings(); m_networkServersInfo = networkInfo = new NetworkServersInfo(); bool iniFileExists = false; IConfig startupConfig = argvSource.Configs["Startup"]; List<string> sources = new List<string>(); string masterFileName = startupConfig.GetString("inimaster", String.Empty); if (IsUri(masterFileName)) { if (!sources.Contains(masterFileName)) sources.Add(masterFileName); } else { string masterFilePath = Path.GetFullPath( Path.Combine(Util.configDir(), masterFileName)); if (masterFileName != String.Empty && File.Exists(masterFilePath) && (!sources.Contains(masterFilePath))) sources.Add(masterFilePath); } string iniFileName = startupConfig.GetString("inifile", "OpenSim.ini"); if (IsUri(iniFileName)) { if (!sources.Contains(iniFileName)) sources.Add(iniFileName); Application.iniFilePath = iniFileName; } else { Application.iniFilePath = Path.GetFullPath( Path.Combine(Util.configDir(), iniFileName)); if (!File.Exists(Application.iniFilePath)) { iniFileName = "OpenSim.xml"; Application.iniFilePath = Path.GetFullPath( Path.Combine(Util.configDir(), iniFileName)); } if (File.Exists(Application.iniFilePath)) { if (!sources.Contains(Application.iniFilePath)) sources.Add(Application.iniFilePath); } } string iniDirName = startupConfig.GetString("inidirectory", "config"); string iniDirPath = Path.Combine(Util.configDir(), iniDirName); if (Directory.Exists(iniDirPath)) { m_log.InfoFormat("Searching folder {0} for config ini files", iniDirPath); string[] fileEntries = Directory.GetFiles(iniDirName); foreach (string filePath in fileEntries) { if (Path.GetExtension(filePath).ToLower() == ".ini") { if (!sources.Contains(Path.GetFullPath(filePath))) sources.Add(Path.GetFullPath(filePath)); } } } m_config = new OpenSimConfigSource(); m_config.Source = new IniConfigSource(); m_config.Source.Merge(DefaultConfig()); m_log.Info("[CONFIG]: Reading configuration settings"); if (sources.Count == 0) { m_log.FatalFormat("[CONFIG]: Could not load any configuration"); m_log.FatalFormat("[CONFIG]: Did you copy the OpenSim.ini.example file to OpenSim.ini?"); Environment.Exit(1); } for (int i = 0 ; i < sources.Count ; i++) { if (ReadConfig(sources[i])) iniFileExists = true; AddIncludes(sources); } if (!iniFileExists) { m_log.FatalFormat("[CONFIG]: Could not load any configuration"); m_log.FatalFormat("[CONFIG]: Configuration exists, but there was an error loading it!"); Environment.Exit(1); } // Make sure command line options take precedence m_config.Source.Merge(argvSource); ReadConfigSettings(); return m_config; } /// <summary> /// Adds the included files as ini configuration files /// </summary> /// <param name="sources">List of URL strings or filename strings</param> private void AddIncludes(List<string> sources) { //loop over config sources foreach (IConfig config in m_config.Source.Configs) { // Look for Include-* in the key name string[] keys = config.GetKeys(); foreach (string k in keys) { if (k.StartsWith("Include-")) { // read the config file to be included. string file = config.GetString(k); if (IsUri(file)) { if (!sources.Contains(file)) sources.Add(file); } else { string basepath = Path.GetFullPath(Util.configDir()); string path = Path.Combine(basepath, file); string[] paths = Util.Glob(path); foreach (string p in paths) { if (!sources.Contains(p)) sources.Add(p); } } } } } } /// <summary> /// Check if we can convert the string to a URI /// </summary> /// <param name="file">String uri to the remote resource</param> /// <returns>true if we can convert the string to a Uri object</returns> bool IsUri(string file) { Uri configUri; return Uri.TryCreate(file, UriKind.Absolute, out configUri) && configUri.Scheme == Uri.UriSchemeHttp; } /// <summary> /// Provide same ini loader functionality for standard ini and master ini - file system or XML over http /// </summary> /// <param name="iniPath">Full path to the ini</param> /// <returns></returns> private bool ReadConfig(string iniPath) { bool success = false; if (!IsUri(iniPath)) { m_log.InfoFormat("[CONFIG]: Reading configuration file {0}", Path.GetFullPath(iniPath)); m_config.Source.Merge(new IniConfigSource(iniPath)); success = true; } else { m_log.InfoFormat("[CONFIG]: {0} is a http:// URI, fetching ...", iniPath); // The ini file path is a http URI // Try to read it try { XmlReader r = XmlReader.Create(iniPath); XmlConfigSource cs = new XmlConfigSource(r); m_config.Source.Merge(cs); success = true; } catch (Exception e) { m_log.FatalFormat("[CONFIG]: Exception reading config from URI {0}\n" + e.ToString(), iniPath); Environment.Exit(1); } } return success; } /// <summary> /// Setup a default config values in case they aren't present in the ini file /// </summary> /// <returns>A Configuration source containing the default configuration</returns> private static IConfigSource DefaultConfig() { IConfigSource defaultConfig = new IniConfigSource(); { IConfig config = defaultConfig.Configs["Startup"]; if (null == config) config = defaultConfig.AddConfig("Startup"); config.Set("region_info_source", "filesystem"); config.Set("physics", "OpenDynamicsEngine"); config.Set("meshing", "Meshmerizer"); config.Set("physical_prim", true); config.Set("see_into_this_sim_from_neighbor", true); config.Set("serverside_object_permissions", false); config.Set("storage_plugin", "OpenSim.Data.SQLite.dll"); config.Set("storage_connection_string", "URI=file:OpenSim.db,version=3"); config.Set("storage_prim_inventories", true); config.Set("startup_console_commands_file", String.Empty); config.Set("shutdown_console_commands_file", String.Empty); config.Set("DefaultScriptEngine", "XEngine"); config.Set("clientstack_plugin", "OpenSim.Region.ClientStack.LindenUDP.dll"); // life doesn't really work without this config.Set("EventQueue", true); } { IConfig config = defaultConfig.Configs["StandAlone"]; if (null == config) config = defaultConfig.AddConfig("StandAlone"); config.Set("accounts_authenticate", true); config.Set("welcome_message", "Welcome to OpenSimulator"); config.Set("inventory_plugin", "OpenSim.Data.SQLite.dll"); config.Set("inventory_source", ""); config.Set("userDatabase_plugin", "OpenSim.Data.SQLite.dll"); config.Set("user_source", ""); config.Set("LibrariesXMLFile", string.Format(".{0}inventory{0}Libraries.xml", Path.DirectorySeparatorChar)); } { IConfig config = defaultConfig.Configs["Network"]; if (null == config) config = defaultConfig.AddConfig("Network"); config.Set("http_listener_port", ConfigSettings.DefaultRegionHttpPort); } return defaultConfig; } /// <summary> /// Read initial region settings from the ConfigSource /// </summary> protected virtual void ReadConfigSettings() { IConfig startupConfig = m_config.Source.Configs["Startup"]; if (startupConfig != null) { m_configSettings.PhysicsEngine = startupConfig.GetString("physics"); m_configSettings.MeshEngineName = startupConfig.GetString("meshing"); m_configSettings.PhysicalPrim = startupConfig.GetBoolean("physical_prim", true); m_configSettings.See_into_region_from_neighbor = startupConfig.GetBoolean("see_into_this_sim_from_neighbor", true); m_configSettings.StorageDll = startupConfig.GetString("storage_plugin"); m_configSettings.StorageConnectionString = startupConfig.GetString("storage_connection_string"); m_configSettings.EstateConnectionString = startupConfig.GetString("estate_connection_string", m_configSettings.StorageConnectionString); m_configSettings.ClientstackDll = startupConfig.GetString("clientstack_plugin", "OpenSim.Region.ClientStack.LindenUDP.dll"); } IConfig standaloneConfig = m_config.Source.Configs["StandAlone"]; if (standaloneConfig != null) { m_configSettings.StandaloneAuthenticate = standaloneConfig.GetBoolean("accounts_authenticate", true); m_configSettings.StandaloneWelcomeMessage = standaloneConfig.GetString("welcome_message"); m_configSettings.StandaloneInventoryPlugin = standaloneConfig.GetString("inventory_plugin"); m_configSettings.StandaloneInventorySource = standaloneConfig.GetString("inventory_source"); m_configSettings.StandaloneUserPlugin = standaloneConfig.GetString("userDatabase_plugin"); m_configSettings.StandaloneUserSource = standaloneConfig.GetString("user_source"); m_configSettings.LibrariesXMLFile = standaloneConfig.GetString("LibrariesXMLFile"); } m_networkServersInfo.loadFromConfiguration(m_config.Source); } } }
// // Mono.WebServer.MonoWorkerRequest // // Authors: // Daniel Lopez Ridruejo // Gonzalo Paniagua Javier // // Documentation: // Brian Nickel // // Copyright (c) 2002 Daniel Lopez Ridruejo. // (c) 2002,2003 Ximian, Inc. // All rights reserved. // (C) Copyright 2004-2010 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Specialized; using System.Configuration; using System.IO; // using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Web; using System.Web.Hosting; using Mono.WebServer.Log; namespace Mono.WebServer { public abstract class MonoWorkerRequest : SimpleWorkerRequest { const string DEFAULT_EXCEPTION_HTML = "<html><head><title>Runtime Error</title></head><body>An exception ocurred:<pre>{0}</pre></body></html>"; static readonly char[] mapPathTrimStartChars = { '/' }; static bool checkFileAccess = true; readonly static bool needToReplacePathSeparator; readonly static char pathSeparatorChar; readonly IApplicationHost appHostBase; Encoding encoding; Encoding headerEncoding; byte [] queryStringBytes; string hostVPath; string hostPath; string hostPhysicalRoot; EndOfSendNotification end_send; object end_send_data; X509Certificate client_cert; NameValueCollection server_variables; bool inUnhandledException; // as we must have the client certificate (if provided) then we're able to avoid // pre-calculating some items (and cache them if we have to calculate) string cert_cookie; string cert_issuer; string cert_serial; string cert_subject; protected byte[] server_raw; protected byte[] client_raw; public event MapPathEventHandler MapPathEvent; public event EndOfRequestHandler EndOfRequestEvent; public abstract int RequestId { get; } protected static bool RunningOnWindows { get; private set; } public static bool CheckFileAccess { get { return checkFileAccess; } set { checkFileAccess = value; } } // Gets the physical path of the application host of the // current instance. string HostPath { get { if (hostPath == null) hostPath = appHostBase.Path; return hostPath; } } // Gets the virtual path of the application host of the // current instance. string HostVPath { get { if (hostVPath == null) hostVPath = appHostBase.VPath; return hostVPath; } } string HostPhysicalRoot { get { if (hostPhysicalRoot == null) hostPhysicalRoot = appHostBase.Server.PhysicalRoot; return hostPhysicalRoot; } } protected virtual Encoding Encoding { get { if (encoding == null) encoding = Encoding.GetEncoding (28591); return encoding; } set { encoding = value; } } protected virtual Encoding HeaderEncoding { get { if (headerEncoding == null) { HttpContext ctx = HttpContext.Current; HttpResponse response = ctx != null ? ctx.Response : null; Encoding enc = inUnhandledException ? null : response != null ? response.HeaderEncoding : null; headerEncoding = enc ?? Encoding; } return headerEncoding; } } static MonoWorkerRequest () { PlatformID pid = Environment.OSVersion.Platform; RunningOnWindows = ((int) pid != 128 && pid != PlatformID.Unix && pid != PlatformID.MacOSX); if (Path.DirectorySeparatorChar != '/') { needToReplacePathSeparator = true; pathSeparatorChar = Path.DirectorySeparatorChar; } try { string v = ConfigurationManager.AppSettings ["MonoServerCheckHiddenFiles"]; if (!String.IsNullOrEmpty (v)) { if (!Boolean.TryParse (v, out checkFileAccess)) checkFileAccess = true; } } catch (Exception) { // ignore checkFileAccess = true; } } protected MonoWorkerRequest (IApplicationHost appHost) : base (String.Empty, String.Empty, null) { if (appHost == null) throw new ArgumentNullException ("appHost"); appHostBase = appHost; } public override string GetAppPath () { return HostVPath; } public override string GetAppPathTranslated () { return HostPath; } public override string GetFilePathTranslated () { return MapPath (GetFilePath ()); } public override string GetLocalAddress () { return "localhost"; } public override string GetServerName () { string hostHeader = GetKnownRequestHeader(HeaderHost); if (String.IsNullOrEmpty (hostHeader)) { hostHeader = GetLocalAddress (); } else { int colonIndex = hostHeader.IndexOf (':'); if (colonIndex > 0) { hostHeader = hostHeader.Substring (0, colonIndex); } else if (colonIndex == 0) { hostHeader = GetLocalAddress (); } } return hostHeader; } public override int GetLocalPort () { return 0; } public override byte [] GetPreloadedEntityBody () { return null; } public override byte [] GetQueryStringRawBytes () { if (queryStringBytes == null) { string queryString = GetQueryString (); if (queryString != null) queryStringBytes = Encoding.GetBytes (queryString); } return queryStringBytes; } // Invokes the registered delegates one by one until the path is mapped. // // Parameters: // path = virutal path of the request. // // Returns a string containing the mapped physical path of the request, or null if // the path was not successfully mapped. // string DoMapPathEvent (string path) { if (MapPathEvent != null) { var args = new MapPathEventArgs (path); foreach (MapPathEventHandler evt in MapPathEvent.GetInvocationList ()) { evt (this, args); if (args.IsMapped) return args.MappedPath; } } return null; } // The logic here is as follows: // // If path is equal to the host's virtual path (including trailing slash), // return the host virtual path. // // If path is absolute (starts with '/') then check if it's under our host vpath. If // it is, base the mapping under the virtual application's physical path. If it // isn't use the physical root of the application server to return the mapped // path. If you have just one application configured, then the values computed in // both of the above cases will be the same. If you have several applications // configured for this xsp/mod-mono-server instance, then virtual paths outside our // application virtual path will return physical paths relative to the server's // physical root, not application's. This is consistent with the way IIS worker // request works. See bug #575600 // public override string MapPath (string path) { string eventResult = DoMapPathEvent (path); if (eventResult != null) return eventResult; string hostVPath = HostVPath; int hostVPathLen = HostVPath.Length; int pathLen = path != null ? path.Length : 0; #if NET_2_0 bool inThisApp = path.StartsWith (hostVPath, StringComparison.Ordinal); #else bool inThisApp = path.StartsWith (hostVPath); #endif if (pathLen == 0 || (inThisApp && (pathLen == hostVPathLen || (pathLen == hostVPathLen + 1 && path [pathLen - 1] == '/')))) { if (needToReplacePathSeparator) return HostPath.Replace ('/', pathSeparatorChar); return HostPath; } string basePath = null; switch (path [0]) { case '~': if (path.Length >= 2 && path [1] == '/') path = path.Substring (1); break; case '/': if (!inThisApp) basePath = HostPhysicalRoot; break; } if (basePath == null) basePath = HostPath; if (inThisApp && (path.Length == hostVPathLen || path [hostVPathLen] == '/')) path = path.Substring (hostVPathLen + 1); path = path.TrimStart (mapPathTrimStartChars); if (needToReplacePathSeparator) path = path.Replace ('/', pathSeparatorChar); return Path.Combine (basePath, path); } protected abstract bool GetRequestData (); public bool ReadRequestData () { return GetRequestData (); } static void LocationAccessible (string localPath) { bool doThrow = false; if (RunningOnWindows) { try { var fi = new FileInfo (localPath); FileAttributes attr = fi.Attributes; if ((attr & FileAttributes.Hidden) != 0 || (attr & FileAttributes.System) != 0) doThrow = true; } catch (Exception) { // ignore, will be handled in system.web return; } } else { // throw only if the file exists, let system.web handle the request // otherwise if (File.Exists (localPath) || Directory.Exists (localPath)) if (Path.GetFileName (localPath) [0] == '.') doThrow = true; } if (doThrow) throw new HttpException (403, "Forbidden."); } void AssertFileAccessible () { if (!checkFileAccess) return; string localPath = GetFilePathTranslated (); if (String.IsNullOrEmpty (localPath)) return; char dirsep = Path.DirectorySeparatorChar; string appPath = GetAppPathTranslated (); string[] segments = localPath.Substring (appPath.Length).Split (dirsep); var sb = new StringBuilder (appPath); foreach (string s in segments) { if (s.Length == 0) continue; if (s [0] != '.') { sb.Append (s); sb.Append (dirsep); continue; } sb.Append (s); LocationAccessible (sb.ToString ()); } } public void ProcessRequest () { string error = null; inUnhandledException = false; try { AssertFileAccessible (); HttpRuntime.ProcessRequest (this); } catch (HttpException ex) { inUnhandledException = true; error = ex.GetHtmlErrorMessage (); } catch (Exception ex) { inUnhandledException = true; var hex = new HttpException (400, "Bad request", ex); error = hex.GetHtmlErrorMessage (); } if (!inUnhandledException) return; if (error.Length == 0) error = String.Format (DEFAULT_EXCEPTION_HTML, "Unknown error"); try { SendStatus (400, "Bad request"); SendUnknownResponseHeader ("Connection", "close"); SendUnknownResponseHeader ("Date", DateTime.Now.ToUniversalTime ().ToString ("r")); Encoding enc = Encoding.UTF8; byte[] bytes = enc.GetBytes (error); SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName); SendUnknownResponseHeader ("Content-Length", bytes.Length.ToString ()); SendResponseFromMemory (bytes, bytes.Length); FlushResponse (true); } catch (Exception ex) { // should "never" happen Logger.Write (LogLevel.Error, "Error while processing a request: "); Logger.Write (ex); throw; } } public override void EndOfRequest () { if (EndOfRequestEvent != null) EndOfRequestEvent (this); if (end_send != null) end_send (this, end_send_data); } public override void SetEndOfSendNotification (EndOfSendNotification callback, object extraData) { end_send = callback; end_send_data = extraData; } public override void SendCalculatedContentLength (int contentLength) { //FIXME: Should we ignore this for apache2? SendUnknownResponseHeader ("Content-Length", contentLength.ToString ()); } public override void SendKnownResponseHeader (int index, string value) { if (HeadersSent ()) return; string headerName = GetKnownResponseHeaderName (index); SendUnknownResponseHeader (headerName, value); } protected void SendFromStream (Stream stream, long offset, long length) { if (offset < 0 || length <= 0) return; long stLength = stream.Length; if (offset + length > stLength) length = stLength - offset; if (offset > 0) stream.Seek (offset, SeekOrigin.Begin); var fileContent = new byte [8192]; int count = fileContent.Length; while (length > 0 && (count = stream.Read (fileContent, 0, count)) != 0) { SendResponseFromMemory (fileContent, count); length -= count; // Keep the System. prefix count = (int) System.Math.Min (length, fileContent.Length); } } public override void SendResponseFromFile (string filename, long offset, long length) { FileStream file = null; try { file = File.OpenRead (filename); SendFromStream (file, offset, length); } finally { if (file != null) file.Close (); } } public override void SendResponseFromFile (IntPtr handle, long offset, long length) { Stream file = null; try { file = new FileStream (handle, FileAccess.Read); SendFromStream (file, offset, length); } finally { if (file != null) file.Close (); } } public override string GetServerVariable (string name) { if (server_variables == null) return String.Empty; if (IsSecure ()) { X509Certificate client = ClientCertificate; switch (name) { case "CERT_COOKIE": if (cert_cookie == null) { if (client == null) cert_cookie = String.Empty; else cert_cookie = client.GetCertHashString (); } return cert_cookie; case "CERT_ISSUER": if (cert_issuer == null) { if (client == null) cert_issuer = String.Empty; else cert_issuer = client.Issuer; } return cert_issuer; case "CERT_SERIALNUMBER": if (cert_serial == null) { if (client == null) cert_serial = String.Empty; else cert_serial = client.GetSerialNumberString (); } return cert_serial; case "CERT_SUBJECT": if (cert_subject == null) { if (client == null) cert_subject = String.Empty; else cert_subject = client.Subject; } return cert_subject; } } string s = server_variables [name]; return s ?? String.Empty; } public void AddServerVariable (string name, string value) { if (server_variables == null) server_variables = new NameValueCollection (); server_variables.Add (name, value); } #region Client Certificate Support public X509Certificate ClientCertificate { get { if ((client_cert == null) && (client_raw != null)) client_cert = new X509Certificate (client_raw); return client_cert; } } public void SetClientCertificate (byte[] rawcert) { client_raw = rawcert; } public override byte[] GetClientCertificate () { return client_raw; } public override byte[] GetClientCertificateBinaryIssuer () { if (ClientCertificate == null) return base.GetClientCertificateBinaryIssuer (); // TODO: not 100% sure of the content return new byte [0]; } public override int GetClientCertificateEncoding () { if (ClientCertificate == null) return base.GetClientCertificateEncoding (); return 0; } public override byte[] GetClientCertificatePublicKey () { if (ClientCertificate == null) return base.GetClientCertificatePublicKey (); return ClientCertificate.GetPublicKey (); } public override DateTime GetClientCertificateValidFrom () { if (ClientCertificate == null) return base.GetClientCertificateValidFrom (); return DateTime.Parse (ClientCertificate.GetEffectiveDateString ()); } public override DateTime GetClientCertificateValidUntil () { if (ClientCertificate == null) return base.GetClientCertificateValidUntil (); return DateTime.Parse (ClientCertificate.GetExpirationDateString ()); } #endregion protected static string[] SplitAndTrim (string list) { if (String.IsNullOrEmpty (list)) return new string[0]; System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>(); string[] astr = list.Split(','); for(int i=0; i < astr.Length; ++i ) { string str = astr[i].Trim(); if(str.Length != 0) ls.Add(str); } return ls.ToArray(); /* return (from f in list.Split (',') let trimmed = f.Trim () where trimmed.Length != 0 select trimmed).ToArray (); */ } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace ODataValidator.RuleEngine { #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Net; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using ODataValidator.RuleEngine.Common; #endregion /// <summary> /// Class encapsulating OData interop request context /// </summary> public class ServiceContext : ServiceContextCore { private List<KeyValuePair<string, string>> reqHeaders; /// <summary> /// The response header of interop service context. /// </summary> private string respHeaders; /// <summary> /// The payload literal body of interop service context. /// </summary> private string payload; /// <summary> /// Metadata document. /// </summary> private string metadataDocument; /// <summary> /// Service document. /// </summary> private string serviceDocument; /// <summary> /// Fully-qualified name of entity type if applicable. /// </summary> private string entityTypeFullName; /// <summary> /// The complete metadata document that is merged with the including metadata document. /// </summary> string mergedMetadataDocument = null; /// <summary> /// The Metadata Service Schema Document. /// </summary> string metadataServiceSchemaDoc = null; /// <summary> /// Whether the metadata document includes external metadata document. /// </summary> bool? containsExternalSchema; /// <summary> /// Creates an instance of ServiceContext. /// </summary> /// <param name="destination">request Uri of the service context</param> /// <param name="jobId">Job identifier</param> /// <param name="statusCode">Http status code of the response</param> /// <param name="responseHttpHeaders">Header text of the response</param> /// <param name="responsePayload">Payload content of the response</param> /// <param name="entityType">Fully-qualified name of entity type the repsonse payload is about</param> /// <param name="serviceBaseUri">Uri of service document</param> /// <param name="serviceDocument">Content of service document</param> /// <param name="metadataDocument">Content of metadata document</param> /// <param name="offline">Flag of conetxt being offline(true) or live(false)</param> /// <param name="reqHeaders">Http headers used as part of header</param> /// <param name="odataMetadata">Odata metadata type</param> public ServiceContext( Uri destination, Guid jobId, HttpStatusCode? statusCode, string responseHttpHeaders, string responsePayload, string entityType, Uri serviceBaseUri, string serviceDocument, string metadataDocument, bool offline, IEnumerable<KeyValuePair<string, string>> reqHeaders, ODataMetadataType odataMetadata = ODataMetadataType.MinOnly, string jsonFullmetadataPayload = null, string category = "core") { if (destination == null) { throw new ArgumentNullException("destination"); } // TODO: uncomment this to enable uri canonicalization // this.Destination = destination.Canonicalize(); this.Destination = destination; this.DestinationBasePath = this.Destination.GetLeftPart(UriPartial.Path).TrimEnd('/'); AnnotationDVsManager.Instance(this.DestinationBasePath); if (!string.IsNullOrEmpty(this.DestinationBasePath)) { string lastLeg = this.DestinationBasePath.Substring(this.DestinationBasePath.LastIndexOf('/')); if (!string.IsNullOrEmpty(lastLeg)) { this.DestinationBaseLastSegment = lastLeg.TrimStart('/'); } } this.Projection = this.Destination.Query.IndexOf("$select=", StringComparison.OrdinalIgnoreCase) >= 0; this.JobId = jobId; this.HttpStatusCode = statusCode; this.ResponseHttpHeaders = responseHttpHeaders; this.OdataMetadataType = odataMetadata; this.JsonFullMetadataPayload = jsonFullmetadataPayload; this.MetadataDocument = metadataDocument; this.ResponsePayload = responsePayload; this.EntityTypeFullName = entityType; this.ServiceBaseUri = serviceBaseUri; this.ServiceDocument = serviceDocument; this.IsOffline = offline; this.RequestHeaders = reqHeaders; this.Category = category; this.ServiceType = ConformanceServiceType.ReadWrite; this.LevelTypes = new ConformanceLevelType[] { ConformanceLevelType.Minimal }; if (category.Contains(";")) { string[] array = category.Split(';'); this.Category = array[0]; this.ServiceType = (ConformanceServiceType)Enum.Parse(typeof(ConformanceServiceType), array[1]); if (array.Length > 2 && array[2].Contains(",")) { string[] levelArray = array[2].Split(','); this.LevelTypes = new ConformanceLevelType[levelArray.Length]; for (int i = 0; i < levelArray.Length; i++) { ConformanceLevelType level; if (Enum.TryParse(levelArray[i], out level)) { this.LevelTypes[i] = level; } } } } } /// <summary> /// Gets Http header key/value pairs to be sent to server /// </summary> public IEnumerable<KeyValuePair<string, string>> RequestHeaders { get { return this.reqHeaders; } private set { if (value != null && value.Any()) { this.reqHeaders = new List<KeyValuePair<string, string>>(); foreach (var p in value) { if (!string.IsNullOrEmpty(p.Key)) { this.reqHeaders.Add(p); if (p.Key.ToLower().Contains("version")) { switch (p.Value) { case "3.0": this.Version = ODataVersion.V3; break; case "4.0": this.Version = ODataVersion.V4; break; default: this.Version = ODataVersion.V1_V2; break; } } } } } } } /// <summary> /// Gets Validation Job Id /// </summary> public Guid JobId { get; private set; } /// <summary> /// Gets the canonicalized uri pointing to the OData service endpoint to be validated /// </summary> public Uri Destination { get; private set; } /// <summary> /// Gets string of uri pointing to the OData service endpoint excluding the query options /// </summary> public string DestinationBasePath { get; private set; } /// <summary> /// Gets the last segment of uri pointing to the OData service endpoint excluding the query options /// </summary> public string DestinationBaseLastSegment { get; private set; } /// <summary> /// Gets/sets http status code for the payload response when http/https protocol is used /// </summary> public HttpStatusCode? HttpStatusCode { get; private set; } /// <summary> /// Gets payload format indicated by http response header of Content-Type /// </summary> public PayloadFormat ContentType { get; private set; } /// <summary> /// Gets the underlying entity type short name this payload is about (applicable to feed or entry only) /// </summary> public string EntityTypeShortName { get; private set; } /// <summary> /// Get the full metadata json format payload /// </summary> public string JsonFullMetadataPayload { get; private set; } /// <summary> /// Gets the underlying entity type full name this payload is about (applicable to feed or entry only) /// </summary> public string EntityTypeFullName { get { return this.entityTypeFullName; } private set { this.entityTypeFullName = value; this.EntityTypeShortName = this.entityTypeFullName.GetLastSegment(); } } /// <summary> /// Gets response headers /// </summary> public string ResponseHttpHeaders { get { return this.respHeaders; } private set { this.respHeaders = value; //this.Version = this.respHeaders.GetODataVersion(); // We should set version by UI selected this.ContentType = this.respHeaders.GetContentType(); } } /// <summary> /// Gets response payload /// </summary> public string ResponsePayload { get { return this.payload; } private set { this.PayloadFormat = value.GetFormatFromPayload(); this.payload = value.FineFormat(this.PayloadFormat); this.PayloadType = ContextHelper.GetPayloadType(this.payload, this.PayloadFormat, this.respHeaders, this.MetadataDocument); if (this.OdataMetadataType == ODataMetadataType.MinOnly) { this.EntityTypeFullName = this.JsonFullMetadataPayload.GetFullEntityTypeFromPayload(this.PayloadType, this.PayloadFormat); } else { this.EntityTypeFullName = this.payload.GetFullEntityTypeFromPayload(this.PayloadType, this.PayloadFormat); } if (!string.IsNullOrEmpty(this.EntityTypeFullName)) { var segs = this.EntityTypeFullName.Split('.'); this.EntityTypeShortName = segs[segs.Length - 1]; } this.IsMediaLinkEntry = this.payload.IsMediaLinkEntry(this.PayloadType, this.PayloadFormat); TermDocuments termDocs = TermDocuments.GetInstance(); this.VocCapabilities = termDocs.VocCapabilitiesDoc; this.VocCore = termDocs.VocCoreDoc; this.VocMeasures = termDocs.VocMeasuresDoc; } } /// <summary> /// Gets uri pointing to the service base of the OData service this context refers to /// </summary> public Uri ServiceBaseUri { get; private set; } /// <summary> /// Gets content of service document of the OData service this context refers to /// </summary> public string ServiceDocument { get { return this.serviceDocument; } private set { this.serviceDocument = value; this.HasServiceDocument = !string.IsNullOrEmpty(this.ServiceDocument); } } /// <summary> /// Gets content of metadata document of the OData service the uri refers to /// </summary> public string MetadataDocument { get { return this.metadataDocument; } private set { this.metadataDocument = value; this.HasMetadata = !string.IsNullOrEmpty(this.MetadataDocument) && this.MetadataDocument.IsMetadata(); } } /// <summary> /// The complete metadata document that is merged with the including metadata document. /// </summary> public string MergedMetadataDocument { get { if (!String.IsNullOrEmpty(mergedMetadataDocument)) { return this.mergedMetadataDocument; } else { try { this.mergedMetadataDocument = this.getAndMergeExternalSchema(); } catch (Exception) { this.mergedMetadataDocument = this.metadataDocument; } return this.mergedMetadataDocument; } } } /// <summary> /// Gets whether metadata service document schema has been found for the OData service this context refers to /// </summary> public bool HasMetadataServiceSchema { get; protected set; } /// <summary> /// The metadata service schema document. /// /// </summary> public string MetadataServiceSchemaDoc { get { if (!String.IsNullOrEmpty(metadataServiceSchemaDoc)) { return this.metadataServiceSchemaDoc; } else { try { this.metadataServiceSchemaDoc = this.GetMetadataServiceSchemaDoc(); this.HasMetadataServiceSchema = !string.IsNullOrEmpty(this.metadataServiceSchemaDoc) && this.metadataServiceSchemaDoc.IsMetadata(); } catch (Exception) { this.metadataServiceSchemaDoc = this.metadataDocument; } return this.metadataServiceSchemaDoc; } } } /// <summary> /// Whether the metadata document includes external metadata document. /// </summary> public bool ContainsExternalSchema { get { if (containsExternalSchema != null) { return containsExternalSchema.Value; } else { XElement md = XElement.Parse(this.metadataDocument); XElement entity = md.XPathSelectElement("./*[local-name()='Reference']/*[local-name()='Include']"); this.containsExternalSchema = entity != null; return containsExternalSchema.Value; } } } public string VocCapabilities { get; private set; } public string VocCore { get; private set; } public string VocMeasures { get; private set; } /// <summary> /// Cache the Service verification result for some functions /// </summary> public ServiceVerification ServiceVerResult = new ServiceVerification(); /// <summary> /// Gets response payload line-by-line /// </summary> /// <returns>lines of payload content</returns> [SuppressMessage("Microsoft.Design", "CA1024: convert method to property if appropriate", Justification = "defined as api expected by online service")] public IEnumerable<string> GetPayloadLines() { if (string.IsNullOrEmpty(this.payload)) { yield break; } if (ContextHelper.IsValidPayload(this.PayloadType)) { StringReader sr = new StringReader(this.payload); string line; while ((line = sr.ReadLine()) != null) { yield return line; } } else { yield break; } } public bool IsRequestVersion() { var respVersion = this.respHeaders.GetODataVersion(); return respVersion == this.Version; } /// <summary> /// Merge the include metadata with current. /// </summary> /// <returns></returns> private string getAndMergeExternalSchema() { XmlDocument xmlDoc=new XmlDocument(); xmlDoc.LoadXml(this.MetadataDocument); XmlNode dataServices = xmlDoc.SelectSingleNode("/*[local-name()='Edmx']/*[local-name()='DataServices']"); string xpath = "/*[local-name()='Edmx']/*[local-name()='Reference']"; XmlNodeList referenceNodeList = xmlDoc.SelectNodes(xpath); foreach (XmlNode reference in referenceNodeList) { if (reference.Attributes["Uri"] != null) { try { Uri referenceUri = new Uri(reference.Attributes["Uri"].Value, UriKind.RelativeOrAbsolute); var payload = XElement.Parse(this.MetadataDocument); string baseUriString = payload.GetAttributeValue("xml:base", ODataNamespaceManager.Instance); if (!string.IsNullOrEmpty(baseUriString) && Uri.IsWellFormedUriString(reference.Attributes["Uri"].Value, UriKind.Relative)) { Uri referenceUriRelative = new Uri(reference.Attributes["Uri"].Value, UriKind.Relative); Uri baseUri = new Uri(baseUriString, UriKind.Absolute); referenceUri = new Uri(baseUri, referenceUriRelative); } Response response = WebHelper.Get(referenceUri, string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, this.RequestHeaders); if (response != null && response.StatusCode.Value == System.Net.HttpStatusCode.OK && !string.IsNullOrEmpty(response.ResponsePayload)) { XmlDocument referenceDoc = new XmlDocument(); referenceDoc.LoadXml(response.ResponsePayload); XmlNodeList referencedSchemas = referenceDoc.SelectNodes("/*[local-name()='Edmx']/*[local-name()='DataServices']/*[local-name()='Schema']"); merge(dataServices, referencedSchemas, reference); } } // if one reference doc failed, we should continue merging others. catch (ArgumentException) { continue; } catch (UriFormatException) { continue; } catch (XmlException) { continue; } catch (OversizedPayloadException) { continue; } } } return xmlDoc.OuterXml; } private void merge(XmlNode dataServices, XmlNodeList referencedSchemas, XmlNode reference) { foreach (XmlNode include in reference.SelectNodes("./*[local-name()='Include' and @Namespace]")) { foreach (XmlNode node in referencedSchemas) { if (node.Attributes["Namespace"] != null && include.Attributes["Namespace"].Value.Equals(node.Attributes["Namespace"].Value)) { XmlNode toAdd = dataServices.OwnerDocument.CreateNode(XmlNodeType.Element, node.Name, node.NamespaceURI); toAdd.InnerXml = node.InnerXml; XmlAttribute ns = dataServices.OwnerDocument.CreateAttribute("Namespace"); ns.Value = node.Attributes["Namespace"].Value; toAdd.Attributes.Append(ns); if (include.Attributes["Alias"] != null) { XmlAttribute alias = dataServices.OwnerDocument.CreateAttribute("Alias"); alias.Value = include.Attributes["Alias"].Value; toAdd.Attributes.Append(alias); } dataServices.AppendChild(toAdd); break; } } } }//merge /// <summary> /// Get the metadata service schema from the internet. /// </summary> /// <returns>The string of the metadata service schema document.</returns> private string GetMetadataServiceSchemaDoc() { //Due to the OData example services on OData.org haven't implement the metadata service schema, pause the testing about it now. //Uri metadataMetadataUri = new Uri("/$metadata/$metadata", UriKind.Relative); //Uri metadataServiceUri = new Uri(this.ServiceBaseUri, metadataMetadataUri); //Uri metadataServiceUri = new Uri("http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/models/MetadataService.edmx", UriKind.Absolute); //Response response = WebHelper.Get(metadataServiceUri, string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, RequestHeaders); //if (response != null && response.StatusCode == System.Net.HttpStatusCode.OK && !string.IsNullOrEmpty(response.ResponsePayload)) //{ // return response.ResponsePayload; //} //else //{ return null; //} } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Text; using System.Windows.Forms; using NQuery.Runtime; using Binding=NQuery.Runtime.Binding; namespace NQuery.UI { public partial class EvaluatableBrowser : UserControl { private Evaluatable _evaluatable; private DataContext _dataContext; private const int FOLDER_IMG_IDX = 0; private const int TABLE_IMG_IDX = 1; private const int COLUMN_IMG_IDX = 2; private const int AGGREGATE_IMG_IDX = 3; private const int FUNCTION_IMG_IDX = 4; private const int PARAMETER_IMG_IDX = 5; private const int RELATION_IMG_IDX = 6; public EvaluatableBrowser() { InitializeComponent(); treeView.Click += treeView_Click; treeView.DoubleClick += treeView_DoubleClick; } private void treeView_Click(object sender, EventArgs e) { OnClick(e); } private void treeView_DoubleClick(object sender, EventArgs e) { OnDoubleClick(e); } [DefaultValue(BorderStyle.Fixed3D)] public new BorderStyle BorderStyle { get { return treeView.BorderStyle; } set { treeView.BorderStyle = value; } } public Evaluatable Evaluatable { get { return _evaluatable; } set { if (_evaluatable != null) DisconnectEvaluatable(); _evaluatable = value; if (_evaluatable != null) ConnectEvaluatable(); Reload(); } } public object SelectedItem { get { if (treeView.SelectedNode == null) return null; return treeView.SelectedNode.Tag; } } public event EventHandler<EventArgs> SelectedItemChanged; private void ConnectEvaluatable() { _evaluatable.DataContextChanged += Evaluatable_DataContextChanged; _evaluatable.Parameters.Changed += Parameters_Changed; _dataContext = _evaluatable.DataContext; if (_dataContext != null) ConnectDataContext(); } private void DisconnectEvaluatable() { if (_dataContext != null) DisconnectDataContext(); _evaluatable.Parameters.Changed -= Parameters_Changed; _evaluatable.DataContextChanged -= Evaluatable_DataContextChanged; _evaluatable = null; } private void ConnectDataContext() { _dataContext.Changed += DataContext_Changed; } private void DisconnectDataContext() { _dataContext.Changed -= DataContext_Changed; _dataContext = null; } private void Evaluatable_DataContextChanged(object sender, EventArgs e) { if (_dataContext != null) DisconnectDataContext(); _dataContext = _evaluatable.DataContext; if (_dataContext != null) ConnectDataContext(); } private void DataContext_Changed(object sender, EventArgs e) { Reload(); } private void Parameters_Changed(object sender, EventArgs e) { Reload(); } private static TreeNode Add(TreeNodeCollection target, string text, object tag, int imageIndex) { TreeNode node = new TreeNode(); node.Text = text; node.Tag = tag; node.ImageIndex = node.SelectedImageIndex = imageIndex; target.Add(node); return node; } private void Reload() { Dictionary<string, object> expandedNodePaths = new Dictionary<string, object>(); treeView.BeginUpdate(); try { Point scrollPos = NativeMethods.GetScrollPos(treeView); SaveExpandedNodes(expandedNodePaths, treeView.Nodes); treeView.Nodes.Clear(); TreeNode folderNode; if (_evaluatable != null) { folderNode = Add(treeView.Nodes, "Parameters", null, FOLDER_IMG_IDX); foreach (ParameterBinding parameterBinding in Sorted(_evaluatable.Parameters)) Add(folderNode.Nodes, parameterBinding.Name, parameterBinding, PARAMETER_IMG_IDX); } if (_dataContext != null) { folderNode = Add(treeView.Nodes, "Tables", null, FOLDER_IMG_IDX); foreach (TableBinding tableBinding in Sorted(_dataContext.Tables)) { TreeNode tableNode = Add(folderNode.Nodes, tableBinding.Name, tableBinding, TABLE_IMG_IDX); TreeNode columnsNode = Add(tableNode.Nodes, "Columns", null, FOLDER_IMG_IDX); foreach (ColumnBinding columnBinding in tableBinding.Columns) Add(columnsNode.Nodes, columnBinding.Name, columnBinding, COLUMN_IMG_IDX); TreeNode parentsNode = Add(tableNode.Nodes, "Parents", null, FOLDER_IMG_IDX); foreach (TableRelation tableRelation in _dataContext.TableRelations.GetParentRelations(tableBinding)) Add(parentsNode.Nodes, tableRelation.ParentTable.Name, tableRelation, RELATION_IMG_IDX); TreeNode childrenNode = Add(tableNode.Nodes, "Children", null, FOLDER_IMG_IDX); foreach (TableRelation tableRelation in _dataContext.TableRelations.GetChildRelations(tableBinding)) Add(childrenNode.Nodes, tableRelation.ChildTable.Name, tableRelation, RELATION_IMG_IDX); } folderNode = Add(treeView.Nodes, "Functions", null, FOLDER_IMG_IDX); IEnumerable<List<FunctionBinding>> functionGroups = GetFunctionsGroupedByName(_dataContext.Functions); foreach (List<FunctionBinding> functionGroup in functionGroups) { TreeNode groupNode; bool isSingleFunction = functionGroup.Count == 1; if (isSingleFunction) groupNode = folderNode; else groupNode = Add(folderNode.Nodes, functionGroup[0].Name, null, FOLDER_IMG_IDX); foreach (FunctionBinding functionBinding in functionGroup) { string functionName; if (isSingleFunction) functionName = functionBinding.Name; else { StringBuilder sb = new StringBuilder(); foreach (Type parameterType in functionBinding.GetParameterTypes()) { if (sb.Length > 0) sb.Append(", "); sb.Append(parameterType.Name); } functionName = sb.ToString(); } TreeNode functionNode = Add(groupNode.Nodes, functionName, functionBinding, FUNCTION_IMG_IDX); foreach (InvokeParameter parameter in functionBinding.GetParameters()) Add(functionNode.Nodes, parameter.Name + ": " + parameter.DataType.Name, null, PARAMETER_IMG_IDX); } } folderNode = Add(treeView.Nodes, "Aggregates", null, FOLDER_IMG_IDX); foreach (AggregateBinding aggregateBinding in Sorted(_dataContext.Aggregates)) Add(folderNode.Nodes, aggregateBinding.Name, aggregateBinding, AGGREGATE_IMG_IDX); } RestoreExpandedNodes(expandedNodePaths, treeView.Nodes); NativeMethods.SetScrollPos(treeView, scrollPos, false); } finally { treeView.EndUpdate(); } } private static IEnumerable<T> Sorted<T>(IEnumerable<T> bindings) where T : Binding { List<T> sorted = new List<T>(bindings); sorted.Sort(delegate(T x, T y) { return x.Name.CompareTo(y.Name); }); return sorted; } private static IEnumerable<List<FunctionBinding>> GetFunctionsGroupedByName(IEnumerable<FunctionBinding> functions) { SortedDictionary<string, List<FunctionBinding>> functionGroups = new SortedDictionary<string, List<FunctionBinding>>(); foreach (FunctionBinding functionBinding in functions) { List<FunctionBinding> overloads; if (!functionGroups.TryGetValue(functionBinding.Name, out overloads)) { overloads = new List<FunctionBinding>(); functionGroups.Add(functionBinding.Name, overloads); } overloads.Add(functionBinding); } foreach (KeyValuePair<string, List<FunctionBinding>> functionGroup in functionGroups) yield return functionGroup.Value; } private static void SaveExpandedNodes(IDictionary<string, object> paths, TreeNodeCollection nodes) { foreach (TreeNode node in nodes) { if (node.IsExpanded) paths.Add(node.FullPath, null); SaveExpandedNodes(paths, node.Nodes); } } private static void RestoreExpandedNodes(IDictionary<string, object> paths, TreeNodeCollection nodes) { foreach (TreeNode node in nodes) { object dummy; if (paths.TryGetValue(node.FullPath, out dummy)) node.Expand(); RestoreExpandedNodes(paths, node.Nodes); } } private void treeView_ItemDrag(object sender, ItemDragEventArgs e) { Binding binding =((TreeNode) e.Item).Tag as Binding; if (binding != null) DoDragDrop(Identifier.CreateNonVerbatim(binding.Name).ToSource(), DragDropEffects.Copy); } private void treeView_AfterSelect(object sender, TreeViewEventArgs e) { EventHandler<EventArgs> handler = SelectedItemChanged; if (handler != null) handler(this, EventArgs.Empty); } private void treeView_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { TreeNode treeNode = treeView.GetNodeAt(e.Location); if (treeNode != null) treeView.SelectedNode = treeNode; } } } }
// 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.Threading.Tasks; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.NetCore.Analyzers.Runtime.TestForEmptyStringsUsingStringLengthAnalyzer, Microsoft.NetCore.CSharp.Analyzers.Runtime.CSharpTestForEmptyStringsUsingStringLengthFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.NetCore.Analyzers.Runtime.TestForEmptyStringsUsingStringLengthAnalyzer, Microsoft.NetCore.VisualBasic.Analyzers.Runtime.BasicTestForEmptyStringsUsingStringLengthFixer>; namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests { public class TestForEmptyStringsUsingStringLengthFixerTests { private const int c_StringLengthCodeActionIndex = 1; [Fact, WorkItem(3686, "https://github.com/dotnet/roslyn-analyzers/pull/3686")] public async Task CA1820_FixTestEmptyStringsUsingIsNullOrEmpty_WhenStringIsLiteral() { await VerifyCS.VerifyCodeFixAsync(@" public class A { public bool Compare(string s) { return [|s == """"|]; } public bool CompareEmptyIsLeft(string s) { return [|"""" == s|]; } } ", @" public class A { public bool Compare(string s) { return string.IsNullOrEmpty(s); } public bool CompareEmptyIsLeft(string s) { return string.IsNullOrEmpty(s); } } "); await VerifyVB.VerifyCodeFixAsync(@" Public Class A Public Function Compare(s As String) As Boolean Return [|s = """"|] End Function Public Function CompareEmptyIsLeft(s As String) As Boolean Return [|"""" = s|] End Function End Class ", @" Public Class A Public Function Compare(s As String) As Boolean Return String.IsNullOrEmpty(s) End Function Public Function CompareEmptyIsLeft(s As String) As Boolean Return String.IsNullOrEmpty(s) End Function End Class "); } [Fact] public async Task CA1820_FixTestEmptyStringsUsingStringLength_WhenStringIsLiteral() { await new VerifyCS.Test { TestState = { Sources = { @" public class A { public bool Compare(string s) { return [|s == """"|]; } } ", }, }, FixedState = { Sources = { @" public class A { public bool Compare(string s) { return s.Length == 0; } } ", }, }, CodeActionIndex = c_StringLengthCodeActionIndex, CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength", }.RunAsync(); await new VerifyVB.Test { TestState = { Sources = { @" Public Class A Public Function Compare(s As String) As Boolean Return [|s = """"|] End Function End Class ", }, }, FixedState = { Sources = { @" Public Class A Public Function Compare(s As String) As Boolean Return s.Length = 0 End Function End Class ", }, }, CodeActionIndex = c_StringLengthCodeActionIndex, CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength", }.RunAsync(); } [Fact] public async Task CA1820_FixTestEmptyStringsUsingIsNullOrEmpty() { await VerifyCS.VerifyCodeFixAsync(@" public class A { public bool Compare(string s) { return [|s == string.Empty|]; } } ", @" public class A { public bool Compare(string s) { return string.IsNullOrEmpty(s); } } "); await VerifyVB.VerifyCodeFixAsync(@" Public Class A Public Function Compare(s As String) As Boolean Return [|s = String.Empty|] End Function End Class ", @" Public Class A Public Function Compare(s As String) As Boolean Return String.IsNullOrEmpty(s) End Function End Class "); } [Fact] public async Task CA1820_FixTestEmptyStringsUsingStringLength() { await new VerifyCS.Test { TestState = { Sources = { @" public class A { public bool Compare(string s) { return [|s == string.Empty|]; } } ", }, }, FixedState = { Sources = { @" public class A { public bool Compare(string s) { return s.Length == 0; } } ", }, }, CodeActionIndex = c_StringLengthCodeActionIndex, CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength", }.RunAsync(); await new VerifyVB.Test { TestState = { Sources = { @" Public Class A Public Function Compare(s As String) As Boolean Return [|s = String.Empty|] End Function End Class ", }, }, FixedState = { Sources = { @" Public Class A Public Function Compare(s As String) As Boolean Return s.Length = 0 End Function End Class ", }, }, CodeActionIndex = c_StringLengthCodeActionIndex, CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength", }.RunAsync(); } [Fact] public async Task CA1820_FixTestEmptyStringsUsingIsNullOrEmptyComparisonOnRight() { await VerifyCS.VerifyCodeFixAsync(@" public class A { public bool Compare(string s) { return [|string.Empty == s|]; } } ", @" public class A { public bool Compare(string s) { return string.IsNullOrEmpty(s); } } "); await VerifyVB.VerifyCodeFixAsync(@" Public Class A Public Function Compare(s As String) As Boolean Return [|String.Empty = s|] End Function End Class ", @" Public Class A Public Function Compare(s As String) As Boolean Return String.IsNullOrEmpty(s) End Function End Class "); } [Fact] public async Task CA1820_FixTestEmptyStringsUsingStringLengthComparisonOnRight() { await new VerifyCS.Test { TestState = { Sources = { @" public class A { public bool Compare(string s) { return [|string.Empty == s|]; } } ", }, }, FixedState = { Sources = { @" public class A { public bool Compare(string s) { return 0 == s.Length; } } ", }, }, CodeActionIndex = c_StringLengthCodeActionIndex, CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength", }.RunAsync(); await new VerifyVB.Test { TestState = { Sources = { @" Public Class A Public Function Compare(s As String) As Boolean Return [|String.Empty = s|] End Function End Class ", }, }, FixedState = { Sources = { @" Public Class A Public Function Compare(s As String) As Boolean Return 0 = s.Length End Function End Class ", }, }, CodeActionIndex = c_StringLengthCodeActionIndex, CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength", }.RunAsync(); } [Fact] public async Task CA1820_FixInequalityTestEmptyStringsUsingIsNullOrEmpty() { await VerifyCS.VerifyCodeFixAsync(@" public class A { public bool Compare(string s) { return [|s != string.Empty|]; } } ", @" public class A { public bool Compare(string s) { return !string.IsNullOrEmpty(s); } } "); await VerifyVB.VerifyCodeFixAsync(@" Public Class A Public Function Compare(s As String) As Boolean Return [|s <> String.Empty|] End Function End Class ", @" Public Class A Public Function Compare(s As String) As Boolean Return Not String.IsNullOrEmpty(s) End Function End Class "); } [Fact] public async Task CA1820_FixInequalityTestEmptyStringsUsingStringLength() { await new VerifyCS.Test { TestState = { Sources = { @" public class A { public bool Compare(string s) { return [|s != string.Empty|]; } } ", }, }, FixedState = { Sources = { @" public class A { public bool Compare(string s) { return s.Length != 0; } } ", }, }, CodeActionIndex = c_StringLengthCodeActionIndex, CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength", }.RunAsync(); await new VerifyVB.Test { TestState = { Sources = { @" Public Class A Public Function Compare(s As String) As Boolean Return [|s <> String.Empty|] End Function End Class ", }, }, FixedState = { Sources = { @" Public Class A Public Function Compare(s As String) As Boolean Return s.Length <> 0 End Function End Class ", }, }, CodeActionIndex = c_StringLengthCodeActionIndex, CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength", }.RunAsync(); } [Fact] public async Task CA1820_FixInequalityTestEmptyStringsUsingIsNullOrEmptyComparisonOnRight() { await VerifyCS.VerifyCodeFixAsync(@" public class A { public bool Compare(string s) { return [|string.Empty != s|]; } } ", @" public class A { public bool Compare(string s) { return !string.IsNullOrEmpty(s); } } "); await VerifyVB.VerifyCodeFixAsync(@" Public Class A Public Function Compare(s As String) As Boolean Return [|String.Empty <> s|] End Function End Class ", @" Public Class A Public Function Compare(s As String) As Boolean Return Not String.IsNullOrEmpty(s) End Function End Class "); } [Fact] public async Task CA1820_FixInequalityTestEmptyStringsUsingStringLengthComparisonOnRight() { await new VerifyCS.Test { TestState = { Sources = { @" public class A { public bool Compare(string s) { return [|string.Empty != s|]; } } ", }, }, FixedState = { Sources = { @" public class A { public bool Compare(string s) { return 0 != s.Length; } } ", }, }, CodeActionIndex = c_StringLengthCodeActionIndex, CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength", }.RunAsync(); await new VerifyVB.Test { TestState = { Sources = { @" Public Class A Public Function Compare(s As String) As Boolean Return [|String.Empty <> s|] End Function End Class ", }, }, FixedState = { Sources = { @" Public Class A Public Function Compare(s As String) As Boolean Return 0 <> s.Length End Function End Class ", }, }, CodeActionIndex = c_StringLengthCodeActionIndex, CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength", }.RunAsync(); } [Fact] public async Task CA1820_FixForComparisonWithEmptyStringInFunctionArgument() { await VerifyCS.VerifyCodeFixAsync(@" public class A { string _s = string.Empty; public void F() { G([|_s == string.Empty|]); } public void G(bool comparison) {} } ", @" public class A { string _s = string.Empty; public void F() { G(string.IsNullOrEmpty(_s)); } public void G(bool comparison) {} } "); await VerifyVB.VerifyCodeFixAsync(@" Public Class A Private _s As String = String.Empty Public Sub F() G([|_s = String.Empty|]) End Sub Public Sub G(comparison As Boolean) End Sub End Class ", @" Public Class A Private _s As String = String.Empty Public Sub F() G(String.IsNullOrEmpty(_s)) End Sub Public Sub G(comparison As Boolean) End Sub End Class "); } [Fact] public async Task CA1820_FixForComparisonWithEmptyStringInTernaryOperator() { await VerifyCS.VerifyCodeFixAsync(@" public class A { string _s = string.Empty; public int F() { return [|_s == string.Empty|] ? 1 : 0; } } ", @" public class A { string _s = string.Empty; public int F() { return string.IsNullOrEmpty(_s) ? 1 : 0; } } "); // VB doesn't have the ternary operator, but we add this test for symmetry. await VerifyVB.VerifyCodeFixAsync(@" Public Class A Private _s As String = String.Empty Public Function F() As Integer Return If([|_s = String.Empty|], 1, 0) End Function End Class ", @" Public Class A Private _s As String = String.Empty Public Function F() As Integer Return If(String.IsNullOrEmpty(_s), 1, 0) End Function End Class "); } [Fact] public async Task CA1820_FixForComparisonWithEmptyStringInThrowStatement() { await VerifyCS.VerifyCodeFixAsync(@" public class A { string _s = string.Empty; public void F() { throw [|_s != string.Empty|] ? new System.Exception() : new System.ArgumentException(); } } ", @" public class A { string _s = string.Empty; public void F() { throw !string.IsNullOrEmpty(_s) ? new System.Exception() : new System.ArgumentException(); } } "); } [Fact] public async Task CA1820_FixForComparisonWithEmptyStringInCatchFilterClause() { await VerifyCS.VerifyCodeFixAsync(@" public class A { string _s = string.Empty; public void F() { try { } catch (System.Exception ex) when ([|_s != string.Empty|]) { } } } ", @" public class A { string _s = string.Empty; public void F() { try { } catch (System.Exception ex) when (!string.IsNullOrEmpty(_s)) { } } } "); } [Fact] public async Task CA1820_FixForComparisonWithEmptyStringInYieldReturnStatement() { await VerifyCS.VerifyCodeFixAsync(@" using System.Collections.Generic; public class A { string _s = string.Empty; public IEnumerable<bool> F() { yield return [|_s != string.Empty|]; } } ", @" using System.Collections.Generic; public class A { string _s = string.Empty; public IEnumerable<bool> F() { yield return !string.IsNullOrEmpty(_s); } } "); } [Fact] public async Task CA1820_FixForComparisonWithEmptyStringInSwitchStatement() { await VerifyCS.VerifyCodeFixAsync(@" public class A { string _s = string.Empty; public void F() { switch ([|_s != string.Empty|]) { default: throw new System.NotImplementedException(); } } } ", @" public class A { string _s = string.Empty; public void F() { switch (!string.IsNullOrEmpty(_s)) { default: throw new System.NotImplementedException(); } } } "); } [Fact] public async Task CA1820_FixForComparisonWithEmptyStringInForLoop() { await VerifyCS.VerifyCodeFixAsync(@" public class A { string _s = string.Empty; public void F() { for (; [|_s != string.Empty|]; ) { throw new System.Exception(); } } } ", @" public class A { string _s = string.Empty; public void F() { for (; !string.IsNullOrEmpty(_s); ) { throw new System.Exception(); } } } "); } [Fact] public async Task CA1820_FixForComparisonWithEmptyStringInWhileLoop() { await VerifyCS.VerifyCodeFixAsync(@" public class A { string _s = string.Empty; public void F() { while ([|_s != string.Empty|]) { } } } ", @" public class A { string _s = string.Empty; public void F() { while (!string.IsNullOrEmpty(_s)) { } } } "); } [Fact] public async Task CA1820_FixForComparisonWithEmptyStringInDoWhileLoop() { await VerifyCS.VerifyCodeFixAsync(@" public class A { string _s = string.Empty; public void F() { do { } while ([|_s != string.Empty|]); } } ", @" public class A { string _s = string.Empty; public void F() { do { } while (!string.IsNullOrEmpty(_s)); } } "); } [Fact] public async Task CA1820_MultilineFixTestEmptyStringsUsingIsNullOrEmpty() { await VerifyCS.VerifyCodeFixAsync(@" public class A { string _s = string.Empty; public bool Compare(string s) { return [|s == string.Empty|] || s == _s; } } ", @" public class A { string _s = string.Empty; public bool Compare(string s) { return string.IsNullOrEmpty(s) || s == _s; } } "); await VerifyVB.VerifyCodeFixAsync(@" Public Class A Private _s As String = String.Empty Public Function Compare(s As String) As Boolean Return [|s = String.Empty|] Or s = _s End Function End Class ", @" Public Class A Private _s As String = String.Empty Public Function Compare(s As String) As Boolean Return String.IsNullOrEmpty(s) Or s = _s End Function End Class "); } [Fact] public async Task CA1820_MultilineFixTestEmptyStringsUsingStringLength() { await new VerifyCS.Test { TestState = { Sources = { @" public class A { string _s = string.Empty; public bool Compare(string s) { return [|s == string.Empty|] || s == _s; } } ", }, }, FixedState = { Sources = { @" public class A { string _s = string.Empty; public bool Compare(string s) { return s.Length == 0 || s == _s; } } ", }, }, CodeActionIndex = c_StringLengthCodeActionIndex, CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength", }.RunAsync(); await new VerifyVB.Test { TestState = { Sources = { @" Public Class A Private _s As String = String.Empty Public Function Compare(s As String) As Boolean Return [|s = String.Empty|] Or s = _s End Function End Class ", }, }, FixedState = { Sources = { @" Public Class A Private _s As String = String.Empty Public Function Compare(s As String) As Boolean Return s.Length = 0 Or s = _s End Function End Class ", }, }, CodeActionIndex = c_StringLengthCodeActionIndex, CodeActionEquivalenceKey = "TestForEmptyStringCorrectlyUsingStringLength", }.RunAsync(); } } }
using GraphQLParser.Visitors; namespace GraphQLParser.Tests.Visitors; public class SDLPrinterVerticalIndentationTests { [Theory] [InlineData(1, @" extend schema @good scalar A schema { query: Q } extend schema @bad ", @"extend schema @good scalar A schema { query: Q } extend schema @bad")] [InlineData(2, @"scalar A1 scalar B scalar C scalar A2 ", @"scalar A1 scalar A2")] [InlineData(3, @"scalar A1 scalar B scalar A2 scalar E scalar D ", @"scalar A1 scalar A2")] [InlineData(4, @"query A1 { x } query B { y } query A2 { z } ", @"query A1 { x } query A2 { z }")] [InlineData(5, @"directive @A1 on FIELD directive @B on FIELD directive @A2 on FIELD ", @"directive @A1 on FIELD directive @A2 on FIELD")] [InlineData(6, @"enum A1 { X Y } enum B { X Y } enum A2 { X Y } enum E { X Y } enum D { X Y } ", @"enum A1 { X Y } enum A2 { X Y }")] [InlineData(7, @"extend enum A1 { X Y } extend enum B { X Y } extend enum A2 { X Y } extend enum E { X Y } extend enum D { X Y } ", @"extend enum A1 { X Y } extend enum A2 { X Y }")] [InlineData(8, @"input A1 @vip input B input A2 { a: Int } input E input D ", @"input A1 @vip input A2 { a: Int }")] [InlineData(9, @"type A1 @vip type B type A2 { a: Int } type E type D ", @"type A1 @vip type A2 { a: Int }")] [InlineData(10, @"interface A1 @vip interface B interface A2 { a: Int } interface E interface D ", @"interface A1 @vip interface A2 { a: Int }")] [InlineData(11, @"extend interface A1 @vip extend interface B { a: Int } extend interface A2 { a: Int } extend interface E { a: Int } extend interface D { a: Int } ", @"extend interface A1 @vip extend interface A2 { a: Int }")] [InlineData(12, @"union A1 @vip union B = X | Y union A2 = X | Y union E = X | Y union D = X | Y ", @"union A1 @vip union A2 = X | Y")] [InlineData(13, @"extend input A1 { a: Int } extend input B { a: Int } extend input A2 { a: Int } extend input E { a: Int } extend input D { a: Int } ", @"extend input A1 { a: Int } extend input A2 { a: Int }")] [InlineData(14, @"extend type A1 { a: Int } extend type B { a: Int } extend type A2 { a: Int } extend type E { a: Int } extend type D { a: Int } ", @"extend type A1 { a: Int } extend type A2 { a: Int }")] public async Task Printer_Should_Print_Pretty_If_Definitions_Skipped( int number, string text, string expected) { var printer = new MyPrinter(); var writer = new StringWriter(); var document = text.Parse(); await printer.PrintAsync(document, writer).ConfigureAwait(false); var actual = writer.ToString(); actual.ShouldBe(expected, $"Test {number} failed"); actual.Parse(); // should be parsed back } private class MyPrinter : SDLPrinter { protected override ValueTask VisitObjectTypeExtensionAsync(GraphQLObjectTypeExtension objectTypeExtension, DefaultPrintContext context) { return objectTypeExtension.Name.Value.Span[0] == 'A' ? base.VisitObjectTypeExtensionAsync(objectTypeExtension, context) : default; } protected override ValueTask VisitInputObjectTypeExtensionAsync(GraphQLInputObjectTypeExtension inputObjectTypeExtension, DefaultPrintContext context) { return inputObjectTypeExtension.Name.Value.Span[0] == 'A' ? base.VisitInputObjectTypeExtensionAsync(inputObjectTypeExtension, context) : default; } protected override ValueTask VisitUnionTypeDefinitionAsync(GraphQLUnionTypeDefinition unionTypeDefinition, DefaultPrintContext context) { return unionTypeDefinition.Name.Value.Span[0] == 'A' ? base.VisitUnionTypeDefinitionAsync(unionTypeDefinition, context) : default; } protected override ValueTask VisitInterfaceTypeExtensionAsync(GraphQLInterfaceTypeExtension interfaceTypeExtension, DefaultPrintContext context) { return interfaceTypeExtension.Name.Value.Span[0] == 'A' ? base.VisitInterfaceTypeExtensionAsync(interfaceTypeExtension, context) : default; } protected override ValueTask VisitInterfaceTypeDefinitionAsync(GraphQLInterfaceTypeDefinition interfaceTypeDefinition, DefaultPrintContext context) { return interfaceTypeDefinition.Name.Value.Span[0] == 'A' ? base.VisitInterfaceTypeDefinitionAsync(interfaceTypeDefinition, context) : default; } protected override ValueTask VisitObjectTypeDefinitionAsync(GraphQLObjectTypeDefinition objectTypeDefinition, DefaultPrintContext context) { return objectTypeDefinition.Name.Value.Span[0] == 'A' ? base.VisitObjectTypeDefinitionAsync(objectTypeDefinition, context) : default; } protected override ValueTask VisitInputObjectTypeDefinitionAsync(GraphQLInputObjectTypeDefinition inputObjectTypeDefinition, DefaultPrintContext context) { return inputObjectTypeDefinition.Name.Value.Span[0] == 'A' ? base.VisitInputObjectTypeDefinitionAsync(inputObjectTypeDefinition, context) : default; } protected override ValueTask VisitEnumTypeExtensionAsync(GraphQLEnumTypeExtension enumTypeExtension, DefaultPrintContext context) { return enumTypeExtension.Name.Value.Span[0] == 'A' ? base.VisitEnumTypeExtensionAsync(enumTypeExtension, context) : default; } protected override ValueTask VisitDirectiveDefinitionAsync(GraphQLDirectiveDefinition directiveDefinition, DefaultPrintContext context) { return directiveDefinition.Name.Value.Span[0] == 'A' ? base.VisitDirectiveDefinitionAsync(directiveDefinition, context) : default; } protected override ValueTask VisitOperationDefinitionAsync(GraphQLOperationDefinition operationDefinition, DefaultPrintContext context) { return operationDefinition.Name.Value.Span[0] == 'A' ? base.VisitOperationDefinitionAsync(operationDefinition, context) : default; } protected override ValueTask VisitScalarTypeDefinitionAsync(GraphQLScalarTypeDefinition scalarTypeDefinition, DefaultPrintContext context) { return scalarTypeDefinition.Name.Value.Span[0] == 'A' ? base.VisitScalarTypeDefinitionAsync(scalarTypeDefinition, context) : default; } protected override ValueTask VisitEnumTypeDefinitionAsync(GraphQLEnumTypeDefinition enumTypeDefinition, DefaultPrintContext context) { return enumTypeDefinition.Name.Value.Span[0] == 'A' ? base.VisitEnumTypeDefinitionAsync(enumTypeDefinition, context) : default; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Baseline; using Weasel.Postgresql; using Newtonsoft.Json.Linq; using Shouldly; using Weasel.Core; namespace Marten.Schema.Testing { public static class Exception<T> where T : Exception { public static T ShouldBeThrownBy(Action action) { T exception = null; try { action(); } catch (Exception e) { exception = e.ShouldBeOfType<T>(); } exception.ShouldNotBeNull("An exception was expected, but not thrown by the given action."); return exception; } public static async Task<T> ShouldBeThrownByAsync(Func<Task> action) { T exception = null; try { await action(); } catch (Exception e) { exception = e.ShouldBeOfType<T>(); } exception.ShouldNotBeNull("An exception was expected, but not thrown by the given action."); return exception; } } public delegate void MethodThatThrows(); public static class SpecificationExtensions { public static void ShouldBeSemanticallySameJsonAs(this string json, string expectedJson) { var actual = JToken.Parse(json); var expected = JToken.Parse(expectedJson); JToken.DeepEquals(expected, actual).ShouldBeTrue($"Expected:\n{expectedJson}\nGot:\n{json}"); } public static void ShouldContain<T>(this IEnumerable<T> actual, Func<T, bool> expected) { actual.Count().ShouldBeGreaterThan(0); actual.Any(expected).ShouldBeTrue(); } public static void ShouldHaveTheSameElementsAs<T>(this IEnumerable<T> actual, IEnumerable<T> expected) { var actualList = (actual is IList tempActual) ? tempActual : actual.ToList(); var expectedList = (expected is IList tempExpected) ? tempExpected : expected.ToList(); ShouldHaveTheSameElementsAs(actualList, expectedList); } public static void ShouldHaveTheSameElementsAs<T>(this IEnumerable<T> actual, params T[] expected) { var actualList = (actual is IList tempActual) ? tempActual : actual.ToList(); var expectedList = (expected is IList tempExpected) ? tempExpected : expected.ToList(); ShouldHaveTheSameElementsAs(actualList, expectedList); } public static void ShouldHaveTheSameElementsAs(this IList actual, IList expected) { actual.ShouldNotBeNull(); expected.ShouldNotBeNull(); try { actual.Count.ShouldBe(expected.Count, $"Actual was " + actual.OfType<object>().Select(x => x.ToString()).Join(", ")); for (var i = 0; i < actual.Count; i++) { actual[i].ShouldBe(expected[i]); } } catch (Exception) { Debug.WriteLine("ACTUAL:"); foreach (var o in actual) { Debug.WriteLine(o); } throw; } } public static void ShouldBeNull(this object anObject) { anObject.ShouldBe(null); } public static void ShouldNotBeNull(this object anObject) { anObject.ShouldNotBe(null); } public static object ShouldBeTheSameAs(this object actual, object expected) { ReferenceEquals(actual, expected).ShouldBeTrue(); return expected; } public static T IsType<T>(this object actual) { actual.ShouldBeOfType(typeof(T)); return (T)actual; } public static object ShouldNotBeTheSameAs(this object actual, object expected) { ReferenceEquals(actual, expected).ShouldBeFalse(); return expected; } public static void ShouldNotBeOfType<T>(this object actual) { actual.ShouldNotBeOfType(typeof(T)); } public static void ShouldNotBeOfType(this object actual, Type expected) { actual.GetType().ShouldNotBe(expected); } public static IComparable ShouldBeGreaterThan(this IComparable arg1, IComparable arg2) { (arg1.CompareTo(arg2) > 0).ShouldBeTrue(); return arg2; } public static string ShouldNotBeEmpty(this string aString) { aString.IsNotEmpty().ShouldBeTrue(); return aString; } public static void ShouldContain(this string actual, string expected, StringComparisonOption options = StringComparisonOption.Default) { if (options == StringComparisonOption.NormalizeWhitespaces) { actual = Regex.Replace(actual, @"\s+", " "); expected = Regex.Replace(expected, @"\s+", " "); } actual.Contains(expected).ShouldBeTrue($"Actual: {actual}{Environment.NewLine}Expected: {expected}"); } public static string ShouldNotContain(this string actual, string expected, StringComparisonOption options = StringComparisonOption.NormalizeWhitespaces) { if (options == StringComparisonOption.NormalizeWhitespaces) { actual = Regex.Replace(actual, @"\s+", " "); expected = Regex.Replace(expected, @"\s+", " "); } actual.Contains(expected).ShouldBeFalse($"Actual: {actual}{Environment.NewLine}Expected: {expected}"); return actual; } public static void ShouldStartWith(this string actual, string expected) { actual.StartsWith(expected).ShouldBeTrue(); } public static Exception ShouldBeThrownBy(this Type exceptionType, MethodThatThrows method) { Exception exception = null; try { method(); } catch (Exception e) { e.GetType().ShouldBe(exceptionType); exception = e; } exception.ShouldNotBeNull("Expected {0} to be thrown.".ToFormat(exceptionType.FullName)); return exception; } public static void ShouldBeEqualWithDbPrecision(this DateTime actual, DateTime expected) { static DateTime toDbPrecision(DateTime date) => new DateTime(date.Ticks / 1000 * 1000); toDbPrecision(actual).ShouldBe(toDbPrecision(expected)); } public static void ShouldBeEqualWithDbPrecision(this DateTimeOffset actual, DateTimeOffset expected) { static DateTimeOffset toDbPrecision(DateTimeOffset date) => new DateTimeOffset(date.Ticks / 1000 * 1000, new TimeSpan(date.Offset.Ticks / 1000 * 1000)); toDbPrecision(actual).ShouldBe(toDbPrecision(expected)); } public static void ShouldContain(this DbObjectName[] names, string qualifiedName) { if (names == null) throw new ArgumentNullException(nameof(names)); var function = DbObjectName.Parse(PostgresqlProvider.Instance, qualifiedName); names.ShouldContain(function); } } public enum StringComparisonOption { Default, NormalizeWhitespaces } }
using AutoMapper; using Microsoft.Azure.Commands.Compute.Common; using Microsoft.Azure.Commands.Compute.Models; using Microsoft.Azure.Common.Authentication.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; using System; using System.Collections; using System.Globalization; using System.IO; using System.Management.Automation; using System.Text.RegularExpressions; namespace Microsoft.Azure.Commands.Compute.Extension.DSC { [Cmdlet( VerbsCommon.Set, ProfileNouns.VirtualMachineDscExtension, SupportsShouldProcess = true, DefaultParameterSetName = AzureBlobDscExtensionParamSet)] [OutputType(typeof(PSComputeLongRunningOperation))] public class SetAzureVMDscExtensionCommand : VirtualMachineExtensionBaseCmdlet { protected const string AzureBlobDscExtensionParamSet = "AzureBlobDscExtension"; [Parameter( Mandatory = true, Position = 2, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the resource group that contains the virtual machine.")] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Parameter( Mandatory = true, Position = 3, ValueFromPipelineByPropertyName = true, HelpMessage = "Name of the virtual machine where dsc extension handler would be installed.")] [ValidateNotNullOrEmpty] public string VMName { get; set; } [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Name of the ARM resource that represents the extension. This is defaulted to 'Microsoft.Powershell.DSC'")] [ValidateNotNullOrEmpty] public string Name { get; set; } /// <summary> /// The name of the configuration archive that was previously uploaded by /// Publish-AzureRmVMDSCConfiguration. This parameter must specify only the name /// of the file, without any path. /// A null value or empty string indicate that the VM extension should install DSC, /// but not start any configuration /// </summary> [Alias("ConfigurationArchiveBlob")] [Parameter( Mandatory = true, Position = 5, ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "The name of the configuration file that was previously uploaded by Publish-AzureRmVMDSCConfiguration")] [AllowEmptyString] [AllowNull] public string ArchiveBlobName { get; set; } /// <summary> /// The Azure Storage Account name used to upload the configuration script to the container specified by ArchiveContainerName. /// </summary> [Alias("StorageAccountName")] [Parameter( Mandatory = true, Position = 4, ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "The Azure Storage Account name used to download the ArchiveBlobName")] [ValidateNotNullOrEmpty] public String ArchiveStorageAccountName { get; set; } [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "The name of the resource group that contains the storage account containing the configuration archive. " + "This param is optional if storage account and virtual machine both exists in the same resource group name, " + "specified by ResourceGroupName param.")] [ValidateNotNullOrEmpty] public string ArchiveResourceGroupName { get; set; } /// <summary> /// The DNS endpoint suffix for all storage services, e.g. "core.windows.net". /// </summary> [Alias("StorageEndpointSuffix")] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "The Storage Endpoint Suffix.")] [ValidateNotNullOrEmpty] public string ArchiveStorageEndpointSuffix { get; set; } /// <summary> /// Name of the Azure Storage Container where the configuration script is located. /// </summary> [Alias("ContainerName")] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "Name of the Azure Storage Container where the configuration archive is located")] [ValidateNotNullOrEmpty] public string ArchiveContainerName { get; set; } /// <summary> /// Name of the configuration that will be invoked by the DSC Extension. The value of this parameter should be the name of one of the configurations /// contained within the file specified by ArchiveBlobName. /// /// If omitted, this parameter will default to the name of the file given by the ArchiveBlobName parameter, excluding any extension, for example if /// ArchiveBlobName is "SalesWebSite.ps1", the default value for ConfigurationName will be "SalesWebSite". /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Name of the configuration that will be invoked by the DSC Extension")] [ValidateNotNullOrEmpty] public string ConfigurationName { get; set; } /// <summary> /// A hashtable specifying the arguments to the ConfigurationFunction. The keys /// correspond to the parameter names and the values to the parameter values. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "A hashtable specifying the arguments to the ConfigurationFunction")] [ValidateNotNullOrEmpty] public Hashtable ConfigurationArgument { get; set; } /// <summary> /// Path to a .psd1 file that specifies the data for the Configuration. This /// file must contain a hashtable with the items described in /// http://technet.microsoft.com/en-us/library/dn249925.aspx. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Path to a .psd1 file that specifies the data for the Configuration")] [ValidateNotNullOrEmpty] public string ConfigurationData { get; set; } /// <summary> /// The specific version of the DSC extension that Set-AzureRmVMDSCExtension will /// apply the settings to. /// </summary> [Alias("HandlerVersion")] [Parameter( Mandatory = true, Position = 1, ValueFromPipelineByPropertyName = true, HelpMessage = "The version of the DSC extension that Set-AzureRmVMDSCExtension will apply the settings to. " + "Allowed format N.N")] [ValidateNotNullOrEmpty] public string Version { get; set; } /// <summary> /// By default Set-AzureRmVMDscExtension will not overwrite any existing blobs. Use -Force to overwrite them. /// </summary> [Parameter( HelpMessage = "Use this parameter to overwrite any existing blobs")] public SwitchParameter Force { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Location of the resource.")] [ValidateNotNullOrEmpty] public string Location { get; set; } /// <summary> /// We install the extension handler version specified by the version param. By default extension handler is not autoupdated. /// Use -AutoUpdate to enable auto update of extension handler to the latest version as and when it is available. /// </summary> [Parameter( HelpMessage = "Extension handler gets auto updated to the latest version if this switch is present.")] public SwitchParameter AutoUpdate { get; set; } /// <summary> /// Specifies the version of the Windows Management Framework (WMF) to install /// on the VM. /// /// The DSC Azure Extension depends on DSC features that are only available in /// the WMF updates. This parameter specifies which version of the update to /// install on the VM. The possible values are "4.0","latest" and "5.0PP". /// /// A value of "4.0" will install KB3000850 /// (http://support.microsoft.com/kb/3000850) on Windows 8.1 or Windows Server /// 2012 R2, or WMF 4.0 /// (http://www.microsoft.com/en-us/download/details.aspx?id=40855) on other /// versions of Windows if a newer version isnt already installed. /// /// A value of "5.0PP" will install the latest release of WMF 5.0PP /// (http://go.microsoft.com/fwlink/?LinkId=398175). /// /// A value of "latest" will install the latest WMF, currently WMF 5.0PP /// /// The default value is "latest" /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [ValidateSetAttribute(new[] { "4.0", "latest", "5.0PP" })] public string WmfVersion { get; set; } //Private Variables private const string VersionRegexExpr = @"^(([0-9])\.)\d+$"; /// <summary> /// Credentials used to access Azure Storage /// </summary> private StorageCredentials _storageCredentials; protected override void ProcessRecord() { base.ProcessRecord(); ValidateParameters(); CreateConfiguration(); } //Private Methods private void ValidateParameters() { if (string.IsNullOrEmpty(ArchiveBlobName)) { if (ConfigurationName != null || ConfigurationArgument != null || ConfigurationData != null) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscNullArchiveNoConfiguragionParameters); } if (ArchiveContainerName != null || ArchiveStorageEndpointSuffix != null) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscNullArchiveNoStorageParameters); } } else { if (string.Compare( Path.GetFileName(ArchiveBlobName), ArchiveBlobName, StringComparison.InvariantCultureIgnoreCase) != 0) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscConfigurationDataFileShouldNotIncludePath); } if (ConfigurationData != null) { ConfigurationData = GetUnresolvedProviderPathFromPSPath(ConfigurationData); if (!File.Exists(ConfigurationData)) { this.ThrowInvalidArgumentError( Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscCannotFindConfigurationDataFile, ConfigurationData); } if (string.Compare( Path.GetExtension(ConfigurationData), ".psd1", StringComparison.InvariantCultureIgnoreCase) != 0) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscInvalidConfigurationDataFile); } } if (ArchiveResourceGroupName == null) { ArchiveResourceGroupName = ResourceGroupName; } _storageCredentials = this.GetStorageCredentials(ArchiveResourceGroupName, ArchiveStorageAccountName); if (ConfigurationName == null) { ConfigurationName = Path.GetFileNameWithoutExtension(ArchiveBlobName); } if (ArchiveContainerName == null) { ArchiveContainerName = DscExtensionCmdletConstants.DefaultContainerName; } if (ArchiveStorageEndpointSuffix == null) { ArchiveStorageEndpointSuffix = DefaultProfile.Context.Environment.GetEndpoint(AzureEnvironment.Endpoint.StorageEndpointSuffix); } if (!(Regex.Match(Version, VersionRegexExpr).Success)) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscExtensionInvalidVersion); } } } private void CreateConfiguration() { var publicSettings = new DscExtensionPublicSettings(); var privateSettings = new DscExtensionPrivateSettings(); publicSettings.WmfVersion = string.IsNullOrEmpty(WmfVersion) ? "latest" : WmfVersion; if (!string.IsNullOrEmpty(ArchiveBlobName)) { ConfigurationUris configurationUris = UploadConfigurationDataToBlob(); publicSettings.SasToken = configurationUris.SasToken; publicSettings.ModulesUrl = configurationUris.ModulesUrl; publicSettings.ConfigurationFunction = string.Format( CultureInfo.InvariantCulture, "{0}\\{1}", Path.GetFileNameWithoutExtension(ArchiveBlobName), ConfigurationName); Tuple<DscExtensionPublicSettings.Property[], Hashtable> settings = DscExtensionSettingsSerializer.SeparatePrivateItems(ConfigurationArgument); publicSettings.Properties = settings.Item1; privateSettings.Items = settings.Item2; privateSettings.DataBlobUri = configurationUris.DataBlobUri; } var parameters = new VirtualMachineExtension { Location = Location, Name = Name ?? DscExtensionCmdletConstants.ExtensionPublishedNamespace + "." + DscExtensionCmdletConstants.ExtensionPublishedName, Type = VirtualMachineExtensionType, Publisher = DscExtensionCmdletConstants.ExtensionPublishedNamespace, ExtensionType = DscExtensionCmdletConstants.ExtensionPublishedName, TypeHandlerVersion = Version, // Define the public and private property bags that will be passed to the extension. Settings = DscExtensionSettingsSerializer.SerializePublicSettings(publicSettings), //PrivateConfuguration contains sensitive data in a plain text ProtectedSettings = DscExtensionSettingsSerializer.SerializePrivateSettings(privateSettings), AutoUpgradeMinorVersion = AutoUpdate.IsPresent }; //Add retry logic due to CRP service restart known issue CRP bug: 3564713 var count = 1; ComputeLongRunningOperationResponse op = null; while (count <= 2) { op = VirtualMachineExtensionClient.CreateOrUpdate( ResourceGroupName, VMName, parameters); if (ComputeOperationStatus.Failed.Equals(op.Status) && op.Error != null && "InternalExecutionError".Equals(op.Error.Code)) { count++; } else { break; } } var result = Mapper.Map<PSComputeLongRunningOperation>(op); WriteObject(result); } /// <summary> /// Uploading configuration data to blob storage. /// </summary> /// <returns>ConfigurationUris collection that represent artifacts of uploading</returns> private ConfigurationUris UploadConfigurationDataToBlob() { // // Get a reference to the container in blob storage // var storageAccount = new CloudStorageAccount(_storageCredentials, ArchiveStorageEndpointSuffix, true); var blobClient = storageAccount.CreateCloudBlobClient(); var containerReference = blobClient.GetContainerReference(ArchiveContainerName); // // Get a reference to the configuration blob and create a SAS token to access it // var blobAccessPolicy = new SharedAccessBlobPolicy { SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1), Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Delete }; var configurationBlobName = ArchiveBlobName; var configurationBlobReference = containerReference.GetBlockBlobReference(configurationBlobName); var configurationBlobSasToken = configurationBlobReference.GetSharedAccessSignature(blobAccessPolicy); // // Upload the configuration data to blob storage and get a SAS token // string configurationDataBlobUri = null; if (ConfigurationData != null) { var guid = Guid.NewGuid(); // there may be multiple VMs using the same configuration var configurationDataBlobName = string.Format( CultureInfo.InvariantCulture, "{0}-{1}.psd1", ConfigurationName, guid); var configurationDataBlobReference = containerReference.GetBlockBlobReference(configurationDataBlobName); ConfirmAction( true, string.Empty, string.Format( CultureInfo.CurrentUICulture, Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscUploadToBlobStorageAction, ConfigurationData), configurationDataBlobReference.Uri.AbsoluteUri, () => { if (!Force && configurationDataBlobReference.Exists()) { ThrowTerminatingError( new ErrorRecord( new UnauthorizedAccessException( string.Format( CultureInfo.CurrentUICulture, Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscStorageBlobAlreadyExists, configurationDataBlobName)), "StorageBlobAlreadyExists", ErrorCategory.PermissionDenied, null)); } configurationDataBlobReference.UploadFromFile(ConfigurationData, FileMode.Open); var configurationDataBlobSasToken = configurationDataBlobReference.GetSharedAccessSignature(blobAccessPolicy); configurationDataBlobUri = configurationDataBlobReference.StorageUri.PrimaryUri.AbsoluteUri + configurationDataBlobSasToken; }); } return new ConfigurationUris { ModulesUrl = configurationBlobReference.StorageUri.PrimaryUri.AbsoluteUri, SasToken = configurationBlobSasToken, DataBlobUri = configurationDataBlobUri }; } /// <summary> /// Class represent info about uploaded Configuration. /// </summary> private class ConfigurationUris { public string SasToken { get; set; } public string DataBlobUri { get; set; } public string ModulesUrl { get; set; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using AlbumSystem.Services.Areas.HelpPage.ModelDescriptions; using AlbumSystem.Services.Areas.HelpPage.Models; namespace AlbumSystem.Services.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Globalization; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Tasks; using Microsoft.Build.Utilities; using Shouldly; using Xunit; using Xunit.Abstractions; using ItemMetadataNames = Microsoft.Build.Tasks.ItemMetadataNames; namespace Microsoft.Build.UnitTests.ResolveAssemblyReference_Tests { /// <summary> /// Unit tests for the ResolveAssemblyReference task. /// </summary> [Trait("Category", "non-mono-tests")] public sealed class WinMDTests : ResolveAssemblyReferenceTestFixture { public WinMDTests(ITestOutputHelper output) : base(output) { } #region AssemblyInformationIsWinMDFile Tests /// <summary> /// Verify a null file path passed in return the fact the file is not a winmd file. /// </summary> [Fact] public void IsWinMDFileNullFilePath() { string imageRuntime; bool isManagedWinMD; Assert.False(AssemblyInformation.IsWinMDFile(null, getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.False(isManagedWinMD); } /// <summary> /// Verify if a empty file path is passed in that the file is not a winmd file. /// </summary> [Fact] public void IsWinMDFileEmptyFilePath() { string imageRuntime; bool isManagedWinMD; Assert.False(AssemblyInformation.IsWinMDFile(String.Empty, getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.False(isManagedWinMD); } /// <summary> /// If the file does not exist then we should report this is not a winmd file. /// </summary> [Fact] public void IsWinMDFileFileDoesNotExistFilePath() { string imageRuntime; bool isManagedWinMD; Assert.False(AssemblyInformation.IsWinMDFile(@"C:\WinMD\SampleDoesNotExist.Winmd", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.False(isManagedWinMD); } /// <summary> /// The file exists and has the correct windowsruntime metadata, we should report this is a winmd file. /// </summary> [Fact] public void IsWinMDFileGoodFile() { string imageRuntime; bool isManagedWinMD; Assert.True(AssemblyInformation.IsWinMDFile(@"C:\WinMD\SampleWindowsRuntimeOnly.Winmd", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.False(isManagedWinMD); } /// <summary> /// This file is a mixed file with CLR and windowsruntime metadata we should report this is a winmd file. /// </summary> [Fact] public void IsWinMDFileMixedFile() { string imageRuntime; bool isManagedWinMD; Assert.True(AssemblyInformation.IsWinMDFile(@"C:\WinMD\SampleWindowsRuntimeAndCLR.Winmd", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.True(isManagedWinMD); } /// <summary> /// The file has only CLR metadata we should report this is not a winmd file /// </summary> [Fact] public void IsWinMDFileCLROnlyFile() { string imageRuntime; bool isManagedWinMD; Assert.False(AssemblyInformation.IsWinMDFile(@"C:\WinMD\SampleClrOnly.Winmd", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.False(isManagedWinMD); } /// <summary> /// The windows runtime string is not correctly formatted, report this is not a winmd file. /// </summary> [Fact] public void IsWinMDFileBadWindowsRuntimeFile() { string imageRuntime; bool isManagedWinMD; Assert.False(AssemblyInformation.IsWinMDFile(@"C:\WinMD\SampleBadWindowsRuntime.Winmd", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.False(isManagedWinMD); } /// <summary> /// We should report that a regular net assembly is not a winmd file. /// </summary> [Fact] public void IsWinMDFileRegularNetAssemblyFile() { string imageRuntime; bool isManagedWinMD; Assert.False(AssemblyInformation.IsWinMDFile(@"C:\Framework\Whidbey\System.dll", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.False(isManagedWinMD); } /// <summary> /// When a project to project reference is passed in we want to verify that /// the winmd references get the correct metadata applied to them /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void VerifyP2PHaveCorrectMetadataWinMD(bool setImplementationMetadata) { // Create the engine. MockEngine engine = new MockEngine(_output); TaskItem taskItem = new TaskItem(@"C:\WinMD\SampleWindowsRuntimeOnly.Winmd"); if (setImplementationMetadata) { taskItem.SetMetadata(ItemMetadataNames.winmdImplmentationFile, "SampleWindowsRuntimeOnly.dll"); } ITaskItem[] assemblyFiles = new TaskItem[] { taskItem }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.AssemblyFiles = assemblyFiles; t.TargetProcessorArchitecture = "X86"; t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Single(t.ResolvedFiles); Assert.Equal(2, t.RelatedFiles.Length); bool dllFound = false; bool priFound = false; foreach (ITaskItem item in t.RelatedFiles) { if (item.ItemSpec.EndsWith(@"C:\WinMD\SampleWindowsRuntimeOnly.dll")) { dllFound = true; Assert.Empty(item.GetMetadata(ItemMetadataNames.imageRuntime)); Assert.Empty(item.GetMetadata(ItemMetadataNames.winMDFile)); Assert.Empty(item.GetMetadata(ItemMetadataNames.winmdImplmentationFile)); } if (item.ItemSpec.EndsWith(@"C:\WinMD\SampleWindowsRuntimeOnly.pri")) { priFound = true; Assert.Empty(item.GetMetadata(ItemMetadataNames.imageRuntime)); Assert.Empty(item.GetMetadata(ItemMetadataNames.winMDFile)); Assert.Empty(item.GetMetadata(ItemMetadataNames.winmdImplmentationFile)); } } Assert.True(dllFound && priFound); // "Expected to find .dll and .pri related files." Assert.Empty(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); Assert.Equal("Native", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFileType)); Assert.Equal("SampleWindowsRuntimeOnly.dll", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); Assert.Equal("WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); } [Fact] public void VerifyP2PHaveCorrectMetadataWinMDStaticLib() { // Create the engine. MockEngine engine = new MockEngine(_output); TaskItem taskItem = new TaskItem(@"C:\WinMDLib\LibWithWinmdAndNoDll.Winmd"); taskItem.SetMetadata(ItemMetadataNames.winmdImplmentationFile, "LibWithWinmdAndNoDll.lib"); ITaskItem[] assemblyFiles = new TaskItem[] { taskItem }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.AssemblyFiles = assemblyFiles; t.TargetProcessorArchitecture = "X86"; t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" }; Execute(t).ShouldBeTrue(); engine.Errors.ShouldBe(0); engine.Warnings.ShouldBe(0); t.ResolvedFiles.ShouldHaveSingleItem(); t.RelatedFiles.ShouldHaveSingleItem(); t.RelatedFiles[0].ItemSpec.ShouldBe(@"C:\WinMDLib\LibWithWinmdAndNoDll.pri", "Expected to find .pri related files but NOT the lib."); t.RelatedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime).ShouldBeEmpty(); t.RelatedFiles[0].GetMetadata(ItemMetadataNames.winMDFile).ShouldBeEmpty(); t.RelatedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile).ShouldBeEmpty(); t.ResolvedDependencyFiles.ShouldBeEmpty(); bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile)).ShouldBeTrue(); t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFileType).ShouldBe("Native"); t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile).ShouldBe("LibWithWinmdAndNoDll.lib"); } /// <summary> /// When a project to project reference is passed in we want to verify that /// the winmd references get the correct metadata applied to them /// </summary> [Fact] public void VerifyP2PHaveCorrectMetadataWinMDManaged() { // Create the engine. MockEngine engine = new MockEngine(_output); TaskItem taskItem = new TaskItem(@"C:\WinMD\SampleWindowsRuntimeAndCLR.Winmd"); ITaskItem[] assemblyFiles = new TaskItem[] { taskItem }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.AssemblyFiles = assemblyFiles; t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Single(t.ResolvedFiles); Assert.Empty(t.RelatedFiles); Assert.Empty(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); Assert.Equal("Managed", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFileType)); Assert.Empty(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); Assert.Equal("WindowsRuntime 1.0, CLR V2.0.50727", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); } /// <summary> /// When a project to project reference is passed in we want to verify that /// the winmd references get the correct metadata applied to them /// </summary> [Fact] public void VerifyP2PHaveCorrectMetadataNonWinMD() { // Create the engine. MockEngine engine = new MockEngine(_output); ITaskItem[] assemblyFiles = new TaskItem[] { new TaskItem(@"C:\AssemblyFolder\SomeAssembly.dll") }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.AssemblyFiles = assemblyFiles; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Single(t.ResolvedFiles); Assert.Empty(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); Assert.Empty(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile)); Assert.Equal("v2.0.50727", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); } /// <summary> /// Verify when we reference a winmd file as a reference item make sure we ignore the mscorlib. /// </summary> [Fact] public void IgnoreReferenceToMscorlib() { // Create the engine. MockEngine engine = new MockEngine(_output); ITaskItem[] assemblyFiles = new TaskItem[] { new TaskItem(@"SampleWindowsRuntimeOnly"), new TaskItem(@"SampleWindowsRuntimeAndClr") }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.TargetProcessorArchitecture = "X86"; t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Equal(2, t.ResolvedFiles.Length); Assert.Empty(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); engine.AssertLogDoesntContain("conflict"); } /// <summary> /// Verify when we reference a mixed winmd file that we do resolve the reference to the mscorlib /// </summary> [Fact] public void MixedWinMDGoodReferenceToMscorlib() { // Create the engine. MockEngine engine = new MockEngine(_output); ITaskItem[] assemblyFiles = new TaskItem[] { new TaskItem(@"SampleWindowsRuntimeAndClr") }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Single(t.ResolvedFiles); Assert.Empty(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); engine.AssertLogContainsMessageFromResource(resourceDelegate, "ResolveAssemblyReference.Resolved", @"C:\WinMD\v4\mscorlib.dll"); } /// <summary> /// Verify when a winmd file depends on another winmd file that we do resolve the dependency /// </summary> [Fact] public void WinMdFileDependsOnAnotherWinMDFile() { // Create the engine. MockEngine engine = new MockEngine(_output); ITaskItem[] assemblyFiles = new TaskItem[] { new TaskItem(@"SampleWindowsRuntimeOnly2") }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.TargetProcessorArchitecture = "X86"; t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Single(t.ResolvedFiles); Assert.Single(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); Assert.Equal(@"C:\WinMD\SampleWindowsRuntimeOnly2.winmd", t.ResolvedFiles[0].ItemSpec); Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); Assert.Equal(@"C:\WinMD\SampleWindowsRuntimeOnly.winmd", t.ResolvedDependencyFiles[0].ItemSpec); Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.True(bool.Parse(t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); } /// <summary> /// We have two dlls which depend on a winmd, the first dll does not have the winmd beside it, the second one does /// we want to make sure that the winmd file is resolved beside the second dll. /// </summary> [Fact] public void ResolveWinmdBesideDll() { // Create the engine. MockEngine engine = new MockEngine(_output); ITaskItem[] assemblyFiles = new TaskItem[] { new TaskItem(@"C:\DirectoryContainsOnlyDll\A.dll"), new TaskItem(@"C:\DirectoryContainsdllAndWinmd\B.dll"), }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { "{RAWFILENAME}" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Equal(2, t.ResolvedFiles.Length); Assert.Single(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); Assert.Equal(@"C:\DirectoryContainsdllAndWinmd\C.winmd", t.ResolvedDependencyFiles[0].ItemSpec); } /// <summary> /// We have a winmd file and a dll depend on a winmd, there are copies of the winmd beside each of the files. /// we want to make sure that the winmd file is resolved beside the winmd since that is the first file resolved. /// </summary> [Fact] public void ResolveWinmdBesideDll2() { // Create the engine. MockEngine engine = new MockEngine(_output); ITaskItem[] assemblyFiles = new TaskItem[] { new TaskItem(@"C:\DirectoryContainstwoWinmd\A.winmd"), new TaskItem(@"C:\DirectoryContainsdllAndWinmd\B.dll"), }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { @"{RAWFILENAME}" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Equal(2, t.ResolvedFiles.Length); Assert.Single(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); Assert.Equal(@"C:\DirectoryContainstwoWinmd\C.winmd", t.ResolvedDependencyFiles[0].ItemSpec); } /// <summary> /// Verify when a winmd file depends on another winmd file that itself has framework dependencies that we do not resolve any of the /// dependencies due to the winmd to winmd reference /// </summary> [Fact] public void WinMdFileDependsOnAnotherWinMDFileWithFrameworkDependencies() { // Create the engine. MockEngine engine = new MockEngine(_output); ITaskItem[] assemblyFiles = new TaskItem[] { new TaskItem(@"SampleWindowsRuntimeOnly3") }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { @"{TargetFrameworkDirectory}", @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" }; t.TargetFrameworkDirectories = new string[] { @"c:\WINNT\Microsoft.NET\Framework\v4.0.MyVersion" }; t.TargetProcessorArchitecture = "x86"; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Single(t.ResolvedFiles); Assert.Equal(4, t.ResolvedDependencyFiles.Length); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); Assert.Equal(@"C:\WinMD\SampleWindowsRuntimeOnly3.winmd", t.ResolvedFiles[0].ItemSpec); Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); } /// <summary> /// Make sure when a dot net assembly depends on a WinMDFile that /// we get the winmd file resolved. Also make sure that if there is Implementation, ImageRuntime, or IsWinMD set on the dll that /// it does not get propagated to the winmd file dependency. /// </summary> [Fact] public void DotNetAssemblyDependsOnAWinMDFile() { // Create the engine. MockEngine engine = new MockEngine(_output); TaskItem item = new TaskItem(@"DotNetAssemblyDependsOnWinMD"); // This should not be used for anything, it is recalculated in rar, this is to make sure it is not forwarded to child items. item.SetMetadata(ItemMetadataNames.imageRuntime, "FOO"); // This should not be used for anything, it is recalculated in rar, this is to make sure it is not forwarded to child items. item.SetMetadata(ItemMetadataNames.winMDFile, "NOPE"); item.SetMetadata(ItemMetadataNames.winmdImplmentationFile, "IMPL"); ITaskItem[] assemblyFiles = new TaskItem[] { item }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.TargetProcessorArchitecture = "X86"; t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Single(t.ResolvedFiles); Assert.Single(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); Assert.Equal(@"C:\WinMD\DotNetAssemblyDependsOnWinMD.dll", t.ResolvedFiles[0].ItemSpec); Assert.Equal(@"v2.0.50727", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.Equal("NOPE", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile)); Assert.Equal("IMPL", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); Assert.Equal(@"C:\WinMD\SampleWindowsRuntimeOnly.winmd", t.ResolvedDependencyFiles[0].ItemSpec); Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.True(bool.Parse(t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); Assert.Equal("SampleWindowsRuntimeOnly.dll", t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); } /// <summary> /// Resolve a winmd file which depends on a native implementation dll that has an invalid pe header. /// This will always result in an error since the dll is malformed /// </summary> [Fact] public void ResolveWinmdWithInvalidPENativeDependency() { // Create the engine. MockEngine engine = new MockEngine(_output); TaskItem item = new TaskItem(@"DependsOnInvalidPeHeader"); ITaskItem[] assemblyFiles = new TaskItem[] { item }; ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { @"C:\WinMDArchVerification" }; bool succeeded = Execute(t); // Should fail since PE Header is not valid and this is always an error. Assert.False(succeeded); Assert.Equal(1, engine.Errors); Assert.Equal(0, engine.Warnings); // The original winmd will resolve but its implementation dll must not be there Assert.Single(t.ResolvedFiles); Assert.Empty(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); string invalidPEMessage = ResourceUtilities.GetResourceString("ResolveAssemblyReference.ImplementationDllHasInvalidPEHeader"); string fullMessage = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ResolveAssemblyReference.ProblemReadingImplementationDll", @"C:\WinMDArchVerification\DependsOnInvalidPeHeader.dll", invalidPEMessage); engine.AssertLogContains(fullMessage); } /// <summary> /// Resolve a winmd file which depends a native dll that matches the targeted architecture /// </summary> [Fact] public void ResolveWinmdWithArchitectureDependencyMatchingArchitecturesX86() { // Create the engine. MockEngine engine = new MockEngine(_output); TaskItem item = new TaskItem("DependsOnX86"); ITaskItem[] assemblyFiles = new TaskItem[] { item }; ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { @"C:\WinMDArchVerification" }; t.TargetProcessorArchitecture = "X86"; t.WarnOrErrorOnTargetArchitectureMismatch = "Error"; bool succeeded = Execute(t); Assert.Single(t.ResolvedFiles); Assert.Equal(@"C:\WinMDArchVerification\DependsOnX86.winmd", t.ResolvedFiles[0].ItemSpec); Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); Assert.True(succeeded); Assert.Equal("DependsOnX86.dll", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); } /// <summary> /// Resolve a winmd file which depends a native dll that matches the targeted architecture /// </summary> [Fact] public void ResolveWinmdWithArchitectureDependencyAnyCPUNative() { // Create the engine. MockEngine engine = new MockEngine(_output); // IMAGE_FILE_MACHINE unknown is supposed to work on all machine types TaskItem item = new TaskItem("DependsOnAnyCPUUnknown"); ITaskItem[] assemblyFiles = new TaskItem[] { item }; ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { @"C:\WinMDArchVerification" }; t.TargetProcessorArchitecture = "X86"; t.WarnOrErrorOnTargetArchitectureMismatch = "Error"; bool succeeded = Execute(t); Assert.Single(t.ResolvedFiles); Assert.Equal(@"C:\WinMDArchVerification\DependsOnAnyCPUUnknown.winmd", t.ResolvedFiles[0].ItemSpec); Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); Assert.True(succeeded); Assert.Equal("DependsOnAnyCPUUnknown.dll", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); } /// <summary> /// Resolve a winmd file which depends on a native implementation dll that has an invalid pe header. /// A warning or error is expected in the log depending on the WarnOrErrorOnTargetArchitecture property value. /// </summary> [Fact] public void ResolveWinmdWithArchitectureDependency() { VerifyImplementationArchitecture("DependsOnX86", "MSIL", "X86", "Error"); VerifyImplementationArchitecture("DependsOnX86", "MSIL", "X86", "Warning"); VerifyImplementationArchitecture("DependsOnX86", "MSIL", "X86", "None"); VerifyImplementationArchitecture("DependsOnX86", "AMD64", "X86", "Error"); VerifyImplementationArchitecture("DependsOnX86", "AMD64", "X86", "Warning"); VerifyImplementationArchitecture("DependsOnX86", "AMD64", "X86", "None"); VerifyImplementationArchitecture("DependsOnAmd64", "MSIL", "AMD64", "Error"); VerifyImplementationArchitecture("DependsOnAmd64", "MSIL", "AMD64", "Warning"); VerifyImplementationArchitecture("DependsOnAmd64", "MSIL", "AMD64", "None"); VerifyImplementationArchitecture("DependsOnAmd64", "X86", "AMD64", "Error"); VerifyImplementationArchitecture("DependsOnAmd64", "X86", "AMD64", "Warning"); VerifyImplementationArchitecture("DependsOnAmd64", "X86", "AMD64", "None"); VerifyImplementationArchitecture("DependsOnARM", "MSIL", "ARM", "Error"); VerifyImplementationArchitecture("DependsOnARM", "MSIL", "ARM", "Warning"); VerifyImplementationArchitecture("DependsOnARM", "MSIL", "ARM", "None"); VerifyImplementationArchitecture("DependsOnARMV7", "MSIL", "ARM", "Error"); VerifyImplementationArchitecture("DependsOnARMV7", "MSIL", "ARM", "Warning"); VerifyImplementationArchitecture("DependsOnARMv7", "MSIL", "ARM", "None"); VerifyImplementationArchitecture("DependsOnIA64", "MSIL", "IA64", "Error"); VerifyImplementationArchitecture("DependsOnIA64", "MSIL", "IA64", "Warning"); VerifyImplementationArchitecture("DependsOnIA64", "MSIL", "IA64", "None"); VerifyImplementationArchitecture("DependsOnUnknown", "MSIL", "Unknown", "Error"); VerifyImplementationArchitecture("DependsOnUnknown", "MSIL", "Unknown", "Warning"); VerifyImplementationArchitecture("DependsOnUnknown", "MSIL", "Unknown", "None"); } private void VerifyImplementationArchitecture(string winmdName, string targetProcessorArchitecture, string implementationFileArch, string warnOrErrorOnTargetArchitectureMismatch) { // Create the engine. MockEngine engine = new MockEngine(_output); TaskItem item = new TaskItem(winmdName); ITaskItem[] assemblyFiles = new TaskItem[] { item }; ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { @"C:\WinMDArchVerification" }; t.TargetProcessorArchitecture = targetProcessorArchitecture; t.WarnOrErrorOnTargetArchitectureMismatch = warnOrErrorOnTargetArchitectureMismatch; bool succeeded = Execute(t); Assert.Single(t.ResolvedFiles); Assert.Equal(@"C:\WinMDArchVerification\" + winmdName + ".winmd", t.ResolvedFiles[0].ItemSpec); Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); string fullMessage = null; if (implementationFileArch.Equals("Unknown")) { fullMessage = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ResolveAssemblyReference.UnknownProcessorArchitecture", @"C:\WinMDArchVerification\" + winmdName + ".dll", @"C:\WinMDArchVerification\" + winmdName + ".winmd", NativeMethods.IMAGE_FILE_MACHINE_R4000.ToString("X", CultureInfo.InvariantCulture)); } else { fullMessage = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ResolveAssemblyReference.MismatchBetweenTargetedAndReferencedArchOfImplementation", targetProcessorArchitecture, implementationFileArch, @"C:\WinMDArchVerification\" + winmdName + ".dll", @"C:\WinMDArchVerification\" + winmdName + ".winmd"); } if (warnOrErrorOnTargetArchitectureMismatch.Equals("None", StringComparison.OrdinalIgnoreCase)) { engine.AssertLogDoesntContain(fullMessage); } else { engine.AssertLogContains(fullMessage); } if (warnOrErrorOnTargetArchitectureMismatch.Equals("Warning", StringComparison.OrdinalIgnoreCase)) { // Should fail since PE Header is not valid and this is always an error. Assert.True(succeeded); Assert.Equal(winmdName + ".dll", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); Assert.Equal(0, engine.Errors); Assert.Equal(1, engine.Warnings); } else if (warnOrErrorOnTargetArchitectureMismatch.Equals("Error", StringComparison.OrdinalIgnoreCase)) { // Should fail since PE Header is not valid and this is always an error. Assert.False(succeeded); Assert.Empty(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); Assert.Equal(1, engine.Errors); Assert.Equal(0, engine.Warnings); } else if (warnOrErrorOnTargetArchitectureMismatch.Equals("None", StringComparison.OrdinalIgnoreCase)) { Assert.True(succeeded); Assert.Equal(winmdName + ".dll", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile)); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); } } /// <summary> /// Verify when a winmd file depends on another winmd file that we resolve both and that the metadata is correct. /// </summary> [Fact] public void DotNetAssemblyDependsOnAWinMDFileWithVersion255() { // Create the engine. MockEngine engine = new MockEngine(_output); ITaskItem[] assemblyFiles = new TaskItem[] { new TaskItem(@"DotNetAssemblyDependsOn255WinMD") }; // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); t.BuildEngine = engine; t.Assemblies = assemblyFiles; t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Single(t.ResolvedFiles); Assert.Single(t.ResolvedDependencyFiles); Assert.Equal(0, engine.Errors); Assert.Equal(0, engine.Warnings); Assert.Equal(@"C:\WinMD\DotNetAssemblyDependsOn255WinMD.dll", t.ResolvedFiles[0].ItemSpec); Assert.Equal(@"v2.0.50727", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.Empty(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile)); Assert.Equal(@"C:\WinMD\WinMDWithVersion255.winmd", t.ResolvedDependencyFiles[0].ItemSpec); Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.imageRuntime)); Assert.True(bool.Parse(t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.winMDFile))); } #endregion } }
// // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR // PURPOSE. IT CAN BE DISTRIBUTED FREE OF CHARGE AS LONG AS THIS HEADER // REMAINS UNCHANGED. // SEE http://www.mp3dev.org/ FOR TECHNICAL AND COPYRIGHT INFORMATION REGARDING // LAME PROJECT. // // Email: [email protected] // // Copyright (C) 2002-2003 Idael Cardoso. // // // About Thomson and/or Fraunhofer patents: // Any use of this product does not convey a license under the relevant // intellectual property of Thomson and/or Fraunhofer Gesellschaft nor imply // any right to use this product in any finished end user or ready-to-use final // product. An independent license for such use is required. // For details, please visit http://www.mp3licensing.com. // using System; using System.IO; using Yeti.Lame; using Yeti.MMedia; using WaveLib; namespace Yeti.MMedia.Mp3 { /// <summary> /// Convert PCM audio data to PCM format /// The data received through the method write is assumed as PCM audio data. /// This data is converted to MP3 format and written to the result stream. /// <seealso cref="yeti.mmedia.utils.AudioFileWriter"/> /// <seealso cref="yeti.Lame"/> /// </summary> public class Mp3Writer : AudioWriter { private bool closed = false; private BE_CONFIG m_Mp3Config = null; private uint m_hLameStream = 0; private uint m_InputSamples = 0; private uint m_OutBufferSize = 0; private byte[] m_InBuffer = null; private int m_InBufferPos = 0; private byte[] m_OutBuffer = null; /// <summary> /// Create a Mp3Writer with the default MP3 format /// </summary> /// <param name="Output">Stream that will hold the MP3 resulting data</param> /// <param name="InputDataFormat">PCM format of input data</param> public Mp3Writer(Stream Output, WaveFormat InputDataFormat) :this(Output, InputDataFormat, new BE_CONFIG(InputDataFormat)) { } /// <summary> /// Create a Mp3Writer with specific MP3 format /// </summary> /// <param name="Output">Stream that will hold the MP3 resulting data</param> /// <param name="cfg">Writer Config</param> public Mp3Writer(Stream Output, Mp3WriterConfig cfg) :this(Output, cfg.Format, cfg.Mp3Config) { } /// <summary> /// Create a Mp3Writer with specific MP3 format /// </summary> /// <param name="Output">Stream that will hold the MP3 resulting data</param> /// <param name="InputDataFormat">PCM format of input data</param> /// <param name="Mp3Config">Desired MP3 config</param> public Mp3Writer(Stream Output, WaveFormat InputDataFormat, BE_CONFIG Mp3Config) :base(Output, InputDataFormat) { try { m_Mp3Config = Mp3Config; uint LameResult = Lame_encDll.beInitStream(m_Mp3Config, ref m_InputSamples, ref m_OutBufferSize, ref m_hLameStream); if ( LameResult != Lame_encDll.BE_ERR_SUCCESSFUL) { throw new ApplicationException(string.Format("Lame_encDll.beInitStream failed with the error code {0}", LameResult)); } m_InBuffer = new byte[m_InputSamples*2]; //Input buffer is expected as short[] m_OutBuffer = new byte[m_OutBufferSize]; } catch { base.Close(); throw; } } /// <summary> /// MP3 Config of final data /// </summary> public BE_CONFIG Mp3Config { get { return m_Mp3Config; } } protected override int GetOptimalBufferSize() { return m_InBuffer.Length; } public override void Close() { if (!closed) { try { uint EncodedSize = 0; if ( m_InBufferPos > 0) { if ( Lame_encDll.EncodeChunk(m_hLameStream, m_InBuffer, 0, (uint)m_InBufferPos, m_OutBuffer, ref EncodedSize) == Lame_encDll.BE_ERR_SUCCESSFUL ) { if ( EncodedSize > 0) { base.Write(m_OutBuffer, 0, (int)EncodedSize); } } } EncodedSize = 0; if (Lame_encDll.beDeinitStream(m_hLameStream, m_OutBuffer, ref EncodedSize) == Lame_encDll.BE_ERR_SUCCESSFUL ) { if ( EncodedSize > 0) { base.Write(m_OutBuffer, 0, (int)EncodedSize); } } } finally { Lame_encDll.beCloseStream(m_hLameStream); } } closed = true; base.Close (); } /// <summary> /// Send to the compressor an array of bytes. /// </summary> /// <param name="buffer">Input buffer</param> /// <param name="index">Start position</param> /// <param name="count">Bytes to process. The optimal size, to avoid buffer copy, is a multiple of <see cref="yeti.mmedia.utils.AudioFileWriter.OptimalBufferSize"/></param> public override void Write(byte[] buffer, int index, int count) { int ToCopy = 0; uint EncodedSize = 0; uint LameResult; while (count > 0) { if ( m_InBufferPos > 0 ) { ToCopy = Math.Min(count, m_InBuffer.Length - m_InBufferPos); Buffer.BlockCopy(buffer, index, m_InBuffer, m_InBufferPos, ToCopy); m_InBufferPos += ToCopy; index += ToCopy; count -= ToCopy; if (m_InBufferPos >= m_InBuffer.Length) { m_InBufferPos = 0; if ( (LameResult=Lame_encDll.EncodeChunk(m_hLameStream, m_InBuffer, m_OutBuffer, ref EncodedSize)) == Lame_encDll.BE_ERR_SUCCESSFUL ) { if ( EncodedSize > 0) { base.Write(m_OutBuffer, 0, (int)EncodedSize); } } else { throw new ApplicationException(string.Format("Lame_encDll.EncodeChunk failed with the error code {0}", LameResult)); } } } else { if (count >= m_InBuffer.Length) { if ( (LameResult=Lame_encDll.EncodeChunk(m_hLameStream, buffer, index, (uint)m_InBuffer.Length, m_OutBuffer, ref EncodedSize)) == Lame_encDll.BE_ERR_SUCCESSFUL ) { if ( EncodedSize > 0) { base.Write(m_OutBuffer, 0, (int)EncodedSize); } } else { throw new ApplicationException(string.Format("Lame_encDll.EncodeChunk failed with the error code {0}", LameResult)); } count -= m_InBuffer.Length; index += m_InBuffer.Length; } else { Buffer.BlockCopy(buffer, index, m_InBuffer, 0, count); m_InBufferPos = count; index += count; count = 0; } } } } /// <summary> /// Send to the compressor an array of bytes. /// </summary> /// <param name="buffer">The optimal size, to avoid buffer copy, is a multiple of <see cref="yeti.mmedia.utils.AudioFileWriter.OptimalBufferSize"/></param> public override void Write(byte[] buffer) { this.Write (buffer, 0, buffer.Length); } protected override AudioWriterConfig GetWriterConfig() { return new Mp3WriterConfig(m_InputDataFormat, Mp3Config); } } }
using System; using System.Reflection; using System.Xml; using System.Text; using System.IO; namespace Hydra.Framework.Conversions { // // ********************************************************************** /// <summary> /// Class with helper functions to work with XML. /// </summary> // ********************************************************************** // public class ConvertXml { #region Static Methods // // ********************************************************************** /// <summary> /// Returns attribute with the given name from the element. /// If attribute absent returns empty string. /// </summary> /// <param name="element">element to find attribute for</param> /// <param name="attrName">name of the attribute</param> /// <returns> /// attribute with the given name from the element /// </returns> // ********************************************************************** // static public string GetAttr(XmlElement element, string attrName) { return GetAttr(element, attrName, ""); } // // ********************************************************************** /// <summary> /// Returns attribute with the given name from the element. /// If attribute absent returns defaut value. /// </summary> /// <param name="element">element to find attribute for</param> /// <param name="attrName">name of the attribute</param> /// <param name="defValue">value to return if attribute not found</param> /// <returns> /// attribute with the given name from the element /// </returns> // ********************************************************************** // static public string GetAttr(XmlElement element, string attrName, string defValue) { return (HasAttr(element, attrName)) ? element.Attributes[attrName].Value : defValue; } // // ********************************************************************** /// <summary> /// Returns true if attribute with the given name exists in the element. /// </summary> /// <param name="element">element to find attribute for</param> /// <param name="attrName">name of the attribute</param> /// <returns> /// true if attribute with the given name exists in the element or false otherwise /// </returns> // ********************************************************************** // static public bool HasAttr(XmlElement element, string attrName) { return (element != null && element.Attributes[attrName] != null); } // // ********************************************************************** /// <summary> /// Appends node like <name>text</name> to the parent node. /// </summary> /// <param name="parent">element to add new one</param> /// <param name="name">name of the new node</param> /// <param name="text">text new node should contain</param> /// <returns>created element</returns> // ********************************************************************** // static public XmlElement AppendTextElement(XmlNode parent, string name, string text) { XmlElement element = CreateElement(parent, name); element.InnerText = text; return element; } // // ********************************************************************** /// <summary> /// Reads text from the text node with the given name under parent. /// </summary> /// <param name="parent">node to find the text one</param> /// <param name="name">name of the node to find</param> /// <returns> /// trimmed text of the node with the given name or empty string if such node not found /// </returns> // ********************************************************************** // static public string ReadTextElement(XmlNode parent, string name) { if (parent == null) return ""; XmlNode node = parent.SelectSingleNode(name); return (node != null ? ConvertText.TrimSpace(node.InnerText) : ""); } // // ********************************************************************** /// <summary> /// Creates element with the given tag name under parent. /// </summary> /// <param name="parent">node to create new element under</param> /// <param name="tagName">tag name of the new element</param> /// <returns>created element</returns> // ********************************************************************** // static public XmlElement CreateElement(XmlNode parent, string tagName) { XmlElement element = parent.OwnerDocument.CreateElement(tagName); parent.AppendChild(element); return element; } // // ********************************************************************** /// <summary> /// Returns true if argument is a valid XML node name. /// </summary> /// <param name="name">name to check</param> /// <returns> /// true if argument is a valid XML node name or false otherwise /// </returns> // ********************************************************************** // static public bool IsValidNodeName(string name) { XmlDocument doc = new XmlDocument(); try { doc.CreateElement(name); return true; } catch (XmlException) { return false; } } // // ********************************************************************** /// <summary> /// Creates XML document drom the file. /// </summary> /// <param name="fileName">name of file with XML document</param> /// <returns>loaded document</returns> // ********************************************************************** // static public XmlDocument LoadDocument(string fileName) { XmlDocument doc = new XmlDocument(); doc.Load(fileName); return doc; } // // ********************************************************************** /// <summary> /// Loads the document. /// </summary> /// <param name="fileName">StateName of the file.</param> /// <param name="nSpace">The n space.</param> /// <returns></returns> // ********************************************************************** // static public XmlDocument LoadDocument(string fileName, string nSpace) { XmlDocument doc = new XmlDocument(); doc.Load(fileName); return doc; } // // ********************************************************************** /// <summary> /// Creates XML document from the string. /// </summary> /// <param name="xml">string with XML document</param> /// <returns>loaded document</returns> // ********************************************************************** // static public XmlDocument StringToDoc(string xml) { XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); return doc; } // // ********************************************************************** /// <summary> /// Creates XML document from the byte array. /// </summary> /// <param name="contents">byte array with document contents</param> /// <returns>loaded document</returns> // ********************************************************************** // static public XmlDocument BytesToDoc(byte[] contents) { XmlDocument doc = new XmlDocument(); MemoryStream stream = new MemoryStream(contents); doc.Load(stream); return doc; } // // ********************************************************************** /// <summary> /// Writes XML document to the file. /// </summary> /// <param name="doc">document to write</param> /// <param name="fileName">name of file to write</param> // ********************************************************************** // static public void SaveDocument(XmlDocument doc, string fileName) { StreamWriter fw = new StreamWriter(fileName, false, Encoding.UTF8); WriteDocTo(doc, fw); } // // ********************************************************************** /// <summary> /// Returns document contents as a string. /// </summary> /// <param name="doc">document to convert to string</param> /// <returns>document contents as a string</returns> // ********************************************************************** // static public string DocToString(XmlDocument doc) { StringWriter sw = new StringWriter(); WriteDocTo(doc, sw); return sw.ToString(); } // // ********************************************************************** /// <summary> /// Writes document to the given writer. /// </summary> /// <param name="doc">document to convert to string</param> /// <param name="tw">text writer to write document to</param> /// / // ********************************************************************** // static public void WriteDocTo(XmlDocument doc, TextWriter tw) { XmlTextWriter writer = new XmlTextWriter(tw); writer.Formatting = Formatting.Indented; doc.WriteContentTo(writer); writer.Flush(); writer.Close(); } // // ********************************************************************** /// <summary> /// Deletes all children of node with the given name and parent. /// </summary> /// <param name="parent">parent of node to delete children</param> /// <param name="nodeName">name of node to delete children</param> // ********************************************************************** // static public void DeleteNodeChildren(XmlNode parent, string nodeName) { XmlNode node = parent.SelectSingleNode(nodeName); if (node != null) node.RemoveAll(); } // // ********************************************************************** /// <summary> /// Creates XML document and appends root element. /// </summary> /// <param name="rootName">name of the root element</param> /// <returns>crated document</returns> // ********************************************************************** // static public XmlDocument CreateDocument(string rootName) { XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement(rootName)); return doc; } // // ********************************************************************** /// <summary> /// Adds attributes to the given element. /// </summary> /// <param name="element">element to add attributes</param> /// <param name="attributes">array with attribute names and values /// to add to the script element (even array elements are names and odd ones are values)</param> // ********************************************************************** // static public void AddAttributes(XmlElement element, params string[] attributes) { for (int i = 0; i < attributes.Length / 2; i++) { string name = attributes[i * 2]; string value = attributes[i * 2 + 1]; element.SetAttribute(name, value); } } // // ********************************************************************** /// <summary> /// Loads XML document from resources of the given assembly. /// </summary> /// <param name="assembly">assembly to load from</param> /// <param name="fileName">XML file name to load</param> /// <param name="nameSpace">namespace for the resource (optional)</param> /// <returns> /// XML document object or null, if not found /// </returns> // ********************************************************************** // static public XmlDocument LoadXmlFromResource(Assembly assembly, string fileName, string nameSpace) { XmlDocument doc = null; if (assembly != null) { foreach (string resourceName in assembly.GetManifestResourceNames()) { bool isFound; if (ConvertUtils.NotEmpty(nameSpace)) { isFound = string.Equals(resourceName, nameSpace + "." + fileName, StringComparison.OrdinalIgnoreCase); } else { isFound = resourceName.ToUpper().EndsWith(fileName.ToUpper()); } if (isFound) { doc = new XmlDocument(); Stream xmlStream = assembly.GetManifestResourceStream(resourceName); XmlTextReader reader = new XmlTextReader(xmlStream); doc.Load(reader); break; } } } return doc; } // // ********************************************************************** /// <summary> /// Loads XML document from resources of the given assembly. /// </summary> /// <param name="assembly">assembly to load from</param> /// <param name="fileName">XML file name to load</param> /// <returns> /// XML document object or null, if not found /// </returns> // ********************************************************************** // static public XmlDocument LoadXmlFromResource(Assembly assembly, string fileName) { return LoadXmlFromResource(assembly, fileName, null); } // // ********************************************************************** /// <summary> /// Combines the given xml documents into one document. /// Does not include root nodes. /// </summary> /// <param name="documents">documents to be combined</param> /// <returns> /// an XML document that contains all the content /// of the given documents (except root nodes) /// </returns> // ********************************************************************** // static public XmlDocument Combine(XmlDocument[] documents) { XmlDocument resultDocument = new XmlDocument(); resultDocument.AppendChild(resultDocument.CreateNode(XmlNodeType.Element, "Root", "")); foreach (XmlDocument document in documents) foreach (XmlNode node in document.DocumentElement.ChildNodes) resultDocument.DocumentElement.AppendChild(resultDocument.ImportNode(node, true)); return resultDocument; } // // ********************************************************************** /// <summary> /// Returns true if the given node contains some child XML elements (not text or cdata values). /// </summary> /// <param name="node">a node to perform check on</param> /// <returns> /// true if the given node contains some child XML elements /// </returns> // ********************************************************************** // static public bool HasChildXmlElements(XmlNode node) { foreach (XmlNode childNode in node) if (childNode.NodeType == XmlNodeType.Element) return true; return false; } #endregion } }
using System; using NUnit.Framework; using Org.BouncyCastle.Asn1.Nist; using Org.BouncyCastle.Asn1.Sec; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Math; using Org.BouncyCastle.Math.EC; using Org.BouncyCastle.Security; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Agreement; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Signers; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Crypto.Tests { /** * ECDSA tests are taken from X9.62. */ [TestFixture] public class ECTest : SimpleTest { /** * X9.62 - 1998,<br/> * J.3.1, Page 152, ECDSA over the field Fp<br/> * an example with 192 bit prime */ [Test] public void TestECDsa192bitPrime() { BigInteger r = new BigInteger("3342403536405981729393488334694600415596881826869351677613"); BigInteger s = new BigInteger("5735822328888155254683894997897571951568553642892029982342"); byte[] kData = BigIntegers.AsUnsignedByteArray(new BigInteger("6140507067065001063065065565667405560006161556565665656654")); SecureRandom k = FixedSecureRandom.From(kData); FpCurve curve = new FpCurve( new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b ECDomainParameters parameters = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G new BigInteger("6277101735386680763835789423176059013767194773182842284081")); // n ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( "ECDSA", new BigInteger("651056770906015076056810763456358567190100156695615665659"), // d parameters); ParametersWithRandom param = new ParametersWithRandom(priKey, k); ECDsaSigner ecdsa = new ECDsaSigner(); ecdsa.Init(true, param); byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray(); BigInteger[] sig = ecdsa.GenerateSignature(message); if (!r.Equals(sig[0])) { Fail("r component wrong." + SimpleTest.NewLine + " expecting: " + r + SimpleTest.NewLine + " got : " + sig[0]); } if (!s.Equals(sig[1])) { Fail("s component wrong." + SimpleTest.NewLine + " expecting: " + s + SimpleTest.NewLine + " got : " + sig[1]); } // Verify the signature ECPublicKeyParameters pubKey = new ECPublicKeyParameters( "ECDSA", curve.DecodePoint(Hex.Decode("0262b12d60690cdcf330babab6e69763b471f994dd702d16a5")), // Q parameters); ecdsa.Init(false, pubKey); if (!ecdsa.VerifySignature(message, sig[0], sig[1])) { Fail("verification fails"); } } [Test] public void TestDecode() { FpCurve curve = new FpCurve( new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b ECPoint p = curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")); if (!p.X.ToBigInteger().Equals(new BigInteger("188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012", 16))) { Fail("x uncompressed incorrectly"); } if (!p.Y.ToBigInteger().Equals(new BigInteger("7192b95ffc8da78631011ed6b24cdd573f977a11e794811", 16))) { Fail("y uncompressed incorrectly"); } byte[] encoding = p.GetEncoded(); if (!AreEqual(encoding, Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012"))) { Fail("point compressed incorrectly"); } } /** * X9.62 - 1998,<br/> * J.3.2, Page 155, ECDSA over the field Fp<br/> * an example with 239 bit prime */ [Test] public void TestECDsa239bitPrime() { BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176"); BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783"); byte[] kData = BigIntegers.AsUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = FixedSecureRandom.From(kData); FpCurve curve = new FpCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters parameters = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( "ECDSA", new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d parameters); ECDsaSigner ecdsa = new ECDsaSigner(); ParametersWithRandom param = new ParametersWithRandom(priKey, k); ecdsa.Init(true, param); byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray(); BigInteger[] sig = ecdsa.GenerateSignature(message); if (!r.Equals(sig[0])) { Fail("r component wrong." + SimpleTest.NewLine + " expecting: " + r + SimpleTest.NewLine + " got : " + sig[0]); } if (!s.Equals(sig[1])) { Fail("s component wrong." + SimpleTest.NewLine + " expecting: " + s + SimpleTest.NewLine + " got : " + sig[1]); } // Verify the signature ECPublicKeyParameters pubKey = new ECPublicKeyParameters( "ECDSA", curve.DecodePoint(Hex.Decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q parameters); ecdsa.Init(false, pubKey); if (!ecdsa.VerifySignature(message, sig[0], sig[1])) { Fail("signature fails"); } } /** * X9.62 - 1998,<br/> * J.2.1, Page 100, ECDSA over the field F2m<br/> * an example with 191 bit binary field */ [Test] public void TestECDsa191bitBinary() { BigInteger r = new BigInteger("87194383164871543355722284926904419997237591535066528048"); BigInteger s = new BigInteger("308992691965804947361541664549085895292153777025772063598"); byte[] kData = BigIntegers.AsUnsignedByteArray(new BigInteger("1542725565216523985789236956265265265235675811949404040041")); SecureRandom k = FixedSecureRandom.From(kData); F2mCurve curve = new F2mCurve( 191, // m 9, //k new BigInteger("2866537B676752636A68F56554E12640276B649EF7526267", 16), // a new BigInteger("2E45EF571F00786F67B0081B9495A3D95462F5DE0AA185EC", 16)); // b ECDomainParameters parameters = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("0436B3DAF8A23206F9C4F299D7B21A9C369137F2C84AE1AA0D765BE73433B3F95E332932E70EA245CA2418EA0EF98018FB")), // G new BigInteger("1569275433846670190958947355803350458831205595451630533029"), // n BigInteger.Two); // h ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( "ECDSA", new BigInteger("1275552191113212300012030439187146164646146646466749494799"), // d parameters); ECDsaSigner ecdsa = new ECDsaSigner(); ParametersWithRandom param = new ParametersWithRandom(priKey, k); ecdsa.Init(true, param); byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray(); BigInteger[] sig = ecdsa.GenerateSignature(message); if (!r.Equals(sig[0])) { Fail("r component wrong." + SimpleTest.NewLine + " expecting: " + r + SimpleTest.NewLine + " got : " + sig[0]); } if (!s.Equals(sig[1])) { Fail("s component wrong." + SimpleTest.NewLine + " expecting: " + s + SimpleTest.NewLine + " got : " + sig[1]); } // Verify the signature ECPublicKeyParameters pubKey = new ECPublicKeyParameters( "ECDSA", curve.DecodePoint(Hex.Decode("045DE37E756BD55D72E3768CB396FFEB962614DEA4CE28A2E755C0E0E02F5FB132CAF416EF85B229BBB8E1352003125BA1")), // Q parameters); ecdsa.Init(false, pubKey); if (!ecdsa.VerifySignature(message, sig[0], sig[1])) { Fail("signature fails"); } } /** * X9.62 - 1998,<br/> * J.2.1, Page 100, ECDSA over the field F2m<br/> * an example with 191 bit binary field */ [Test] public void TestECDsa239bitBinary() { BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552"); BigInteger s = new BigInteger("197030374000731686738334997654997227052849804072198819102649413465737174"); byte[] kData = BigIntegers.AsUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = FixedSecureRandom.From(kData); F2mCurve curve = new F2mCurve( 239, // m 36, //k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECDomainParameters parameters = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.ValueOf(4)); // h ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( "ECDSA", new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d parameters); ECDsaSigner ecdsa = new ECDsaSigner(); ParametersWithRandom param = new ParametersWithRandom(priKey, k); ecdsa.Init(true, param); byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray(); BigInteger[] sig = ecdsa.GenerateSignature(message); if (!r.Equals(sig[0])) { Fail("r component wrong." + SimpleTest.NewLine + " expecting: " + r + SimpleTest.NewLine + " got : " + sig[0]); } if (!s.Equals(sig[1])) { Fail("s component wrong." + SimpleTest.NewLine + " expecting: " + s + SimpleTest.NewLine + " got : " + sig[1]); } // Verify the signature ECPublicKeyParameters pubKey = new ECPublicKeyParameters( "ECDSA", curve.DecodePoint(Hex.Decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q parameters); ecdsa.Init(false, pubKey); if (!ecdsa.VerifySignature(message, sig[0], sig[1])) { Fail("signature fails"); } } // L 4.1 X9.62 2005 [Test] public void TestECDsaP224Sha224() { X9ECParameters p = NistNamedCurves.GetByName("P-224"); ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H); ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( new BigInteger("6081831502424510080126737029209236539191290354021104541805484120491"), // d parameters); SecureRandom k = FixedSecureRandom.From(BigIntegers.AsUnsignedByteArray(new BigInteger("15456715103636396133226117016818339719732885723579037388121116732601"))); byte[] M = Hex.Decode("8797A3C693CC292441039A4E6BAB7387F3B4F2A63D00ED384B378C79"); ECDsaSigner dsa = new ECDsaSigner(); dsa.Init(true, new ParametersWithRandom(priKey, k)); BigInteger[] sig = dsa.GenerateSignature(M); BigInteger r = new BigInteger("26477406756127720855365980332052585411804331993436302005017227573742"); BigInteger s = new BigInteger("17694958233103667059888193972742186995283044672015112738919822429978"); if (!r.Equals(sig[0])) { Fail("r component wrong." + SimpleTest.NewLine + " expecting: " + r + SimpleTest.NewLine + " got : " + sig[0]); } if (!s.Equals(sig[1])) { Fail("s component wrong." + SimpleTest.NewLine + " expecting: " + s + SimpleTest.NewLine + " got : " + sig[1]); } // Verify the signature ECPublicKeyParameters pubKey = new ECPublicKeyParameters( parameters.Curve.DecodePoint(Hex.Decode("03FD44EC11F9D43D9D23B1E1D1C9ED6519B40ECF0C79F48CF476CC43F1")), // Q parameters); dsa.Init(false, pubKey); if (!dsa.VerifySignature(M, sig[0], sig[1])) { Fail("signature fails"); } } [Test] public void TestECDsaSecP224k1Sha256() { X9ECParameters p = SecNamedCurves.GetByName("secp224k1"); ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H); ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( new BigInteger("BE6F6E91FE96840A6518B56F3FE21689903A64FA729057AB872A9F51", 16), // d parameters); SecureRandom k = FixedSecureRandom.From(Hex.Decode("00c39beac93db21c3266084429eb9b846b787c094f23a4de66447efbb3")); byte[] M = Hex.Decode("E5D5A7ADF73C5476FAEE93A2C76CE94DC0557DB04CDC189504779117920B896D"); ECDsaSigner dsa = new ECDsaSigner(); dsa.Init(true, new ParametersWithRandom(priKey, k)); BigInteger[] sig = dsa.GenerateSignature(M); BigInteger r = new BigInteger("8163E5941BED41DA441B33E653C632A55A110893133351E20CE7CB75", 16); BigInteger s = new BigInteger("D12C3FC289DDD5F6890DCE26B65792C8C50E68BF551D617D47DF15A8", 16); if (!r.Equals(sig[0])) { Fail("r component wrong." + SimpleTest.NewLine + " expecting: " + r + SimpleTest.NewLine + " got : " + sig[0]); } if (!s.Equals(sig[1])) { Fail("s component wrong." + SimpleTest.NewLine + " expecting: " + s + SimpleTest.NewLine + " got : " + sig[1]); } // Verify the signature ECPublicKeyParameters pubKey = new ECPublicKeyParameters( parameters.Curve.DecodePoint(Hex.Decode("04C5C9B38D3603FCCD6994CBB9594E152B658721E483669BB42728520F484B537647EC816E58A8284D3B89DFEDB173AFDC214ECA95A836FA7C")), // Q parameters); dsa.Init(false, pubKey); if (!dsa.VerifySignature(M, sig[0], sig[1])) { Fail("signature fails"); } } // L4.2 X9.62 2005 [Test] public void TestECDsaP256Sha256() { X9ECParameters p = NistNamedCurves.GetByName("P-256"); ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H); ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( new BigInteger("20186677036482506117540275567393538695075300175221296989956723148347484984008"), // d parameters); SecureRandom k = FixedSecureRandom.From(BigIntegers.AsUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))); byte[] M = Hex.Decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); ECDsaSigner dsa = new ECDsaSigner(); dsa.Init(true, new ParametersWithRandom(priKey, k)); BigInteger[] sig = dsa.GenerateSignature(M); BigInteger r = new BigInteger("97354732615802252173078420023658453040116611318111190383344590814578738210384"); BigInteger s = new BigInteger("98506158880355671805367324764306888225238061309262649376965428126566081727535"); if (!r.Equals(sig[0])) { Fail("r component wrong." + SimpleTest.NewLine + " expecting: " + r + SimpleTest.NewLine + " got : " + sig[0]); } if (!s.Equals(sig[1])) { Fail("s component wrong." + SimpleTest.NewLine + " expecting: " + s + SimpleTest.NewLine + " got : " + sig[1]); } // Verify the signature ECPublicKeyParameters pubKey = new ECPublicKeyParameters( parameters.Curve.DecodePoint(Hex.Decode("03596375E6CE57E0F20294FC46BDFCFD19A39F8161B58695B3EC5B3D16427C274D")), // Q parameters); dsa.Init(false, pubKey); if (!dsa.VerifySignature(M, sig[0], sig[1])) { Fail("signature fails"); } } [Test] public void TestECDsaP224OneByteOver() { X9ECParameters p = NistNamedCurves.GetByName("P-224"); ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H); ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( new BigInteger("6081831502424510080126737029209236539191290354021104541805484120491"), // d parameters); SecureRandom k = FixedSecureRandom.From(BigIntegers.AsUnsignedByteArray(new BigInteger("15456715103636396133226117016818339719732885723579037388121116732601"))); byte[] M = Hex.Decode("8797A3C693CC292441039A4E6BAB7387F3B4F2A63D00ED384B378C79FF"); ECDsaSigner dsa = new ECDsaSigner(); dsa.Init(true, new ParametersWithRandom(priKey, k)); BigInteger[] sig = dsa.GenerateSignature(M); BigInteger r = new BigInteger("26477406756127720855365980332052585411804331993436302005017227573742"); BigInteger s = new BigInteger("17694958233103667059888193972742186995283044672015112738919822429978"); if (!r.Equals(sig[0])) { Fail("r component wrong." + SimpleTest.NewLine + " expecting: " + r + SimpleTest.NewLine + " got : " + sig[0]); } if (!s.Equals(sig[1])) { Fail("s component wrong." + SimpleTest.NewLine + " expecting: " + s + SimpleTest.NewLine + " got : " + sig[1]); } // Verify the signature ECPublicKeyParameters pubKey = new ECPublicKeyParameters( parameters.Curve.DecodePoint(Hex.Decode("03FD44EC11F9D43D9D23B1E1D1C9ED6519B40ECF0C79F48CF476CC43F1")), // Q parameters); dsa.Init(false, pubKey); if (!dsa.VerifySignature(M, sig[0], sig[1])) { Fail("signature fails"); } } // L4.3 X9.62 2005 [Test] public void TestECDsaP521Sha512() { X9ECParameters p = NistNamedCurves.GetByName("P-521"); ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H); ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( new BigInteger("617573726813476282316253885608633222275541026607493641741273231656161177732180358888434629562647985511298272498852936680947729040673640492310550142822667389"), // d parameters); SecureRandom k = FixedSecureRandom.From(BigIntegers.AsUnsignedByteArray(new BigInteger("6806532878215503520845109818432174847616958675335397773700324097584974639728725689481598054743894544060040710846048585856076812050552869216017728862957612913"))); byte[] M = Hex.Decode("6893B64BD3A9615C39C3E62DDD269C2BAAF1D85915526083183CE14C2E883B48B193607C1ED871852C9DF9C3147B574DC1526C55DE1FE263A676346A20028A66"); ECDsaSigner dsa = new ECDsaSigner(); dsa.Init(true, new ParametersWithRandom(priKey, k)); BigInteger[] sig = dsa.GenerateSignature(M); BigInteger r = new BigInteger("1368926195812127407956140744722257403535864168182534321188553460365652865686040549247096155740756318290773648848859639978618869784291633651685766829574104630"); BigInteger s = new BigInteger("1624754720348883715608122151214003032398685415003935734485445999065609979304811509538477657407457976246218976767156629169821116579317401249024208611945405790"); if (!r.Equals(sig[0])) { Fail("r component wrong." + SimpleTest.NewLine + " expecting: " + r + SimpleTest.NewLine + " got : " + sig[0]); } if (!s.Equals(sig[1])) { Fail("s component wrong." + SimpleTest.NewLine + " expecting: " + s + SimpleTest.NewLine + " got : " + sig[1]); } // Verify the signature ECPublicKeyParameters pubKey = new ECPublicKeyParameters( parameters.Curve.DecodePoint(Hex.Decode("020145E221AB9F71C5FE740D8D2B94939A09E2816E2167A7D058125A06A80C014F553E8D6764B048FB6F2B687CEC72F39738F223D4CE6AFCBFF2E34774AA5D3C342CB3")), // Q parameters); dsa.Init(false, pubKey); if (!dsa.VerifySignature(M, sig[0], sig[1])) { Fail("signature fails"); } } /** * General test for long digest. */ [Test] public void TestECDsa239bitBinaryAndLargeDigest() { BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552"); BigInteger s = new BigInteger("144940322424411242416373536877786566515839911620497068645600824084578597"); byte[] kData = BigIntegers.AsUnsignedByteArray( new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = FixedSecureRandom.From(kData); F2mCurve curve = new F2mCurve( 239, // m 36, //k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECDomainParameters parameters = new ECDomainParameters( curve, curve.DecodePoint( Hex.Decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.ValueOf(4)); // h ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( "ECDSA", new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d parameters); ECDsaSigner ecdsa = new ECDsaSigner(); ParametersWithRandom param = new ParametersWithRandom(priKey, k); ecdsa.Init(true, param); byte[] message = new BigInteger("968236873715988614170569073515315707566766479517968236873715988614170569073515315707566766479517968236873715988614170569073515315707566766479517").ToByteArray(); BigInteger[] sig = ecdsa.GenerateSignature(message); if (!r.Equals(sig[0])) { Fail("r component wrong." + SimpleTest.NewLine + " expecting: " + r + SimpleTest.NewLine + " got : " + sig[0]); } if (!s.Equals(sig[1])) { Fail("s component wrong." + SimpleTest.NewLine + " expecting: " + s + SimpleTest.NewLine + " got : " + sig[1]); } // Verify the signature ECPublicKeyParameters pubKey = new ECPublicKeyParameters( "ECDSA", curve.DecodePoint( Hex.Decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q parameters); ecdsa.Init(false, pubKey); if (!ecdsa.VerifySignature(message, sig[0], sig[1])) { Fail("signature fails"); } } /** * key generation test */ [Test] public void TestECDsaKeyGenTest() { SecureRandom random = new SecureRandom(); FpCurve curve = new FpCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters parameters = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECKeyPairGenerator pGen = new ECKeyPairGenerator(); ECKeyGenerationParameters genParam = new ECKeyGenerationParameters( parameters, random); pGen.Init(genParam); AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair(); ParametersWithRandom param = new ParametersWithRandom(pair.Private, random); ECDsaSigner ecdsa = new ECDsaSigner(); ecdsa.Init(true, param); byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray(); BigInteger[] sig = ecdsa.GenerateSignature(message); ecdsa.Init(false, pair.Public); if (!ecdsa.VerifySignature(message, sig[0], sig[1])) { Fail("signature fails"); } } /** * Basic Key Agreement Test */ [Test] public void TestECBasicAgreementTest() { SecureRandom random = new SecureRandom(); FpCurve curve = new FpCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters parameters = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECKeyPairGenerator pGen = new ECKeyPairGenerator(); ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(parameters, random); pGen.Init(genParam); AsymmetricCipherKeyPair p1 = pGen.GenerateKeyPair(); AsymmetricCipherKeyPair p2 = pGen.GenerateKeyPair(); // // two way // IBasicAgreement e1 = new ECDHBasicAgreement(); IBasicAgreement e2 = new ECDHBasicAgreement(); e1.Init(p1.Private); e2.Init(p2.Private); BigInteger k1 = e1.CalculateAgreement(p2.Public); BigInteger k2 = e2.CalculateAgreement(p1.Public); if (!k1.Equals(k2)) { Fail("calculated agreement test failed"); } // // two way // e1 = new ECDHCBasicAgreement(); e2 = new ECDHCBasicAgreement(); e1.Init(p1.Private); e2.Init(p2.Private); k1 = e1.CalculateAgreement(p2.Public); k2 = e2.CalculateAgreement(p1.Public); if (!k1.Equals(k2)) { Fail("calculated agreement test failed"); } } [Test] public void TestECMqvTestVector1() { // Test Vector from GEC-2 X9ECParameters x9 = SecNamedCurves.GetByName("secp160r1"); ECDomainParameters p = new ECDomainParameters( x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); AsymmetricCipherKeyPair U1 = new AsymmetricCipherKeyPair( new ECPublicKeyParameters( p.Curve.DecodePoint(Hex.Decode("0251B4496FECC406ED0E75A24A3C03206251419DC0")), p), new ECPrivateKeyParameters( new BigInteger("AA374FFC3CE144E6B073307972CB6D57B2A4E982", 16), p)); AsymmetricCipherKeyPair U2 = new AsymmetricCipherKeyPair( new ECPublicKeyParameters( p.Curve.DecodePoint(Hex.Decode("03D99CE4D8BF52FA20BD21A962C6556B0F71F4CA1F")), p), new ECPrivateKeyParameters( new BigInteger("149EC7EA3A220A887619B3F9E5B4CA51C7D1779C", 16), p)); AsymmetricCipherKeyPair V1 = new AsymmetricCipherKeyPair( new ECPublicKeyParameters( p.Curve.DecodePoint(Hex.Decode("0349B41E0E9C0369C2328739D90F63D56707C6E5BC")), p), new ECPrivateKeyParameters( new BigInteger("45FB58A92A17AD4B15101C66E74F277E2B460866", 16), p)); AsymmetricCipherKeyPair V2 = new AsymmetricCipherKeyPair( new ECPublicKeyParameters( p.Curve.DecodePoint(Hex.Decode("02706E5D6E1F640C6E9C804E75DBC14521B1E5F3B5")), p), new ECPrivateKeyParameters( new BigInteger("18C13FCED9EADF884F7C595C8CB565DEFD0CB41E", 16), p)); BigInteger x = calculateAgreement(U1, U2, V1, V2); if (x == null || !x.Equals(new BigInteger("5A6955CEFDB4E43255FB7FCF718611E4DF8E05AC", 16))) { Fail("MQV Test Vector #1 agreement failed"); } } [Test] public void TestECMqvTestVector2() { // Test Vector from GEC-2 X9ECParameters x9 = SecNamedCurves.GetByName("sect163k1"); ECDomainParameters p = new ECDomainParameters( x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); AsymmetricCipherKeyPair U1 = new AsymmetricCipherKeyPair( new ECPublicKeyParameters( p.Curve.DecodePoint(Hex.Decode("03037D529FA37E42195F10111127FFB2BB38644806BC")), p), new ECPrivateKeyParameters( new BigInteger("03A41434AA99C2EF40C8495B2ED9739CB2155A1E0D", 16), p)); AsymmetricCipherKeyPair U2 = new AsymmetricCipherKeyPair( new ECPublicKeyParameters( p.Curve.DecodePoint(Hex.Decode("02015198E74BC2F1E5C9A62B80248DF0D62B9ADF8429")), p), new ECPrivateKeyParameters( new BigInteger("032FC4C61A8211E6A7C4B8B0C03CF35F7CF20DBD52", 16), p)); AsymmetricCipherKeyPair V1 = new AsymmetricCipherKeyPair( new ECPublicKeyParameters( p.Curve.DecodePoint(Hex.Decode("03072783FAAB9549002B4F13140B88132D1C75B3886C")), p), new ECPrivateKeyParameters( new BigInteger("57E8A78E842BF4ACD5C315AA0569DB1703541D96", 16), p)); AsymmetricCipherKeyPair V2 = new AsymmetricCipherKeyPair( new ECPublicKeyParameters( p.Curve.DecodePoint(Hex.Decode("03067E3AEA3510D69E8EDD19CB2A703DDC6CF5E56E32")), p), new ECPrivateKeyParameters( new BigInteger("02BD198B83A667A8D908EA1E6F90FD5C6D695DE94F", 16), p)); BigInteger x = calculateAgreement(U1, U2, V1, V2); if (x == null || !x.Equals(new BigInteger("038359FFD30C0D5FC1E6154F483B73D43E5CF2B503", 16))) { Fail("MQV Test Vector #2 agreement failed"); } } [Test] public void TestECMqvRandom() { SecureRandom random = new SecureRandom(); FpCurve curve = new FpCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters parameters = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECKeyPairGenerator pGen = new ECKeyPairGenerator(); pGen.Init(new ECKeyGenerationParameters(parameters, random)); // Pre-established key pairs AsymmetricCipherKeyPair U1 = pGen.GenerateKeyPair(); AsymmetricCipherKeyPair V1 = pGen.GenerateKeyPair(); // Ephemeral key pairs AsymmetricCipherKeyPair U2 = pGen.GenerateKeyPair(); AsymmetricCipherKeyPair V2 = pGen.GenerateKeyPair(); BigInteger x = calculateAgreement(U1, U2, V1, V2); if (x == null) { Fail("MQV Test Vector (random) agreement failed"); } } private static BigInteger calculateAgreement( AsymmetricCipherKeyPair U1, AsymmetricCipherKeyPair U2, AsymmetricCipherKeyPair V1, AsymmetricCipherKeyPair V2) { ECMqvBasicAgreement u = new ECMqvBasicAgreement(); u.Init(new MqvPrivateParameters( (ECPrivateKeyParameters)U1.Private, (ECPrivateKeyParameters)U2.Private, (ECPublicKeyParameters)U2.Public)); BigInteger ux = u.CalculateAgreement(new MqvPublicParameters( (ECPublicKeyParameters)V1.Public, (ECPublicKeyParameters)V2.Public)); ECMqvBasicAgreement v = new ECMqvBasicAgreement(); v.Init(new MqvPrivateParameters( (ECPrivateKeyParameters)V1.Private, (ECPrivateKeyParameters)V2.Private, (ECPublicKeyParameters)V2.Public)); BigInteger vx = v.CalculateAgreement(new MqvPublicParameters( (ECPublicKeyParameters)U1.Public, (ECPublicKeyParameters)U2.Public)); if (ux.Equals(vx)) return ux; return null; } public override string Name { get { return "EC"; } } public override void PerformTest() { TestDecode(); TestECDsa192bitPrime(); TestECDsa239bitPrime(); TestECDsa191bitBinary(); TestECDsa239bitBinary(); TestECDsaKeyGenTest(); TestECBasicAgreementTest(); TestECDsaP224Sha224(); TestECDsaP224OneByteOver(); TestECDsaP256Sha256(); TestECDsaP521Sha512(); TestECDsaSecP224k1Sha256(); TestECDsa239bitBinaryAndLargeDigest(); TestECMqvTestVector1(); TestECMqvTestVector2(); TestECMqvRandom(); } public static void Main( string[] args) { RunTest(new ECTest()); } } }
using System.Diagnostics; namespace System.Threading.Atomics { /// <summary> /// An <see cref="int"/> value wrapper with atomic operations /// </summary> [DebuggerDisplay("{Value}")] #pragma warning disable 0659, 0661 public sealed class AtomicInteger : IAtomic<int>, IEquatable<int> #pragma warning restore 0659, 0661 { private volatile MemoryOrder _order; // making volatile to prohibit reordering in constructors private int _value; private volatile object _instanceLock; /// <summary> /// Creates new instance of <see cref="AtomicInteger"/> /// </summary> /// <param name="order">Affects the way store operation occur. Default is <see cref="MemoryOrder.AcqRel"/> semantics</param> public AtomicInteger(MemoryOrder order = MemoryOrder.AcqRel) { if (!order.IsSpported()) throw new ArgumentException(string.Format("{0} is not supported", order)); if (order == MemoryOrder.SeqCst) _instanceLock = new object(); _order = order; } /// <summary> /// Creates new instance of <see cref="AtomicInteger"/> /// </summary> /// <param name="value">The value to store</param> /// <param name="order">Affects the way store operation occur. Load operations are always use <see cref="MemoryOrder.Acquire"/> semantics</param> public AtomicInteger(int value, MemoryOrder order = MemoryOrder.AcqRel) { if (!order.IsSpported()) throw new ArgumentException(string.Format("{0} is not supported", order)); if (order == MemoryOrder.SeqCst) _instanceLock = new object(); _order = order; this.Value = value; } /// <summary> /// Gets or sets atomically the underlying value /// </summary> public int Value { get { if (_order != MemoryOrder.SeqCst) return Volatile.Read(ref _value); lock (_instanceLock) { return Volatile.Read(ref _value); } } set { if (_order == MemoryOrder.SeqCst) { lock (_instanceLock) { Interlocked.Exchange(ref _value, value); // for processors cache coherence } } else if (_order.IsAcquireRelease()) { // should use compare_exchange_weak // but implementing CAS using compare_exchange_strong since we are on .NET int currentValue = this._value; int tempValue; do { tempValue = Interlocked.CompareExchange(ref this._value, value, currentValue); } while (tempValue != currentValue); } } } /// <summary> /// Increments the <see cref="AtomicInteger"/> operand by one. /// </summary> /// <param name="atomicInteger">The value to increment.</param> /// <returns>The value of <paramref name="atomicInteger"/> incremented by 1.</returns> public static AtomicInteger operator ++(AtomicInteger atomicInteger) { return Interlocked.Increment(ref atomicInteger._value); } /// <summary> /// Decrements the <see cref="AtomicInteger"/> operand by one. /// </summary> /// <param name="atomicInteger">The value to decrement.</param> /// <returns>The value of <paramref name="atomicInteger"/> decremented by 1.</returns> public static AtomicInteger operator --(AtomicInteger atomicInteger) { return Interlocked.Decrement(ref atomicInteger._value); } /// <summary> /// Adds specified <paramref name="value"/> to <see cref="AtomicInteger"/> and returns the result as a <see cref="int"/>. /// </summary> /// <param name="atomicInteger">The <paramref name="atomicInteger"/> used for addition.</param> /// <param name="value">The value to add</param> /// <returns>The result of adding value to <paramref name="atomicInteger"/></returns> public static int operator +(AtomicInteger atomicInteger, int value) { return Interlocked.Add(ref atomicInteger._value, value); } /// <summary> /// Subtracts <paramref name="value"/> from <paramref name="atomicInteger"/> and returns the result as a <see cref="int"/>. /// </summary> /// <param name="atomicInteger">The <paramref name="atomicInteger"/> from which <paramref name="value"/> is subtracted.</param> /// <param name="value">The value to subtract from <paramref name="atomicInteger"/></param> /// <returns>The result of subtracting value from <see cref="AtomicInteger"/></returns> public static int operator -(AtomicInteger atomicInteger, int value) { return Interlocked.Add(ref atomicInteger._value, -value); } /// <summary> /// Multiplies <see cref="AtomicInteger"/> by specified <paramref name="value"/> and returns the result as a <see cref="int"/>. /// </summary> /// <param name="atomicInteger">The <see cref="AtomicInteger"/> to multiply.</param> /// <param name="value">The value to multiply</param> /// <returns>The result of multiplying <see cref="AtomicInteger"/> and <paramref name="value"/></returns> public static int operator *(AtomicInteger atomicInteger, int value) { bool entered = false; int currentValue = atomicInteger.Value; if (atomicInteger._order == MemoryOrder.SeqCst) { Monitor.Enter(atomicInteger._instanceLock, ref entered); } int result = currentValue * value; try { int tempValue; do { tempValue = Interlocked.CompareExchange(ref atomicInteger._value, result, currentValue); } while (tempValue != currentValue); } finally { if (entered) Monitor.Exit(atomicInteger._instanceLock); } return result; } /// <summary> /// Divides the specified <see cref="AtomicInteger"/> by the specified <paramref name="value"/> and returns the resulting as <see cref="int"/>. /// </summary> /// <param name="atomicInteger">The <see cref="AtomicInteger"/> to divide</param> /// <param name="value">The value by which <paramref name="atomicInteger"/> will be divided.</param> /// <returns>The result of dividing <paramref name="atomicInteger"/> by <paramref name="value"/>.</returns> public static int operator /(AtomicInteger atomicInteger, int value) { if (value == 0) throw new DivideByZeroException(); bool entered = false; int currentValue = atomicInteger.Value; if (atomicInteger._order == MemoryOrder.SeqCst) { Monitor.Enter(atomicInteger._instanceLock, ref entered); } int result = currentValue / value; try { int tempValue; do { tempValue = Interlocked.CompareExchange(ref atomicInteger._value, result, currentValue); } while (tempValue != currentValue); } finally { if (entered) Monitor.Exit(atomicInteger._instanceLock); } return result; } /// <summary> /// Defines an implicit conversion of a <see cref="AtomicInteger"/> to a 32-bit signed integer. /// </summary> /// <param name="atomicInteger">The <see cref="AtomicInteger"/> to convert.</param> /// <returns>The converted <see cref="AtomicInteger"/>.</returns> public static implicit operator int(AtomicInteger atomicInteger) { return atomicInteger.Value; } /// <summary> /// Defines an implicit conversion of a 32-bit signed integer to a <see cref="AtomicInteger"/>. /// </summary> /// <param name="value">The 32-bit signed integer to convert.</param> /// <returns>The converted 32-bit signed integer.</returns> public static implicit operator AtomicInteger(int value) { return new AtomicInteger(value); } /// <summary> /// Returns a value that indicates whether <see cref="AtomicInteger"/> and <see cref="int"/> are equal. /// </summary> /// <param name="x">The first value (<see cref="AtomicInteger"/>) to compare.</param> /// <param name="y">The second value (<see cref="int"/>) to compare.</param> /// <returns><c>true</c> if <paramref name="x"/> and <paramref name="y"/> are equal; otherwise, <c>false</c>.</returns> public static bool operator ==(AtomicInteger x, int y) { return (x != null && x.Value == y); } /// <summary> /// Returns a value that indicates whether <see cref="AtomicInteger"/> and <see cref="int"/> have different values. /// </summary> /// <param name="x">The first value (<see cref="AtomicInteger"/>) to compare.</param> /// <param name="y">The second value (<see cref="int"/>) to compare.</param> /// <returns><c>true</c> if <paramref name="x"/> and <paramref name="y"/> are not equal; otherwise, <c>false</c>.</returns> public static bool operator !=(AtomicInteger x, int y) { return (x != null && x.Value != y); } /// <summary> /// Returns a value indicating whether this instance and a specified Object represent the same type and value. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns><c>true</c> if <paramref name="obj"/> is a <see cref="AtomicInteger"/> and equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { AtomicInteger other = obj as AtomicInteger; if (other == null) return false; return object.ReferenceEquals(this, other) || this.Value == other.Value; } /// <summary> /// Returns a value indicating whether this instance and a specified <see cref="AtomicInteger"/> object represent the same value. /// </summary> /// <param name="other">An object to compare to this instance.</param> /// <returns><c>true</c> if <paramref name="other"/> is equal to this instance; otherwise, <c>false</c>.</returns> bool IEquatable<int>.Equals(int other) { return this.Value == other; } int IAtomic<int>.Value { get { return this.Value; } set { this.Value = value; } } int IAtomicsOperator<int>.CompareExchange(ref int location1, int value, int comparand) { return Interlocked.CompareExchange(ref location1, value, comparand); } int IAtomicsOperator<int>.Read(ref int location1) { return Volatile.Read(ref location1); } } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; namespace Orleans.Runtime { /// <summary> /// The Utils class contains a variety of utility methods for use in application and grain code. /// </summary> public static class Utils { /// <summary> /// Returns a human-readable text string that describes an IEnumerable collection of objects. /// </summary> /// <typeparam name="T">The type of the list elements.</typeparam> /// <param name="collection">The IEnumerable to describe.</param> /// <returns>A string assembled by wrapping the string descriptions of the individual /// elements with square brackets and separating them with commas.</returns> public static string EnumerableToString<T>(IEnumerable<T> collection, Func<T, string> toString = null, string separator = ", ", bool putInBrackets = true) { if (collection == null) { if (putInBrackets) return "[]"; else return "null"; } var sb = new StringBuilder(); if (putInBrackets) sb.Append("["); var enumerator = collection.GetEnumerator(); bool firstDone = false; while (enumerator.MoveNext()) { T value = enumerator.Current; string val; if (toString != null) val = toString(value); else val = value == null ? "null" : value.ToString(); if (firstDone) { sb.Append(separator); sb.Append(val); } else { sb.Append(val); firstDone = true; } } if (putInBrackets) sb.Append("]"); return sb.ToString(); } /// <summary> /// Returns a human-readable text string that describes a dictionary that maps objects to objects. /// </summary> /// <typeparam name="T1">The type of the dictionary keys.</typeparam> /// <typeparam name="T2">The type of the dictionary elements.</typeparam> /// <param name="separateWithNewLine">Whether the elements should appear separated by a new line.</param> /// <param name="dict">The dictionary to describe.</param> /// <returns>A string assembled by wrapping the string descriptions of the individual /// pairs with square brackets and separating them with commas. /// Each key-value pair is represented as the string description of the key followed by /// the string description of the value, /// separated by " -> ", and enclosed in curly brackets.</returns> public static string DictionaryToString<T1, T2>(ICollection<KeyValuePair<T1, T2>> dict, Func<T2, string> toString = null, string separator = null) { if (dict == null || dict.Count == 0) { return "[]"; } if (separator == null) { separator = Environment.NewLine; } var sb = new StringBuilder("["); var enumerator = dict.GetEnumerator(); int index = 0; while (enumerator.MoveNext()) { var pair = enumerator.Current; sb.Append("{"); sb.Append(pair.Key); sb.Append(" -> "); string val; if (toString != null) val = toString(pair.Value); else val = pair.Value == null ? "null" : pair.Value.ToString(); sb.Append(val); sb.Append("}"); if (index++ < dict.Count - 1) sb.Append(separator); } sb.Append("]"); return sb.ToString(); } public static string TimeSpanToString(TimeSpan timeSpan) { //00:03:32.8289777 return String.Format("{0}h:{1}m:{2}s.{3}ms", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds); } public static long TicksToMilliSeconds(long ticks) { return (long)TimeSpan.FromTicks(ticks).TotalMilliseconds; } public static float AverageTicksToMilliSeconds(float ticks) { return (float)TimeSpan.FromTicks((long)ticks).TotalMilliseconds; } /// <summary> /// Parse a Uri as an IPEndpoint. /// </summary> /// <param name="uri">The input Uri</param> /// <returns></returns> public static System.Net.IPEndPoint ToIPEndPoint(this Uri uri) { switch (uri.Scheme) { case "gwy.tcp": return new System.Net.IPEndPoint(System.Net.IPAddress.Parse(uri.Host), uri.Port); } return null; } /// <summary> /// Parse a Uri as a Silo address, including the IPEndpoint and generation identifier. /// </summary> /// <param name="uri">The input Uri</param> /// <returns></returns> public static SiloAddress ToSiloAddress(this Uri uri) { switch (uri.Scheme) { case "gwy.tcp": return SiloAddress.New(uri.ToIPEndPoint(), uri.Segments.Length > 1 ? int.Parse(uri.Segments[1]) : 0); } return null; } /// <summary> /// Represent an IP end point in the gateway URI format.. /// </summary> /// <param name="ep">The input IP end point</param> /// <returns></returns> public static Uri ToGatewayUri(this System.Net.IPEndPoint ep) { return new Uri(string.Format("gwy.tcp://{0}:{1}/0", ep.Address, ep.Port)); } /// <summary> /// Represent a silo address in the gateway URI format. /// </summary> /// <param name="address">The input silo address</param> /// <returns></returns> public static Uri ToGatewayUri(this SiloAddress address) { return new Uri(string.Format("gwy.tcp://{0}:{1}/{2}", address.Endpoint.Address, address.Endpoint.Port, address.Generation)); } /// <summary> /// Calculates an integer hash value based on the consistent identity hash of a string. /// </summary> /// <param name="text">The string to hash.</param> /// <returns>An integer hash for the string.</returns> public static int CalculateIdHash(string text) { SHA256 sha = SHA256.Create(); // This is one implementation of the abstract class SHA1. int hash = 0; try { byte[] data = Encoding.Unicode.GetBytes(text); byte[] result = sha.ComputeHash(data); for (int i = 0; i < result.Length; i += 4) { int tmp = (result[i] << 24) | (result[i + 1] << 16) | (result[i + 2] << 8) | (result[i + 3]); hash = hash ^ tmp; } } finally { sha.Dispose(); } return hash; } public static bool TryFindException(Exception original, Type targetType, out Exception target) { if (original.GetType() == targetType) { target = original; return true; } else if (original is AggregateException) { var baseEx = original.GetBaseException(); if (baseEx.GetType() == targetType) { target = baseEx; return true; } else { var newEx = ((AggregateException)original).Flatten(); foreach (var exc in newEx.InnerExceptions) { if (exc.GetType() == targetType) { target = newEx; return true; } } } } target = null; return false; } public static void SafeExecute(Action action, TraceLogger logger = null, string caller = null) { SafeExecute(action, logger, caller==null ? (Func<string>)null : () => caller); } // a function to safely execute an action without any exception being thrown. // callerGetter function is called only in faulty case (now string is generated in the success case). [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public static void SafeExecute(Action action, TraceLogger logger, Func<string> callerGetter) { try { action(); } catch (Exception exc) { try { if (logger != null) { string caller = null; if (callerGetter != null) { caller = callerGetter(); } foreach (var e in exc.FlattenAggregate()) { logger.Warn(ErrorCode.Runtime_Error_100325, String.Format("Ignoring {0} exception thrown from an action called by {1}.", e.GetType().FullName, caller ?? String.Empty), exc); } } } catch (Exception) { // now really, really ignore. } } } /// <summary> /// Get the last characters of a string /// </summary> /// <param name="s"></param> /// <param name="count"></param> /// <returns></returns> public static string Tail(this string s, int count) { return s.Substring(Math.Max(0, s.Length - count)); } public static TimeSpan Since(DateTime start) { return DateTime.UtcNow.Subtract(start); } public static List<T> ObjectToList<T>(object data) { if (data is List<T>) return (List<T>) data; T[] dataArray; if (data is ArrayList) { dataArray = (T[]) (data as ArrayList).ToArray(typeof(T)); } else if (data is ICollection<T>) { dataArray = (data as ICollection<T>).ToArray(); } else { throw new InvalidCastException(string.Format( "Connet convert type {0} to type List<{1}>", TypeUtils.GetFullName(data.GetType()), TypeUtils.GetFullName(typeof(T)))); } var list = new List<T>(); list.AddRange(dataArray); return list; } public static List<Exception> FlattenAggregate(this Exception exc) { var result = new List<Exception>(); if (exc is AggregateException) result.AddRange(exc.InnerException.FlattenAggregate()); else result.Add(exc); return result; } public static AggregateException Flatten(this ReflectionTypeLoadException rtle) { // if ReflectionTypeLoadException is thrown, we need to provide the // LoaderExceptions property in order to make it meaningful. var all = new List<Exception> { rtle }; all.AddRange(rtle.LoaderExceptions); throw new AggregateException("A ReflectionTypeLoadException has been thrown. The original exception and the contents of the LoaderExceptions property have been aggregated for your convenence.", all); } /// <summary> /// </summary> public static IEnumerable<List<T>> BatchIEnumerable<T>(this IEnumerable<T> sequence, int batchSize) { var batch = new List<T>(batchSize); foreach (var item in sequence) { batch.Add(item); // when we've accumulated enough in the batch, send it out if (batch.Count >= batchSize) { yield return batch; // batch.ToArray(); batch = new List<T>(batchSize); } } if (batch.Count > 0) { yield return batch; //batch.ToArray(); } } internal static MethodInfo GetStaticMethodThroughReflection(string assemblyName, string className, string methodName, Type[] argumentTypes) { var asm = Assembly.Load(assemblyName); if (asm == null) throw new InvalidOperationException(string.Format("Cannot find assembly {0}", assemblyName)); var cl = asm.GetType(className); if (cl == null) throw new InvalidOperationException(string.Format("Cannot find class {0} in assembly {1}", className, assemblyName)); MethodInfo method; method = argumentTypes == null ? cl.GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static) : cl.GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, argumentTypes, null); if (method == null) throw new InvalidOperationException(string.Format("Cannot find static method {0} of class {1} in assembly {2}", methodName, className, assemblyName)); return method; } internal static object InvokeStaticMethodThroughReflection(string assemblyName, string className, string methodName, Type[] argumentTypes, object[] arguments) { var method = GetStaticMethodThroughReflection(assemblyName, className, methodName, argumentTypes); return method.Invoke(null, arguments); } internal static Type LoadTypeThroughReflection(string assemblyName, string className) { var asm = Assembly.Load(assemblyName); if (asm == null) throw new InvalidOperationException(string.Format("Cannot find assembly {0}", assemblyName)); var cl = asm.GetType(className); if (cl == null) throw new InvalidOperationException(string.Format("Cannot find class {0} in assembly {1}", className, assemblyName)); return cl; } } }
/* * 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; namespace XenAPI { /// <summary> /// Represents a patch stored on a server /// First published in XenServer 4.0. /// </summary> public partial class Host_patch : XenObject<Host_patch> { public Host_patch() { } public Host_patch(string uuid, string name_label, string name_description, string version, XenRef<Host> host, bool applied, DateTime timestamp_applied, long size, XenRef<Pool_patch> pool_patch, Dictionary<string, string> other_config) { this.uuid = uuid; this.name_label = name_label; this.name_description = name_description; this.version = version; this.host = host; this.applied = applied; this.timestamp_applied = timestamp_applied; this.size = size; this.pool_patch = pool_patch; this.other_config = other_config; } /// <summary> /// Creates a new Host_patch from a Proxy_Host_patch. /// </summary> /// <param name="proxy"></param> public Host_patch(Proxy_Host_patch proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(Host_patch update) { uuid = update.uuid; name_label = update.name_label; name_description = update.name_description; version = update.version; host = update.host; applied = update.applied; timestamp_applied = update.timestamp_applied; size = update.size; pool_patch = update.pool_patch; other_config = update.other_config; } internal void UpdateFromProxy(Proxy_Host_patch proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; name_label = proxy.name_label == null ? null : (string)proxy.name_label; name_description = proxy.name_description == null ? null : (string)proxy.name_description; version = proxy.version == null ? null : (string)proxy.version; host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host); applied = (bool)proxy.applied; timestamp_applied = proxy.timestamp_applied; size = proxy.size == null ? 0 : long.Parse((string)proxy.size); pool_patch = proxy.pool_patch == null ? null : XenRef<Pool_patch>.Create(proxy.pool_patch); other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_Host_patch ToProxy() { Proxy_Host_patch result_ = new Proxy_Host_patch(); result_.uuid = uuid ?? ""; result_.name_label = name_label ?? ""; result_.name_description = name_description ?? ""; result_.version = version ?? ""; result_.host = host ?? ""; result_.applied = applied; result_.timestamp_applied = timestamp_applied; result_.size = size.ToString(); result_.pool_patch = pool_patch ?? ""; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Creates a new Host_patch from a Hashtable. /// </summary> /// <param name="table"></param> public Host_patch(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); name_label = Marshalling.ParseString(table, "name_label"); name_description = Marshalling.ParseString(table, "name_description"); version = Marshalling.ParseString(table, "version"); host = Marshalling.ParseRef<Host>(table, "host"); applied = Marshalling.ParseBool(table, "applied"); timestamp_applied = Marshalling.ParseDateTime(table, "timestamp_applied"); size = Marshalling.ParseLong(table, "size"); pool_patch = Marshalling.ParseRef<Pool_patch>(table, "pool_patch"); other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Host_patch other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._name_label, other._name_label) && Helper.AreEqual2(this._name_description, other._name_description) && Helper.AreEqual2(this._version, other._version) && Helper.AreEqual2(this._host, other._host) && Helper.AreEqual2(this._applied, other._applied) && Helper.AreEqual2(this._timestamp_applied, other._timestamp_applied) && Helper.AreEqual2(this._size, other._size) && Helper.AreEqual2(this._pool_patch, other._pool_patch) && Helper.AreEqual2(this._other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, Host_patch 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)) { Host_patch.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given host_patch. /// First published in XenServer 4.0. /// Deprecated since XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> [Deprecated("XenServer 7.1")] public static Host_patch get_record(Session session, string _host_patch) { return new Host_patch((Proxy_Host_patch)session.proxy.host_patch_get_record(session.uuid, _host_patch ?? "").parse()); } /// <summary> /// Get a reference to the host_patch instance with the specified UUID. /// First published in XenServer 4.0. /// Deprecated since XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> [Deprecated("XenServer 7.1")] public static XenRef<Host_patch> get_by_uuid(Session session, string _uuid) { return XenRef<Host_patch>.Create(session.proxy.host_patch_get_by_uuid(session.uuid, _uuid ?? "").parse()); } /// <summary> /// Get all the host_patch instances with the given label. /// First published in XenServer 4.0. /// Deprecated since XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_label">label of object to return</param> [Deprecated("XenServer 7.1")] public static List<XenRef<Host_patch>> get_by_name_label(Session session, string _label) { return XenRef<Host_patch>.Create(session.proxy.host_patch_get_by_name_label(session.uuid, _label ?? "").parse()); } /// <summary> /// Get the uuid field of the given host_patch. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static string get_uuid(Session session, string _host_patch) { return (string)session.proxy.host_patch_get_uuid(session.uuid, _host_patch ?? "").parse(); } /// <summary> /// Get the name/label field of the given host_patch. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static string get_name_label(Session session, string _host_patch) { return (string)session.proxy.host_patch_get_name_label(session.uuid, _host_patch ?? "").parse(); } /// <summary> /// Get the name/description field of the given host_patch. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static string get_name_description(Session session, string _host_patch) { return (string)session.proxy.host_patch_get_name_description(session.uuid, _host_patch ?? "").parse(); } /// <summary> /// Get the version field of the given host_patch. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static string get_version(Session session, string _host_patch) { return (string)session.proxy.host_patch_get_version(session.uuid, _host_patch ?? "").parse(); } /// <summary> /// Get the host field of the given host_patch. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static XenRef<Host> get_host(Session session, string _host_patch) { return XenRef<Host>.Create(session.proxy.host_patch_get_host(session.uuid, _host_patch ?? "").parse()); } /// <summary> /// Get the applied field of the given host_patch. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static bool get_applied(Session session, string _host_patch) { return (bool)session.proxy.host_patch_get_applied(session.uuid, _host_patch ?? "").parse(); } /// <summary> /// Get the timestamp_applied field of the given host_patch. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static DateTime get_timestamp_applied(Session session, string _host_patch) { return session.proxy.host_patch_get_timestamp_applied(session.uuid, _host_patch ?? "").parse(); } /// <summary> /// Get the size field of the given host_patch. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static long get_size(Session session, string _host_patch) { return long.Parse((string)session.proxy.host_patch_get_size(session.uuid, _host_patch ?? "").parse()); } /// <summary> /// Get the pool_patch field of the given host_patch. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static XenRef<Pool_patch> get_pool_patch(Session session, string _host_patch) { return XenRef<Pool_patch>.Create(session.proxy.host_patch_get_pool_patch(session.uuid, _host_patch ?? "").parse()); } /// <summary> /// Get the other_config field of the given host_patch. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> public static Dictionary<string, string> get_other_config(Session session, string _host_patch) { return Maps.convert_from_proxy_string_string(session.proxy.host_patch_get_other_config(session.uuid, _host_patch ?? "").parse()); } /// <summary> /// Set the other_config field of the given host_patch. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _host_patch, Dictionary<string, string> _other_config) { session.proxy.host_patch_set_other_config(session.uuid, _host_patch ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given host_patch. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</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 _host_patch, string _key, string _value) { session.proxy.host_patch_add_to_other_config(session.uuid, _host_patch ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given host_patch. 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="_host_patch">The opaque_ref of the given host_patch</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _host_patch, string _key) { session.proxy.host_patch_remove_from_other_config(session.uuid, _host_patch ?? "", _key ?? "").parse(); } /// <summary> /// Destroy the specified host patch, removing it from the disk. This does NOT reverse the patch /// First published in XenServer 4.0. /// Deprecated since XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> [Deprecated("XenServer 4.1")] public static void destroy(Session session, string _host_patch) { session.proxy.host_patch_destroy(session.uuid, _host_patch ?? "").parse(); } /// <summary> /// Destroy the specified host patch, removing it from the disk. This does NOT reverse the patch /// First published in XenServer 4.0. /// Deprecated since XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> [Deprecated("XenServer 4.1")] public static XenRef<Task> async_destroy(Session session, string _host_patch) { return XenRef<Task>.Create(session.proxy.async_host_patch_destroy(session.uuid, _host_patch ?? "").parse()); } /// <summary> /// Apply the selected patch and return its output /// First published in XenServer 4.0. /// Deprecated since XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> [Deprecated("XenServer 4.1")] public static string apply(Session session, string _host_patch) { return (string)session.proxy.host_patch_apply(session.uuid, _host_patch ?? "").parse(); } /// <summary> /// Apply the selected patch and return its output /// First published in XenServer 4.0. /// Deprecated since XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_host_patch">The opaque_ref of the given host_patch</param> [Deprecated("XenServer 4.1")] public static XenRef<Task> async_apply(Session session, string _host_patch) { return XenRef<Task>.Create(session.proxy.async_host_patch_apply(session.uuid, _host_patch ?? "").parse()); } /// <summary> /// Return a list of all the host_patchs known to the system. /// First published in XenServer 4.0. /// Deprecated since XenServer 7.1. /// </summary> /// <param name="session">The session</param> [Deprecated("XenServer 7.1")] public static List<XenRef<Host_patch>> get_all(Session session) { return XenRef<Host_patch>.Create(session.proxy.host_patch_get_all(session.uuid).parse()); } /// <summary> /// Get all the host_patch 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<Host_patch>, Host_patch> get_all_records(Session session) { return XenRef<Host_patch>.Create<Proxy_Host_patch>(session.proxy.host_patch_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// a human-readable name /// </summary> public virtual string name_label { get { return _name_label; } set { if (!Helper.AreEqual(value, _name_label)) { _name_label = value; Changed = true; NotifyPropertyChanged("name_label"); } } } private string _name_label; /// <summary> /// a notes field containing human-readable description /// </summary> public virtual string name_description { get { return _name_description; } set { if (!Helper.AreEqual(value, _name_description)) { _name_description = value; Changed = true; NotifyPropertyChanged("name_description"); } } } private string _name_description; /// <summary> /// Patch version number /// </summary> public virtual string version { get { return _version; } set { if (!Helper.AreEqual(value, _version)) { _version = value; Changed = true; NotifyPropertyChanged("version"); } } } private string _version; /// <summary> /// Host the patch relates to /// </summary> public virtual XenRef<Host> host { get { return _host; } set { if (!Helper.AreEqual(value, _host)) { _host = value; Changed = true; NotifyPropertyChanged("host"); } } } private XenRef<Host> _host; /// <summary> /// True if the patch has been applied /// </summary> public virtual bool applied { get { return _applied; } set { if (!Helper.AreEqual(value, _applied)) { _applied = value; Changed = true; NotifyPropertyChanged("applied"); } } } private bool _applied; /// <summary> /// Time the patch was applied /// </summary> public virtual DateTime timestamp_applied { get { return _timestamp_applied; } set { if (!Helper.AreEqual(value, _timestamp_applied)) { _timestamp_applied = value; Changed = true; NotifyPropertyChanged("timestamp_applied"); } } } private DateTime _timestamp_applied; /// <summary> /// Size of the patch /// </summary> public virtual long size { get { return _size; } set { if (!Helper.AreEqual(value, _size)) { _size = value; Changed = true; NotifyPropertyChanged("size"); } } } private long _size; /// <summary> /// The patch applied /// First published in XenServer 4.1. /// </summary> public virtual XenRef<Pool_patch> pool_patch { get { return _pool_patch; } set { if (!Helper.AreEqual(value, _pool_patch)) { _pool_patch = value; Changed = true; NotifyPropertyChanged("pool_patch"); } } } private XenRef<Pool_patch> _pool_patch; /// <summary> /// additional configuration /// First published in XenServer 4.1. /// </summary> public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config; } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier< Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier< Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.NetFramework.Analyzers.UnitTests { public partial class DoNotUseInsecureDtdProcessingAnalyzerTests { private static DiagnosticResult GetCA3075DataViewCSharpResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleReviewDtdProcessingProperties).WithLocation(line, column); #pragma warning restore RS0030 // Do not used banned APIs private static DiagnosticResult GetCA3075DataViewBasicResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleReviewDtdProcessingProperties).WithLocation(line, column); #pragma warning restore RS0030 // Do not used banned APIs [Fact] public async Task UseDataSetDefaultDataViewManagerSetCollectionStringShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; namespace TestNamespace { public class ReviewDataViewConnectionString { public void TestMethod(string src) { DataSet ds = new DataSet(); ds.DefaultViewManager.DataViewSettingCollectionString = src; } } } ", GetCA3075DataViewCSharpResultAt(11, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Namespace TestNamespace Public Class ReviewDataViewConnectionString Public Sub TestMethod(src As String) Dim ds As New DataSet() ds.DefaultViewManager.DataViewSettingCollectionString = src End Sub End Class End Namespace", GetCA3075DataViewBasicResultAt(8, 13) ); } [Fact] public async Task UseDataSetDefaultDataViewManagernInGetShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; class TestClass { public DataSet Test { get { var src = """"; DataSet ds = new DataSet(); ds.DefaultViewManager.DataViewSettingCollectionString = src; return ds; } } }", GetCA3075DataViewCSharpResultAt(11, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Class TestClass Public ReadOnly Property Test() As DataSet Get Dim src = """" Dim ds As New DataSet() ds.DefaultViewManager.DataViewSettingCollectionString = src Return ds End Get End Property End Class", GetCA3075DataViewBasicResultAt(9, 13) ); } [Fact] public async Task UseDataSetDefaultDataViewManagerInSetShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; class TestClass { DataSet privateDoc; public DataSet GetDoc { set { if (value == null) { var src = """"; DataSet ds = new DataSet(); ds.DefaultViewManager.DataViewSettingCollectionString = src; privateDoc = ds; } else privateDoc = value; } } }", GetCA3075DataViewCSharpResultAt(15, 21) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Class TestClass Private privateDoc As DataSet Public WriteOnly Property GetDoc() As DataSet Set If value Is Nothing Then Dim src = """" Dim ds As New DataSet() ds.DefaultViewManager.DataViewSettingCollectionString = src privateDoc = ds Else privateDoc = value End If End Set End Property End Class", GetCA3075DataViewBasicResultAt(11, 17) ); } [Fact] public async Task UseDataSetDefaultDataViewManagerInTryBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Data; class TestClass { private void TestMethod() { try { var src = """"; DataSet ds = new DataSet(); ds.DefaultViewManager.DataViewSettingCollectionString = src; } catch (Exception) { throw; } finally { } } }", GetCA3075DataViewCSharpResultAt(13, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Data Class TestClass Private Sub TestMethod() Try Dim src = """" Dim ds As New DataSet() ds.DefaultViewManager.DataViewSettingCollectionString = src Catch generatedExceptionName As Exception Throw Finally End Try End Sub End Class", GetCA3075DataViewBasicResultAt(10, 13) ); } [Fact] public async Task UseDataSetDefaultDataViewManagerInCatchBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Data; class TestClass { private void TestMethod() { try { } catch (Exception) { var src = """"; DataSet ds = new DataSet(); ds.DefaultViewManager.DataViewSettingCollectionString = src; } finally { } } }", GetCA3075DataViewCSharpResultAt(14, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Data Class TestClass Private Sub TestMethod() Try Catch generatedExceptionName As Exception Dim src = """" Dim ds As New DataSet() ds.DefaultViewManager.DataViewSettingCollectionString = src Finally End Try End Sub End Class", GetCA3075DataViewBasicResultAt(11, 13) ); } [Fact] public async Task UseDataSetDefaultDataViewManagerInFinallyBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Data; class TestClass { private void TestMethod() { try { } catch (Exception) { throw; } finally { var src = """"; DataSet ds = new DataSet(); ds.DefaultViewManager.DataViewSettingCollectionString = src; } } }", GetCA3075DataViewCSharpResultAt(15, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Data Class TestClass Private Sub TestMethod() Try Catch generatedExceptionName As Exception Throw Finally Dim src = """" Dim ds As New DataSet() ds.DefaultViewManager.DataViewSettingCollectionString = src End Try End Sub End Class", GetCA3075DataViewBasicResultAt(13, 13) ); } [Fact] public async Task UseDataSetDefaultDataViewManagerInAsyncAwaitShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Threading.Tasks; using System.Data; class TestClass { private async Task TestMethod() { await Task.Run(() => { var src = """"; DataSet ds = new DataSet(); ds.DefaultViewManager.DataViewSettingCollectionString = src; }); } private async void TestMethod2() { await TestMethod(); } }", GetCA3075DataViewCSharpResultAt(12, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Threading.Tasks Imports System.Data Class TestClass Private Async Function TestMethod() As Task Await Task.Run(Function() Dim src = """" Dim ds As New DataSet() ds.DefaultViewManager.DataViewSettingCollectionString = src End Function) End Function Private Async Sub TestMethod2() Await TestMethod() End Sub End Class", GetCA3075DataViewBasicResultAt(10, 9) ); } [Fact] public async Task UseDataSetDefaultDataViewManagerInDelegateShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; class TestClass { delegate void Del(); Del d = delegate () { var src = """"; DataSet ds = new DataSet(); ds.DefaultViewManager.DataViewSettingCollectionString = src; }; }", GetCA3075DataViewCSharpResultAt(11, 9) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Class TestClass Private Delegate Sub Del() Private d As Del = Sub() Dim src = """" Dim ds As New DataSet() ds.DefaultViewManager.DataViewSettingCollectionString = src End Sub End Class", GetCA3075DataViewBasicResultAt(10, 5) ); } [Fact] public async Task UseDataViewManagerSetCollectionStringShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; namespace TestNamespace { public class ReviewDataViewConnectionString { public void TestMethod(string src) { DataViewManager manager = new DataViewManager(); manager.DataViewSettingCollectionString = src; } } } ", GetCA3075DataViewCSharpResultAt(11, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Namespace TestNamespace Public Class ReviewDataViewConnectionString Public Sub TestMethod(src As String) Dim manager As New DataViewManager() manager.DataViewSettingCollectionString = src End Sub End Class End Namespace", GetCA3075DataViewBasicResultAt(8, 13) ); } [Fact] public async Task UseDataViewManagerInGetShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; class TestClass { public DataViewManager Test { get { var src = """"; DataViewManager manager = new DataViewManager(); manager.DataViewSettingCollectionString = src; return manager; } } }", GetCA3075DataViewCSharpResultAt(11, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Class TestClass Public ReadOnly Property Test() As DataViewManager Get Dim src = """" Dim manager As New DataViewManager() manager.DataViewSettingCollectionString = src Return manager End Get End Property End Class", GetCA3075DataViewBasicResultAt(9, 13) ); } [Fact] public async Task UseDataViewManagerInSetShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; class TestClass { DataViewManager privateDoc; public DataViewManager GetDoc { set { if (value == null) { var src = """"; DataViewManager manager = new DataViewManager(); manager.DataViewSettingCollectionString = src; privateDoc = manager; } else privateDoc = value; } } }", GetCA3075DataViewCSharpResultAt(15, 21) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Class TestClass Private privateDoc As DataViewManager Public WriteOnly Property GetDoc() As DataViewManager Set If value Is Nothing Then Dim src = """" Dim manager As New DataViewManager() manager.DataViewSettingCollectionString = src privateDoc = manager Else privateDoc = value End If End Set End Property End Class", GetCA3075DataViewBasicResultAt(11, 17) ); } [Fact] public async Task UseDataViewManagerInTryBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Data; class TestClass { private void TestMethod() { try { var src = """"; DataViewManager manager = new DataViewManager(); manager.DataViewSettingCollectionString = src; } catch (Exception) { throw; } finally { } } }", GetCA3075DataViewCSharpResultAt(13, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Data Class TestClass Private Sub TestMethod() Try Dim src = """" Dim manager As New DataViewManager() manager.DataViewSettingCollectionString = src Catch generatedExceptionName As Exception Throw Finally End Try End Sub End Class", GetCA3075DataViewBasicResultAt(10, 13) ); } [Fact] public async Task UseDataViewManagerInCatchBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Data; class TestClass { private void TestMethod() { try { } catch (Exception) { var src = """"; DataViewManager manager = new DataViewManager(); manager.DataViewSettingCollectionString = src; } finally { } } }", GetCA3075DataViewCSharpResultAt(14, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Data Class TestClass Private Sub TestMethod() Try Catch generatedExceptionName As Exception Dim src = """" Dim manager As New DataViewManager() manager.DataViewSettingCollectionString = src Finally End Try End Sub End Class", GetCA3075DataViewBasicResultAt(11, 13) ); } [Fact] public async Task UseDataViewManagerInFinallyBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Data; class TestClass { private void TestMethod() { try { } catch (Exception) { throw; } finally { var src = """"; DataViewManager manager = new DataViewManager(); manager.DataViewSettingCollectionString = src; } } }", GetCA3075DataViewCSharpResultAt(15, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Data Class TestClass Private Sub TestMethod() Try Catch generatedExceptionName As Exception Throw Finally Dim src = """" Dim manager As New DataViewManager() manager.DataViewSettingCollectionString = src End Try End Sub End Class", GetCA3075DataViewBasicResultAt(13, 13) ); } [Fact] public async Task UseDataViewManagerInAsyncAwaitShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Threading.Tasks; using System.Data; class TestClass { private async Task TestMethod() { await Task.Run(() => { var src = """"; DataViewManager manager = new DataViewManager(); manager.DataViewSettingCollectionString = src; }); } private async void TestMethod2() { await TestMethod(); } }", GetCA3075DataViewCSharpResultAt(12, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Threading.Tasks Imports System.Data Class TestClass Private Async Function TestMethod() As Task Await Task.Run(Function() Dim src = """" Dim manager As New DataViewManager() manager.DataViewSettingCollectionString = src End Function) End Function Private Async Sub TestMethod2() Await TestMethod() End Sub End Class", GetCA3075DataViewBasicResultAt(10, 9) ); } [Fact] public async Task UseDataViewManagerInDelegateShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; class TestClass { delegate void Del(); Del d = delegate () { var src = """"; DataViewManager manager = new DataViewManager(); manager.DataViewSettingCollectionString = src; }; }", GetCA3075DataViewCSharpResultAt(11, 9) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Class TestClass Private Delegate Sub Del() Private d As Del = Sub() Dim src = """" Dim manager As New DataViewManager() manager.DataViewSettingCollectionString = src End Sub End Class", GetCA3075DataViewBasicResultAt(10, 5) ); } } }
/* ==================================================================== Licensed to the Apache Software Foundation =(ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 =(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.XWPF.UserModel { using System; /** * Specifies all types of borders which can be specified for WordProcessingML * objects which have a border. Borders can be Separated into two types: * <ul> * <li> Line borders: which specify a pattern to be used when Drawing a line around the * specified object. * </li> * <li> Art borders: which specify a repeated image to be used * when Drawing a border around the specified object. Line borders may be * specified on any object which allows a border, however, art borders may only * be used as a border at the page level - the borders under the pgBorders * element *</li> * </ul> * @author Gisella Bronzetti */ public enum Borders { NIL = (1), NONE = (2), /** * Specifies a line border consisting of a single line around the parent * object. */ SINGLE = (3), THICK = (4), DOUBLE = (5), DOTTED = (6), DASHED = (7), DOT_DASH = (8), DOT_DOT_DASH = (9), TRIPLE = (10), THIN_THICK_SMALL_GAP = (11), THICK_THIN_SMALL_GAP = (12), THIN_THICK_THIN_SMALL_GAP = (13), THIN_THICK_MEDIUM_GAP = (14), THICK_THIN_MEDIUM_GAP = (15), THIN_THICK_THIN_MEDIUM_GAP = (16), THIN_THICK_LARGE_GAP = (17), THICK_THIN_LARGE_GAP = (18), THIN_THICK_THIN_LARGE_GAP = (19), WAVE = (20), DOUBLE_WAVE = (21), DASH_SMALL_GAP = (22), DASH_DOT_STROKED = (23), THREE_D_EMBOSS = (24), THREE_D_ENGRAVE = (25), OUTSET = (26), INSET = (27), /** * Specifies an art border consisting of a repeated image of an apple */ APPLES = (28), /** * Specifies an art border consisting of a repeated image of a shell pattern */ ARCHED_SCALLOPS = (29), /** * Specifies an art border consisting of a repeated image of a baby pacifier */ BABY_PACIFIER = (30), /** * Specifies an art border consisting of a repeated image of a baby rattle */ BABY_RATTLE = (31), /** * Specifies an art border consisting of a repeated image of a Set of * balloons */ BALLOONS_3_COLORS = (32), /** * Specifies an art border consisting of a repeated image of a hot air * balloon */ BALLOONS_HOT_AIR = (33), /** * Specifies an art border consisting of a repeating image of a black and * white background. */ BASIC_BLACK_DASHES = (34), /** * Specifies an art border consisting of a repeating image of a black dot on * a white background. */ BASIC_BLACK_DOTS = (35), /** * Specifies an art border consisting of a repeating image of a black and * white background */ BASIC_BLACK_SQUARES = (36), /** * Specifies an art border consisting of a repeating image of a black and * white background. */ BASIC_THIN_LINES = (37), /** * Specifies an art border consisting of a repeating image of a black and * white background. */ BASIC_WHITE_DASHES = (38), /** * Specifies an art border consisting of a repeating image of a white dot on * a black background. */ BASIC_WHITE_DOTS = (39), /** * Specifies an art border consisting of a repeating image of a black and * white background. */ BASIC_WHITE_SQUARES = (40), /** * Specifies an art border consisting of a repeating image of a black and * white background. */ BASIC_WIDE_INLINE = (41), /** * Specifies an art border consisting of a repeating image of a black and * white background */ BASIC_WIDE_MIDLINE = (42), /** * Specifies an art border consisting of a repeating image of a black and * white background */ BASIC_WIDE_OUTLINE = (43), /** * Specifies an art border consisting of a repeated image of bats */ BATS = (44), /** * Specifies an art border consisting of repeating images of birds */ BIRDS = (45), /** * Specifies an art border consisting of a repeated image of birds flying */ BIRDS_FLIGHT = (46), /** * Specifies an art border consisting of a repeated image of a cabin */ CABINS = (47), /** * Specifies an art border consisting of a repeated image of a piece of cake */ CAKE_SLICE = (48), /** * Specifies an art border consisting of a repeated image of candy corn */ CANDY_CORN = (49), /** * Specifies an art border consisting of a repeated image of a knot work * pattern */ CELTIC_KNOTWORK = (50), /** * Specifies an art border consisting of a banner. * <p> * If the border is on the left or right, no border is displayed. * </p> */ CERTIFICATE_BANNER = (51), /** * Specifies an art border consisting of a repeating image of a chain link * pattern. */ CHAIN_LINK = (52), /** * Specifies an art border consisting of a repeated image of a champagne * bottle */ CHAMPAGNE_BOTTLE = (53), /** * Specifies an art border consisting of repeating images of a compass */ CHECKED_BAR_BLACK = (54), /** * Specifies an art border consisting of a repeating image of a colored * pattern. */ CHECKED_BAR_COLOR = (55), /** * Specifies an art border consisting of a repeated image of a Checkerboard */ CHECKERED = (56), /** * Specifies an art border consisting of a repeated image of a Christmas * tree */ CHRISTMAS_TREE = (57), /** * Specifies an art border consisting of repeating images of lines and * circles */ CIRCLES_LINES = (58), /** * Specifies an art border consisting of a repeated image of a rectangular * pattern */ CIRCLES_RECTANGLES = (59), /** * Specifies an art border consisting of a repeated image of a wave */ CLASSICAL_WAVE = (60), /** * Specifies an art border consisting of a repeated image of a clock */ CLOCKS = (61), /** * Specifies an art border consisting of repeating images of a compass */ COMPASS = (62), /** * Specifies an art border consisting of a repeated image of confetti */ CONFETTI = (63), /** * Specifies an art border consisting of a repeated image of confetti */ CONFETTI_GRAYS = (64), /** * Specifies an art border consisting of a repeated image of confetti */ CONFETTI_OUTLINE = (65), /** * Specifies an art border consisting of a repeated image of confetti * streamers */ CONFETTI_STREAMERS = (66), /** * Specifies an art border consisting of a repeated image of confetti */ CONFETTI_WHITE = (67), /** * Specifies an art border consisting of a repeated image */ CORNER_TRIANGLES = (68), /** * Specifies an art border consisting of a dashed line */ COUPON_CUTOUT_DASHES = (69), /** * Specifies an art border consisting of a dotted line */ COUPON_CUTOUT_DOTS = (70), /** * Specifies an art border consisting of a repeated image of a maze-like * pattern */ CRAZY_MAZE = (71), /** * Specifies an art border consisting of a repeated image of a butterfly */ CREATURES_BUTTERFLY = (72), /** * Specifies an art border consisting of a repeated image of a fish */ CREATURES_FISH = (73), /** * Specifies an art border consisting of repeating images of insects. */ CREATURES_INSECTS = (74), /** * Specifies an art border consisting of a repeated image of a ladybug */ CREATURES_LADY_BUG = (75), /** * Specifies an art border consisting of repeating images of a cross-stitch * pattern */ CROSS_STITCH = (76), /** * Specifies an art border consisting of a repeated image of Cupid */ CUP = (77), DECO_ARCH = (78), DECO_ARCH_COLOR = (79), DECO_BLOCKS = (80), DIAMONDS_GRAY = (81), DOUBLE_D = (82), DOUBLE_DIAMONDS = (83), EARTH_1 = (84), EARTH_2 = (85), ECLIPSING_SQUARES_1 = (86), ECLIPSING_SQUARES_2 = (87), EGGS_BLACK = (88), FANS = (89), FILM = (90), FIRECRACKERS = (91), FLOWERS_BLOCK_PRINT = (92), FLOWERS_DAISIES = (93), FLOWERS_MODERN_1 = (94), FLOWERS_MODERN_2 = (95), FLOWERS_PANSY = (96), FLOWERS_RED_ROSE = (97), FLOWERS_ROSES = (98), FLOWERS_TEACUP = (99), FLOWERS_TINY = (100), GEMS = (101), GINGERBREAD_MAN = (102), GRADIENT = (103), HANDMADE_1 = (104), HANDMADE_2 = (105), HEART_BALLOON = (106), HEART_GRAY = (107), HEARTS = (108), HEEBIE_JEEBIES = (109), HOLLY = (110), HOUSE_FUNKY = (111), HYPNOTIC = (112), ICE_CREAM_CONES = (113), LIGHT_BULB = (114), LIGHTNING_1 = (115), LIGHTNING_2 = (116), MAP_PINS = (117), MAPLE_LEAF = (118), MAPLE_MUFFINS = (119), MARQUEE = (120), MARQUEE_TOOTHED = (121), MOONS = (122), MOSAIC = (123), MUSIC_NOTES = (124), NORTHWEST = (125), OVALS = (126), PACKAGES = (127), PALMS_BLACK = (128), PALMS_COLOR = (129), PAPER_CLIPS = (130), PAPYRUS = (131), PARTY_FAVOR = (132), PARTY_GLASS = (133), PENCILS = (134), PEOPLE = (135), PEOPLE_WAVING = (136), PEOPLE_HATS = (137), POINSETTIAS = (138), POSTAGE_STAMP = (139), PUMPKIN_1 = (140), PUSH_PIN_NOTE_2 = (141), PUSH_PIN_NOTE_1 = (142), PYRAMIDS = (143), PYRAMIDS_ABOVE = (144), QUADRANTS = (145), RINGS = (146), SAFARI = (147), SAWTOOTH = (148), SAWTOOTH_GRAY = (149), SCARED_CAT = (150), SEATTLE = (151), SHADOWED_SQUARES = (152), SHARKS_TEETH = (153), SHOREBIRD_TRACKS = (154), SKYROCKET = (155), SNOWFLAKE_FANCY = (156), SNOWFLAKES = (157), SOMBRERO = (158), SOUTHWEST = (159), STARS = (160), STARS_TOP = (161), STARS_3_D = (162), STARS_BLACK = (163), STARS_SHADOWED = (164), SUN = (165), SWIRLIGIG = (166), TORN_PAPER = (167), TORN_PAPER_BLACK = (168), TREES = (169), TRIANGLE_PARTY = (170), TRIANGLES = (171), TRIBAL_1 = (172), TRIBAL_2 = (173), TRIBAL_3 = (174), TRIBAL_4 = (175), TRIBAL_5 = (176), TRIBAL_6 = (177), TWISTED_LINES_1 = (178), TWISTED_LINES_2 = (179), VINE = (180), WAVELINE = (181), WEAVING_ANGLES = (182), WEAVING_BRAID = (183), WEAVING_RIBBON = (184), WEAVING_STRIPS = (185), WHITE_FLOWERS = (186), WOODWORK = (187), X_ILLUSIONS = (188), ZANY_TRIANGLES = (189), ZIG_ZAG = (190), ZIG_ZAG_STITCH = (191) //private int value; //private Borders(int val) { // value = val; //} //public int GetValue() { // return value; //} //private static Dictionary<int, Borders> imap = new Dictionary<int, Borders>(); //static { // foreach =(Borders p in values=()) { // imap.Put=(Int32.ValueOf=(p.Value), p); // } //} //public static Borders ValueOf(int type) { // Borders pBorder = imap.Get(Int32.ValueOf=(type)); // if (pBorder == null) { // throw new ArgumentException("Unknown paragraph border: " + type); // } // return pBorder; //} } }
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 TsAngular2.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace Pathfinding.Examples { /** Example script for generating an infinite procedural world */ [HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_examples_1_1_procedural_world.php")] public class ProceduralWorld : MonoBehaviour { public Transform target; public ProceduralPrefab[] prefabs; /** How far away to generate tiles */ public int range = 1; /** World size of tiles */ public float tileSize = 100; public int subTiles = 20; /** Enable static batching on generated tiles. * Will improve overall FPS, but might cause FPS drops on * some frames when static batching is done */ public bool staticBatching = false; Queue<IEnumerator> tileGenerationQueue = new Queue<IEnumerator>(); [System.Serializable] public class ProceduralPrefab { /** Prefab to use */ public GameObject prefab; /** Number of objects per square world unit */ public float density = 0; /** Multiply by [perlin noise]. * Value from 0 to 1 indicating weight. */ public float perlin = 0; /** Perlin will be raised to this power. * A higher value gives more distinct edges */ public float perlinPower = 1; /** Some offset to avoid identical density maps */ public Vector2 perlinOffset = Vector2.zero; /** Perlin noise scale. * A higher value spreads out the maximums and minimums of the density. */ public float perlinScale = 1; /** Multiply by [random]. * Value from 0 to 1 indicating weight. */ public float random = 1; /** If checked, a single object will be created in the center of each tile */ public bool singleFixed = false; } /** All tiles */ Dictionary<Int2, ProceduralTile> tiles = new Dictionary<Int2, ProceduralTile>(); // Use this for initialization void Start () { // Calculate the closest tiles // and then recalculate the graph Update(); AstarPath.active.Scan(); StartCoroutine(GenerateTiles()); } // Update is called once per frame void Update () { // Calculate the tile the target is standing on Int2 p = new Int2(Mathf.RoundToInt((target.position.x - tileSize*0.5f) / tileSize), Mathf.RoundToInt((target.position.z - tileSize*0.5f) / tileSize)); // Clamp range range = range < 1 ? 1 : range; // Remove tiles which are out of range bool changed = true; while (changed) { changed = false; foreach (KeyValuePair<Int2, ProceduralTile> pair in tiles) { if (Mathf.Abs(pair.Key.x-p.x) > range || Mathf.Abs(pair.Key.y-p.y) > range) { pair.Value.Destroy(); tiles.Remove(pair.Key); changed = true; break; } } } // Add tiles which have come in range // and start calculating them for (int x = p.x-range; x <= p.x+range; x++) { for (int z = p.y-range; z <= p.y+range; z++) { if (!tiles.ContainsKey(new Int2(x, z))) { ProceduralTile tile = new ProceduralTile(this, x, z); var generator = tile.Generate(); // Tick it one step forward generator.MoveNext(); // Calculate the rest later tileGenerationQueue.Enqueue(generator); tiles.Add(new Int2(x, z), tile); } } } // The ones directly adjacent to the current one // should always be completely calculated // make sure they are for (int x = p.x-1; x <= p.x+1; x++) { for (int z = p.y-1; z <= p.y+1; z++) { tiles[new Int2(x, z)].ForceFinish(); } } } IEnumerator GenerateTiles () { while (true) { if (tileGenerationQueue.Count > 0) { var generator = tileGenerationQueue.Dequeue(); yield return StartCoroutine(generator); } yield return null; } } class ProceduralTile { int x, z; System.Random rnd; ProceduralWorld world; public bool destroyed { get; private set; } public ProceduralTile (ProceduralWorld world, int x, int z) { this.x = x; this.z = z; this.world = world; rnd = new System.Random((x * 10007) ^ (z*36007)); } Transform root; IEnumerator ie; public IEnumerator Generate () { ie = InternalGenerate(); GameObject rt = new GameObject("Tile " + x + " " + z); root = rt.transform; while (ie != null && root != null && ie.MoveNext()) yield return ie.Current; ie = null; } public void ForceFinish () { while (ie != null && root != null && ie.MoveNext()) {} ie = null; } Vector3 RandomInside () { Vector3 v = new Vector3(); v.x = (x + (float)rnd.NextDouble())*world.tileSize; v.z = (z + (float)rnd.NextDouble())*world.tileSize; return v; } Vector3 RandomInside (float px, float pz) { Vector3 v = new Vector3(); v.x = (px + (float)rnd.NextDouble()/world.subTiles)*world.tileSize; v.z = (pz + (float)rnd.NextDouble()/world.subTiles)*world.tileSize; return v; } Quaternion RandomYRot () { return Quaternion.Euler(360*(float)rnd.NextDouble(), 0, 360*(float)rnd.NextDouble()); } IEnumerator InternalGenerate () { Debug.Log("Generating tile " + x + ", " + z); int counter = 0; float[, ] ditherMap = new float[world.subTiles+2, world.subTiles+2]; //List<GameObject> objs = new List<GameObject>(); for (int i = 0; i < world.prefabs.Length; i++) { ProceduralPrefab pref = world.prefabs[i]; if (pref.singleFixed) { Vector3 p = new Vector3((x+0.5f) * world.tileSize, 0, (z+0.5f) * world.tileSize); GameObject ob = GameObject.Instantiate(pref.prefab, p, Quaternion.identity) as GameObject; ob.transform.parent = root; } else { float subSize = world.tileSize/world.subTiles; for (int sx = 0; sx < world.subTiles; sx++) { for (int sz = 0; sz < world.subTiles; sz++) { ditherMap[sx+1, sz+1] = 0; } } for (int sx = 0; sx < world.subTiles; sx++) { for (int sz = 0; sz < world.subTiles; sz++) { float px = x + sx/(float)world.subTiles;//sx / world.tileSize; float pz = z + sz/(float)world.subTiles;//sz / world.tileSize; float perl = Mathf.Pow(Mathf.PerlinNoise((px + pref.perlinOffset.x)*pref.perlinScale, (pz + pref.perlinOffset.y)*pref.perlinScale), pref.perlinPower); float density = pref.density * Mathf.Lerp(1, perl, pref.perlin) * Mathf.Lerp(1, (float)rnd.NextDouble(), pref.random); float fcount = subSize*subSize*density + ditherMap[sx+1, sz+1]; int count = Mathf.RoundToInt(fcount); // Apply dithering // See http://en.wikipedia.org/wiki/Floyd%E2%80%93Steinberg_dithering ditherMap[sx+1+1, sz+1+0] += (7f/16f) * (fcount - count); ditherMap[sx+1-1, sz+1+1] += (3f/16f) * (fcount - count); ditherMap[sx+1+0, sz+1+1] += (5f/16f) * (fcount - count); ditherMap[sx+1+1, sz+1+1] += (1f/16f) * (fcount - count); // Create a number of objects for (int j = 0; j < count; j++) { // Find a random position inside the current sub-tile Vector3 p = RandomInside(px, pz); GameObject ob = GameObject.Instantiate(pref.prefab, p, RandomYRot()) as GameObject; ob.transform.parent = root; //ob.SetActive ( false ); //objs.Add ( ob ); counter++; if (counter % 2 == 0) yield return null; } } } } } ditherMap = null; yield return null; yield return null; //Batch everything for improved performance if (Application.HasProLicense() && world.staticBatching) { StaticBatchingUtility.Combine(root.gameObject); } } public void Destroy () { if (root != null) { Debug.Log("Destroying tile " + x + ", " + z); GameObject.Destroy(root.gameObject); root = null; } // Make sure the tile generator coroutine is destroyed ie = null; } } } }
namespace ChoETL { #region NameSpaces using System; using System.IO; using System.Linq; using System.Reflection; using System.Collections; using System.Web; using System.Collections.Generic; using System.Diagnostics; #endregion NameSpaces public static class ChoAssembly { #region Constants private const string AspNetNamespace = "ASP"; #endregion Constants #region Shared Members (Public) internal static void Initialize() { ChoAssemblyResolver.Attach(); } private static readonly object _entryAssemblyLock = new object(); private static Assembly _entryAssembly; public static Assembly EntryAssembly { get { return _entryAssembly; } set { if (value != null) _entryAssembly = value; } } public static Assembly GetEntryAssembly() { if (_entryAssembly != null) return _entryAssembly; lock (_entryAssemblyLock) { if (_entryAssembly != null) return _entryAssembly; // Try the EntryAssembly, this doesn't work for ASP.NET classic pipeline (untested on integrated) Assembly assembly = Assembly.GetEntryAssembly(); #if !NETSTANDARD2_0 // Look for web application assembly HttpContext ctx = HttpContext.Current; if (ctx != null) assembly = GetWebApplicationAssembly(ctx); #endif // Fallback to executing assembly _entryAssembly = assembly ?? (Assembly.GetExecutingAssembly()); return _entryAssembly; } } #region GetAssemblies Overloads private readonly static object _loadedAssemblyLock = new object(); private static List<Assembly> _loadedAssemblies = null; internal static void AddToLoadedAssembly(Assembly assembly) { if (assembly == null) return; lock (_loadedAssemblyLock) { _loadedAssemblies.Add(assembly); } } public static Assembly[] GetLoadedAssemblies() { if (_loadedAssemblies != null) return _loadedAssemblies.ToArray(); lock (_loadedAssemblyLock) { if (_loadedAssemblies != null) return _loadedAssemblies.ToArray(); _loadedAssemblies = new List<Assembly>(); Assembly[] loadedAssemblies = null; try { LoadReferencedAssemblies(); loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); } catch (System.Security.SecurityException) { // Insufficient permissions to get the list of loaded assemblies } if (loadedAssemblies != null) { // Search the loaded assemblies for the type foreach (Assembly assembly in loadedAssemblies) { DiscoverNLoadAssemblies(assembly, _loadedAssemblies); } } return _loadedAssemblies.ToArray(); } } private static void LoadReferencedAssemblies() { var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList(); var loadedPaths = loadedAssemblies.Select((a) => { if (!a.IsDynamic) { try { return a.Location; } catch (Exception ex) { ChoETLLog.Error(ex.ToString()); } } return String.Empty; }).ToArray(); if (ChoETLFrxBootstrap.EnableLoadingReferencedAssemblies) { var referencedPaths = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll"); var toLoad = referencedPaths.Where(r => !loadedPaths.Contains(r, StringComparer.InvariantCultureIgnoreCase)).ToList(); toLoad.ForEach(path => { try { if (ChoETLFrxBootstrap.IgnoreLoadingAssemblies.Contains(path) || ChoETLFrxBootstrap.IgnoreLoadingAssemblies.Contains(Path.GetFileName(path))) { } else loadedAssemblies.Add(AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(path))); } catch { } } ); } } private static void DiscoverNLoadAssemblies(Assembly assembly, List<Assembly> assemblies) { assemblies.Add(assembly); } public static Assembly[] LoadAssemblies(string directory) { return LoadAssemblies(new string[] { directory }); } public static Assembly[] LoadAssemblies(string[] directories) { List<Assembly> assemblies = new List<Assembly>(); foreach (string directory in directories) { if (directory == null) continue; foreach (string file in Directory.GetFiles(directory, "*.dll;*.exe", SearchOption.AllDirectories)) //TODO: Filter needs to be configurable { if (file == null) continue; try { Assembly assembly = Assembly.LoadFile(file); if (assembly != null) { DiscoverNLoadAssemblies(assembly, assemblies); //fileProfile.Info(file); } } catch (ChoFatalApplicationException) { throw; } catch (Exception ex) { ChoETLLog.Error(ex.ToString()); } } } return assemblies.ToArray(); } #endregion GetAssemblies Overloads /// <summary> /// Gets the assembly location path for the specified assembly. /// </summary> /// <param name="assembly">The assembly to get the location for.</param> /// <returns>The location of the assembly.</returns> /// <remarks> /// <para> /// This method does not guarantee to return the correct path /// to the assembly. If only tries to give an indication as to /// where the assembly was loaded from. /// </para> /// </remarks> public static string GetAssemblyLocationInfo(Assembly assembly) { if (assembly.GlobalAssemblyCache) { return "Global Assembly Cache"; } else { try { // This call requires FileIOPermission for access to the path // if we don't have permission then we just ignore it and // carry on. return assembly.Location; } catch (System.Security.SecurityException) { return "Location Permission Denied"; } } } /// <summary> /// Gets the fully qualified name of the <see cref="Type" />, including /// the name of the assembly from which the <see cref="Type" /> was /// loaded. /// </summary> /// <param name="type">The <see cref="Type" /> to get the fully qualified name for.</param> /// <returns>The fully qualified name for the <see cref="Type" />.</returns> /// <remarks> /// <para> /// This is equivalent to the <c>Type.AssemblyQualifiedName</c> property, /// but this method works on the .NET Compact Framework 1.0 as well as /// the full .NET runtime. /// </para> /// </remarks> public static string AssemblyQualifiedName(Type type) { return type.FullName + ", " + type.Assembly.FullName; } /// <summary> /// Gets the short name of the <see cref="Assembly" />. /// </summary> /// <param name="assembly">The <see cref="Assembly" /> to get the name for.</param> /// <returns>The short name of the <see cref="Assembly" />.</returns> /// <remarks> /// <para> /// The short name of the assembly is the <see cref="Assembly.FullName" /> /// without the version, culture, or public key. i.e. it is just the /// assembly's file name without the extension. /// </para> /// <para> /// Use this rather than <c>Assembly.GetName().Name</c> because that /// is not available on the Compact Framework. /// </para> /// <para> /// Because of a FileIOPermission security demand we cannot do /// the obvious Assembly.GetName().Name. We are allowed to get /// the <see cref="Assembly.FullName" /> of the assembly so we /// start from there and strip out just the assembly name. /// </para> /// </remarks> public static string AssemblyShortName(Assembly assembly) { string name = assembly.FullName; int offset = name.IndexOf(','); if (offset > 0) { name = name.Substring(0, offset); } return name.Trim(); } /// <summary> /// Gets the file name portion of the <see cref="Assembly" />, including the extension. /// </summary> /// <param name="assembly">The <see cref="Assembly" /> to get the file name for.</param> /// <returns>The file name of the assembly.</returns> /// <remarks> /// <para> /// Gets the file name portion of the <see cref="Assembly" />, including the extension. /// </para> /// </remarks> public static string AssemblyFileName(Assembly assembly) { return System.IO.Path.GetFileName(assembly.Location); } public static string GetAssemblyName() { return GetAssemblyName(Assembly.GetCallingAssembly().FullName); } public static string GetAssemblyName(object assemblyObject) { if (assemblyObject == null) return null; return GetAssemblyName(assemblyObject.GetType().Assembly.FullName); } public static string GetAssemblyName(string assemblyFullName) { if (assemblyFullName == null) return null; if (assemblyFullName.IndexOf(",") < 0) return assemblyFullName; return assemblyFullName.Substring(0, assemblyFullName.IndexOf(",")); } #endregion #region Shared Members (Private) #if !NETSTANDARD2_0 private static Assembly GetWebApplicationAssembly(HttpContext context) { ChoGuard.ArgumentNotNull(context, "context"); IHttpHandler handler = context.CurrentHandler; if (handler == null) return null; Type type = handler.GetType(); while (type != null && type != typeof(object) && type.Namespace == AspNetNamespace) type = type.BaseType; return type.Assembly; } #endif #endregion Shared Members (Private) } }
// 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.Runtime.InteropServices; namespace System.Drawing.Graphics { internal class DLLImports { const int gdMaxColors = 256; enum gdInterpolationMethod { GD_DEFAULT = 0, GD_BELL, GD_BESSEL, GD_BILINEAR_FIXED, GD_BICUBIC, GD_BICUBIC_FIXED, GD_BLACKMAN, GD_BOX, GD_BSPLINE, GD_CATMULLROM, GD_GAUSSIAN, GD_GENERALIZED_CUBIC, GD_HERMITE, GD_HAMMING, GD_HANNING, GD_MITCHELL, GD_NEAREST_NEIGHBOUR, GD_POWER, GD_QUADRATIC, GD_SINC, GD_TRIANGLE, GD_WEIGHTED4, GD_METHOD_COUNT = 21 }; public delegate double interpolation_method(double param0); [StructLayout(LayoutKind.Sequential)] //[CLSCompliant(false)] unsafe internal struct gdImageStruct { public byte** pixels; //public IntPtr pixels; public int sx; public int sy; public int colorsTotal; public fixed int red[gdMaxColors]; public fixed int green[gdMaxColors]; public fixed int blue[gdMaxColors]; public fixed int open[gdMaxColors]; public int transparent; public IntPtr polyInts; public int polyAllocated; IntPtr brush; IntPtr tile; public fixed int brushColorMap[gdMaxColors]; public fixed int tileColorMap[gdMaxColors]; public int styleLength; public int stylePos; public IntPtr style; public int interlace; public int thick; public fixed int alpha[gdMaxColors]; public int trueColor; public int** tpixels; public int alphaBlendingFlag; public int saveAlphaFlag; public int AA; public int AA_color; public int AA_dont_blend; public int cx1; public int cy1; public int cx2; public int cy2; public uint res_x; public uint res_y; public int paletteQuantizationMethod; public int paletteQuantizationSpeed; public int paletteQuantizationMinQuality; public int paletteQuantizationMaxQuality; //gdInterpolationMethod interpolation_id; //interpolation_method interpolation; } [DllImport(Interop.LibGDBinary, CharSet = CharSet.Ansi)] internal static extern bool gdSupportsFileType(string filename, bool writing); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern IntPtr gdImageCreate(int sx, int sy); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern IntPtr gdImageCreateTrueColor(int sx, int sy); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode, EntryPoint = Interop.LibGDColorAllocateEntryPoint)] internal static extern int gdImageColorAllocate(int r, int b, int g); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Ansi)] internal static extern IntPtr gdImageCreateFromFile(string filename); //had to use mangled name here [DllImport(Interop.LibGDBinary, CharSet = CharSet.Ansi, EntryPoint = Interop.LibGDImageFileEntryPoint)] internal static extern bool gdImageFile(IntPtr image, string filename); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern void gdImageCopyResized(IntPtr destination, IntPtr source, int destinationX, int destinationY, int sourceX, int sourceY, int destinationWidth, int destinationHeight, int sourceWidth, int sourceHeight); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern void gdImageCopyMerge(IntPtr destination, IntPtr source, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern void gdImageColorTransparent(IntPtr im, int color); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern void gdImageSaveAlpha(IntPtr im, int flag); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern void gdImageAlphaBlending(IntPtr im, int flag); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern int gdImageGetPixel(IntPtr im, int x, int y); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern int gdImageGetTrueColorPixel(IntPtr im, int x, int y); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern void gdImageSetPixel(IntPtr im, int x, int y, int color); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern int gdImagePaletteToTrueColor(IntPtr src); [DllImport(Interop.LibGDBinary, EntryPoint = Interop.LibGDImageCreateFromPngCtxEntryPoint)] public static extern IntPtr gdImageCreateFromPngCtx(ref gdIOCtx @in); [DllImport(Interop.LibGDBinary, EntryPoint = Interop.LibGDImagePngCtxEntryPoint)] public static extern void gdImagePngCtx(ref gdImageStruct im, ref gdIOCtx @out); [DllImport(Interop.LibGDBinary, EntryPoint = Interop.LibGDImageCreateFromJpegCtxEntryPoint)] public static extern IntPtr gdImageCreateFromJpegCtx(ref gdIOCtx @in); [DllImport(Interop.LibGDBinary, EntryPoint = Interop.LibGDImageJpegCtxEntryPoint)] public static extern void gdImageJpegCtx(ref gdImageStruct im, ref gdIOCtx @out); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] public static extern void gdImageDestroy(IntPtr im); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] public static extern int gdAlphaBlend(int src, int dst); /// Return Type: int ///param0: gdIOCtx* [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int gdIOCtx_getC(IntPtr ctx); /// Return Type: int ///param0: gdIOCtx* ///param1: void* ///param2: int [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int gdIOCtx_getBuf(IntPtr ctx, System.IntPtr buf, int wanted); /// Return Type: void ///param0: gdIOCtx* ///param1: int [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void gdIOCtx_putC(IntPtr ctx, int ch); /// Return Type: int ///param0: gdIOCtx* ///param1: void* ///param2: int [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int gdIOCtx_putBuf(IntPtr ctx, System.IntPtr buf, int wanted); /// Return Type: int ///param0: gdIOCtx* ///param1: int [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int gdIOCtx_seek(IntPtr ctx, int pos); /// Return Type: int ///param0: gdIOCtx* [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int gdIOCtx_tell(IntPtr ctx); /// Return Type: void ///param0: gdIOCtx* [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void gdIOCtx_gd_free(IntPtr param0); [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct gdIOCtx { /// gdIOCtx_getC public gdIOCtx_getC getC; /// gdIOCtx_getBuf public gdIOCtx_getBuf getBuf; /// gdIOCtx_putC public gdIOCtx_putC putC; /// gdIOCtx_putBuf public gdIOCtx_putBuf putBuf; /// gdIOCtx_seek public gdIOCtx_seek seek; /// gdIOCtx_tell public gdIOCtx_tell tell; /// gdIOCtx_gd_free public gdIOCtx_gd_free gd_free; /// void* public System.IntPtr data; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System { using System; using System.Reflection; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Globalization; using System.Diagnostics.Contracts; using System.Security; using System.Security.Permissions; [Serializable] [AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple=false)] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_Attribute))] [System.Runtime.InteropServices.ComVisible(true)] public abstract class Attribute : _Attribute { #region Private Statics #region PropertyInfo private static Attribute[] InternalGetCustomAttributes(PropertyInfo element, Type type, bool inherit) { Contract.Requires(element != null); Contract.Requires(type != null); Contract.Requires(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute)); // walk up the hierarchy chain Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit); if (!inherit) return attributes; // create the hashtable that keeps track of inherited types Dictionary<Type, AttributeUsageAttribute> types = new Dictionary<Type, AttributeUsageAttribute>(11); // create an array list to collect all the requested attibutes List<Attribute> attributeList = new List<Attribute>(); CopyToArrayList(attributeList, attributes, types); //if this is an index we need to get the parameter types to help disambiguate Type[] indexParamTypes = GetIndexParameterTypes(element); PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes); while (baseProp != null) { attributes = GetCustomAttributes(baseProp, type, false); AddAttributesToList(attributeList, attributes, types); baseProp = GetParentDefinition(baseProp, indexParamTypes); } Array array = CreateAttributeArrayHelper(type, attributeList.Count); Array.Copy(attributeList.ToArray(), 0, array, 0, attributeList.Count); return (Attribute[])array; } private static bool InternalIsDefined(PropertyInfo element, Type attributeType, bool inherit) { // walk up the hierarchy chain if (element.IsDefined(attributeType, inherit)) return true; if (inherit) { AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType); if (!usage.Inherited) return false; //if this is an index we need to get the parameter types to help disambiguate Type[] indexParamTypes = GetIndexParameterTypes(element); PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes); while (baseProp != null) { if (baseProp.IsDefined(attributeType, false)) return true; baseProp = GetParentDefinition(baseProp, indexParamTypes); } } return false; } private static PropertyInfo GetParentDefinition(PropertyInfo property, Type[] propertyParameters) { Contract.Requires(property != null); // for the current property get the base class of the getter and the setter, they might be different // note that this only works for RuntimeMethodInfo MethodInfo propAccessor = property.GetGetMethod(true); if (propAccessor == null) propAccessor = property.GetSetMethod(true); RuntimeMethodInfo rtPropAccessor = propAccessor as RuntimeMethodInfo; if (rtPropAccessor != null) { rtPropAccessor = rtPropAccessor.GetParentDefinition(); if (rtPropAccessor != null) { // There is a public overload of Type.GetProperty that takes both a BingingFlags enum and a return type. // However, we cannot use that because it doesn't accept null for "types". return rtPropAccessor.DeclaringType.GetProperty( property.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, //will use default binder property.PropertyType, propertyParameters, //used for index properties null); } } return null; } #endregion #region EventInfo private static Attribute[] InternalGetCustomAttributes(EventInfo element, Type type, bool inherit) { Contract.Requires(element != null); Contract.Requires(type != null); Contract.Requires(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute)); // walk up the hierarchy chain Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit); if (inherit) { // create the hashtable that keeps track of inherited types Dictionary<Type, AttributeUsageAttribute> types = new Dictionary<Type, AttributeUsageAttribute>(11); // create an array list to collect all the requested attibutes List<Attribute> attributeList = new List<Attribute>(); CopyToArrayList(attributeList, attributes, types); EventInfo baseEvent = GetParentDefinition(element); while (baseEvent != null) { attributes = GetCustomAttributes(baseEvent, type, false); AddAttributesToList(attributeList, attributes, types); baseEvent = GetParentDefinition(baseEvent); } Array array = CreateAttributeArrayHelper(type, attributeList.Count); Array.Copy(attributeList.ToArray(), 0, array, 0, attributeList.Count); return (Attribute[])array; } else return attributes; } private static EventInfo GetParentDefinition(EventInfo ev) { Contract.Requires(ev != null); // note that this only works for RuntimeMethodInfo MethodInfo add = ev.GetAddMethod(true); RuntimeMethodInfo rtAdd = add as RuntimeMethodInfo; if (rtAdd != null) { rtAdd = rtAdd.GetParentDefinition(); if (rtAdd != null) return rtAdd.DeclaringType.GetEvent(ev.Name); } return null; } private static bool InternalIsDefined (EventInfo element, Type attributeType, bool inherit) { Contract.Requires(element != null); // walk up the hierarchy chain if (element.IsDefined(attributeType, inherit)) return true; if (inherit) { AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType); if (!usage.Inherited) return false; EventInfo baseEvent = GetParentDefinition(element); while (baseEvent != null) { if (baseEvent.IsDefined(attributeType, false)) return true; baseEvent = GetParentDefinition(baseEvent); } } return false; } #endregion #region ParameterInfo private static ParameterInfo GetParentDefinition(ParameterInfo param) { Contract.Requires(param != null); // note that this only works for RuntimeMethodInfo RuntimeMethodInfo rtMethod = param.Member as RuntimeMethodInfo; if (rtMethod != null) { rtMethod = rtMethod.GetParentDefinition(); if (rtMethod != null) { // Find the ParameterInfo on this method int position = param.Position; if (position == -1) { return rtMethod.ReturnParameter; } else { ParameterInfo[] parameters = rtMethod.GetParameters(); return parameters[position]; // Point to the correct ParameterInfo of the method } } } return null; } private static Attribute[] InternalParamGetCustomAttributes(ParameterInfo param, Type type, bool inherit) { Contract.Requires(param != null); // For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain that // have this ParameterInfo defined. .We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes // that are marked inherited from the remainder of the MethodInfo's in the inheritance chain. // For MethodInfo's on an interface we do not do an inheritance walk so the default ParameterInfo attributes are returned. // For MethodInfo's on a class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the // class inherits from and return the respective ParameterInfo attributes List<Type> disAllowMultiple = new List<Type>(); Object [] objAttr; if (type == null) type = typeof(Attribute); objAttr = param.GetCustomAttributes(type, false); for (int i =0;i < objAttr.Length;i++) { Type objType = objAttr[i].GetType(); AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType); if (attribUsage.AllowMultiple == false) disAllowMultiple.Add(objType); } // Get all the attributes that have Attribute as the base class Attribute [] ret = null; if (objAttr.Length == 0) ret = CreateAttributeArrayHelper(type,0); else ret = (Attribute[])objAttr; if (param.Member.DeclaringType == null) // This is an interface so we are done. return ret; if (!inherit) return ret; ParameterInfo baseParam = GetParentDefinition(param); while (baseParam != null) { objAttr = baseParam.GetCustomAttributes(type, false); int count = 0; for (int i =0;i < objAttr.Length;i++) { Type objType = objAttr[i].GetType(); AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType); if ((attribUsage.Inherited) && (disAllowMultiple.Contains(objType) == false)) { if (attribUsage.AllowMultiple == false) disAllowMultiple.Add(objType); count++; } else objAttr[i] = null; } // Get all the attributes that have Attribute as the base class Attribute [] attributes = CreateAttributeArrayHelper(type,count); count = 0; for (int i =0;i < objAttr.Length;i++) { if (objAttr[i] != null) { attributes[count] = (Attribute)objAttr[i]; count++; } } Attribute [] temp = ret; ret = CreateAttributeArrayHelper(type,temp.Length + count); Array.Copy(temp,ret,temp.Length); int offset = temp.Length; for (int i =0;i < attributes.Length;i++) ret[offset + i] = attributes[i]; baseParam = GetParentDefinition(baseParam); } return ret; } private static bool InternalParamIsDefined(ParameterInfo param, Type type, bool inherit) { Contract.Requires(param != null); Contract.Requires(type != null); // For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain. // We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes // that are marked inherited from the remainder of the ParameterInfo's in the inheritance chain. // For MethodInfo's on an interface we do not do an inheritance walk. For ParameterInfo's on a // Class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the class inherits from. if (param.IsDefined(type, false)) return true; if (param.Member.DeclaringType == null || !inherit) // This is an interface so we are done. return false; ParameterInfo baseParam = GetParentDefinition(param); while (baseParam != null) { Object[] objAttr = baseParam.GetCustomAttributes(type, false); for (int i =0; i < objAttr.Length; i++) { Type objType = objAttr[i].GetType(); AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType); if ((objAttr[i] is Attribute) && (attribUsage.Inherited)) return true; } baseParam = GetParentDefinition(baseParam); } return false; } #endregion #region Utility private static void CopyToArrayList(List<Attribute> attributeList,Attribute[] attributes,Dictionary<Type, AttributeUsageAttribute> types) { for (int i = 0; i < attributes.Length; i++) { attributeList.Add(attributes[i]); Type attrType = attributes[i].GetType(); if (!types.ContainsKey(attrType)) types[attrType] = InternalGetAttributeUsage(attrType); } } private static Type[] GetIndexParameterTypes(PropertyInfo element) { ParameterInfo[] indexParams = element.GetIndexParameters(); if (indexParams.Length > 0) { Type[] indexParamTypes = new Type[indexParams.Length]; for (int i = 0; i < indexParams.Length; i++) { indexParamTypes[i] = indexParams[i].ParameterType; } return indexParamTypes; } return Array.Empty<Type>(); } private static void AddAttributesToList(List<Attribute> attributeList, Attribute[] attributes, Dictionary<Type, AttributeUsageAttribute> types) { for (int i = 0; i < attributes.Length; i++) { Type attrType = attributes[i].GetType(); AttributeUsageAttribute usage = null; types.TryGetValue(attrType, out usage); if (usage == null) { // the type has never been seen before if it's inheritable add it to the list usage = InternalGetAttributeUsage(attrType); types[attrType] = usage; if (usage.Inherited) attributeList.Add(attributes[i]); } else if (usage.Inherited && usage.AllowMultiple) { // we saw this type already add it only if it is inheritable and it does allow multiple attributeList.Add(attributes[i]); } } } private static AttributeUsageAttribute InternalGetAttributeUsage(Type type) { // Check if the custom attributes is Inheritable Object [] obj = type.GetCustomAttributes(typeof(AttributeUsageAttribute), false); if (obj.Length == 1) return (AttributeUsageAttribute)obj[0]; if (obj.Length == 0) return AttributeUsageAttribute.Default; throw new FormatException( Environment.GetResourceString("Format_AttributeUsage", type)); } [System.Security.SecuritySafeCritical] private static Attribute[] CreateAttributeArrayHelper(Type elementType, int elementCount) { return (Attribute[])Array.UnsafeCreateInstance(elementType, elementCount); } #endregion #endregion #region Public Statics #region MemberInfo public static Attribute[] GetCustomAttributes(MemberInfo element, Type type) { return GetCustomAttributes(element, type, true); } public static Attribute[] GetCustomAttributes(MemberInfo element, Type type, bool inherit) { if (element == null) throw new ArgumentNullException(nameof(element)); if (type == null) throw new ArgumentNullException(nameof(type)); if (!type.IsSubclassOf(typeof(Attribute)) && type != typeof(Attribute)) throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); Contract.EndContractBlock(); switch (element.MemberType) { case MemberTypes.Property: return InternalGetCustomAttributes((PropertyInfo)element, type, inherit); case MemberTypes.Event: return InternalGetCustomAttributes((EventInfo)element, type, inherit); default: return element.GetCustomAttributes(type, inherit) as Attribute[]; } } public static Attribute[] GetCustomAttributes(MemberInfo element) { return GetCustomAttributes(element, true); } public static Attribute[] GetCustomAttributes(MemberInfo element, bool inherit) { if (element == null) throw new ArgumentNullException(nameof(element)); Contract.EndContractBlock(); switch (element.MemberType) { case MemberTypes.Property: return InternalGetCustomAttributes((PropertyInfo)element, typeof(Attribute), inherit); case MemberTypes.Event: return InternalGetCustomAttributes((EventInfo)element, typeof(Attribute), inherit); default: return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[]; } } public static bool IsDefined(MemberInfo element, Type attributeType) { return IsDefined(element, attributeType, true); } public static bool IsDefined(MemberInfo element, Type attributeType, bool inherit) { // Returns true if a custom attribute subclass of attributeType class/interface with inheritance walk if (element == null) throw new ArgumentNullException(nameof(element)); if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); Contract.EndContractBlock(); switch(element.MemberType) { case MemberTypes.Property: return InternalIsDefined((PropertyInfo)element, attributeType, inherit); case MemberTypes.Event: return InternalIsDefined((EventInfo)element, attributeType, inherit); default: return element.IsDefined(attributeType, inherit); } } public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType) { return GetCustomAttribute(element, attributeType, true); } public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType, bool inherit) { Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit); if (attrib == null || attrib.Length == 0) return null; if (attrib.Length == 1) return attrib[0]; throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust")); } #endregion #region ParameterInfo public static Attribute[] GetCustomAttributes(ParameterInfo element) { return GetCustomAttributes(element, true); } public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType) { return (Attribute[])GetCustomAttributes(element, attributeType, true); } public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType, bool inherit) { if (element == null) throw new ArgumentNullException(nameof(element)); if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); if (element.Member == null) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), nameof(element)); Contract.EndContractBlock(); MemberInfo member = element.Member; if (member.MemberType == MemberTypes.Method && inherit) return InternalParamGetCustomAttributes(element, attributeType, inherit) as Attribute[]; return element.GetCustomAttributes(attributeType, inherit) as Attribute[]; } public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit) { if (element == null) throw new ArgumentNullException(nameof(element)); if (element.Member == null) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), nameof(element)); Contract.EndContractBlock(); MemberInfo member = element.Member; if (member.MemberType == MemberTypes.Method && inherit) return InternalParamGetCustomAttributes(element, null, inherit) as Attribute[]; return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[]; } public static bool IsDefined(ParameterInfo element, Type attributeType) { return IsDefined(element, attributeType, true); } public static bool IsDefined(ParameterInfo element, Type attributeType, bool inherit) { // Returns true is a custom attribute subclass of attributeType class/interface with inheritance walk if (element == null) throw new ArgumentNullException(nameof(element)); if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); Contract.EndContractBlock(); MemberInfo member = element.Member; switch(member.MemberType) { case MemberTypes.Method: // We need to climb up the member hierarchy return InternalParamIsDefined(element, attributeType, inherit); case MemberTypes.Constructor: return element.IsDefined(attributeType, false); case MemberTypes.Property: return element.IsDefined(attributeType, false); default: Contract.Assert(false, "Invalid type for ParameterInfo member in Attribute class"); throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParamInfo")); } } public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType) { return GetCustomAttribute(element, attributeType, true); } public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType, bool inherit) { // Returns an Attribute of base class/inteface attributeType on the ParameterInfo or null if none exists. // throws an AmbiguousMatchException if there are more than one defined. Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit); if (attrib == null || attrib.Length == 0) return null; if (attrib.Length == 0) return null; if (attrib.Length == 1) return attrib[0]; throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust")); } #endregion #region Module public static Attribute[] GetCustomAttributes(Module element, Type attributeType) { return GetCustomAttributes (element, attributeType, true); } public static Attribute[] GetCustomAttributes(Module element) { return GetCustomAttributes(element, true); } public static Attribute[] GetCustomAttributes(Module element, bool inherit) { if (element == null) throw new ArgumentNullException(nameof(element)); Contract.EndContractBlock(); return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit); } public static Attribute[] GetCustomAttributes(Module element, Type attributeType, bool inherit) { if (element == null) throw new ArgumentNullException(nameof(element)); if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); Contract.EndContractBlock(); return (Attribute[])element.GetCustomAttributes(attributeType, inherit); } public static bool IsDefined(Module element, Type attributeType) { return IsDefined(element, attributeType, false); } public static bool IsDefined(Module element, Type attributeType, bool inherit) { // Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk if (element == null) throw new ArgumentNullException(nameof(element)); if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); Contract.EndContractBlock(); return element.IsDefined(attributeType,false); } public static Attribute GetCustomAttribute(Module element, Type attributeType) { return GetCustomAttribute(element, attributeType, true); } public static Attribute GetCustomAttribute(Module element, Type attributeType, bool inherit) { // Returns an Attribute of base class/inteface attributeType on the Module or null if none exists. // throws an AmbiguousMatchException if there are more than one defined. Attribute[] attrib = GetCustomAttributes(element,attributeType,inherit); if (attrib == null || attrib.Length == 0) return null; if (attrib.Length == 1) return attrib[0]; throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust")); } #endregion #region Assembly public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType) { return GetCustomAttributes(element, attributeType, true); } public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType, bool inherit) { if (element == null) throw new ArgumentNullException(nameof(element)); if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); Contract.EndContractBlock(); return (Attribute[])element.GetCustomAttributes(attributeType, inherit); } public static Attribute[] GetCustomAttributes(Assembly element) { return GetCustomAttributes(element, true); } public static Attribute[] GetCustomAttributes(Assembly element, bool inherit) { if (element == null) throw new ArgumentNullException(nameof(element)); Contract.EndContractBlock(); return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit); } public static bool IsDefined (Assembly element, Type attributeType) { return IsDefined (element, attributeType, true); } public static bool IsDefined (Assembly element, Type attributeType, bool inherit) { // Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk if (element == null) throw new ArgumentNullException(nameof(element)); if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); Contract.EndContractBlock(); return element.IsDefined(attributeType, false); } public static Attribute GetCustomAttribute(Assembly element, Type attributeType) { return GetCustomAttribute (element, attributeType, true); } public static Attribute GetCustomAttribute(Assembly element, Type attributeType, bool inherit) { // Returns an Attribute of base class/inteface attributeType on the Assembly or null if none exists. // throws an AmbiguousMatchException if there are more than one defined. Attribute[] attrib = GetCustomAttributes(element,attributeType,inherit); if (attrib == null || attrib.Length == 0) return null; if (attrib.Length == 1) return attrib[0]; throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust")); } #endregion #endregion #region Constructor protected Attribute() { } #endregion #region Object Overrides [SecuritySafeCritical] public override bool Equals(Object obj) { if (obj == null) return false; Type thisType = this.GetType(); Type thatType = obj.GetType(); if (thatType != thisType) return false; Object thisObj = this; Object thisResult, thatResult; while (thisType != typeof(Attribute)) { FieldInfo[] thisFields = thisType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); for (int i = 0; i < thisFields.Length; i++) { // Visibility check and consistency check are not necessary. thisResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(thisObj); thatResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(obj); if (!AreFieldValuesEqual(thisResult, thatResult)) { return false; } } thisType = thisType.BaseType; } return true; } // Compares values of custom-attribute fields. private static bool AreFieldValuesEqual(Object thisValue, Object thatValue) { if (thisValue == null && thatValue == null) return true; if (thisValue == null || thatValue == null) return false; if (thisValue.GetType().IsArray) { // Ensure both are arrays of the same type. if (!thisValue.GetType().Equals(thatValue.GetType())) { return false; } Array thisValueArray = thisValue as Array; Array thatValueArray = thatValue as Array; if (thisValueArray.Length != thatValueArray.Length) { return false; } // Attributes can only contain single-dimension arrays, so we don't need to worry about // multidimensional arrays. Contract.Assert(thisValueArray.Rank == 1 && thatValueArray.Rank == 1); for (int j = 0; j < thisValueArray.Length; j++) { if (!AreFieldValuesEqual(thisValueArray.GetValue(j), thatValueArray.GetValue(j))) { return false; } } } else { // An object of type Attribute will cause a stack overflow. // However, this should never happen because custom attributes cannot contain values other than // constants, single-dimensional arrays and typeof expressions. Contract.Assert(!(thisValue is Attribute)); if (!thisValue.Equals(thatValue)) return false; } return true; } [SecuritySafeCritical] public override int GetHashCode() { Type type = GetType(); while (type != typeof(Attribute)) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); Object vThis = null; for (int i = 0; i < fields.Length; i++) { // Visibility check and consistency check are not necessary. Object fieldValue = ((RtFieldInfo)fields[i]).UnsafeGetValue(this); // The hashcode of an array ignores the contents of the array, so it can produce // different hashcodes for arrays with the same contents. // Since we do deep comparisons of arrays in Equals(), this means Equals and GetHashCode will // be inconsistent for arrays. Therefore, we ignore hashes of arrays. if (fieldValue != null && !fieldValue.GetType().IsArray) vThis = fieldValue; if (vThis != null) break; } if (vThis != null) return vThis.GetHashCode(); type = type.BaseType; } return type.GetHashCode(); } #endregion #region Public Virtual Members public virtual Object TypeId { get { return GetType(); } } public virtual bool Match(Object obj) { return Equals(obj); } #endregion #region Public Members public virtual bool IsDefaultAttribute() { return false; } #endregion #if !FEATURE_CORECLR void _Attribute.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _Attribute.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _Attribute.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } void _Attribute.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } }
using System; using System.Threading.Tasks; using System.Collections.Generic; using Discord; using Discord.WebSocket; using Discord.Commands; namespace ConsoleApp1 { public class Guildinfo : ModuleBase { [Command("guildinfo"), Summary("Grabs a detailed summary of the current guild!")] [Alias("ginfo")] public async Task GetGuildInfo() { await ReplyAsync("", false, new EmbedGuildInfo(Context.Guild as SocketGuild, Context.User as SocketUser)._get(), null); } [Command("guildinfo"), Summary("Grabs a detailed summary of any guild!")] [Alias("ginfo")] public async Task GetGuildInfo(ulong id) { SocketGuild guild = (await Context.Client.GetGuildAsync(id)) as SocketGuild; if (guild == null) throw new NullGuildException(id); else await ReplyAsync("", false, new EmbedGuildInfo(guild, Context.User as SocketUser)._get(), null); } } public class Userinfo : ModuleBase { [Command("userinfo"), Summary("Grabs the detailed user-information of a specific person!")] [Alias("uinfo")] public async Task GetUserInfo([Summary("The user to retrieve information from!")] IUser user) { EmbedUserInfo ui = new EmbedUserInfo((SocketUser)user, (SocketGuild)Context.Guild, Context.User as SocketUser); ui._get().ThumbnailUrl = Context.Client.CurrentUser.GetAvatarUrl(ImageFormat.Png, 256); await ReplyAsync("", false, ui._get(), null); } } public class Userlist : ModuleBase { [Command("userlist"), Summary("Shows a list of users in this server from <1-25>!")] public async Task UserlistCommand([Summary("The integer to display!")] ushort Int) { if (Int == 0) Int = 10; IEnumerable<IUser> users = await Context.Channel.GetUsersAsync().Flatten(); ushort count = 0; string text = "Due to spam protection, a complete list (as in 25+ people) has been disabled! " + "However, to get vastly more detailed information on a **specific user**, use the *userinfo* command!\n\n"; foreach (IUser obj in users) { if (obj.IsBot) continue; count++; text += $"{count}. **{obj.Username}**\n"; if (count == Int || count == 25) break; } text += $"\nThere's a list of {count} users (excluding bots, since they don't count! :p)"; await ReplyAsync(text); } } public class EightBall : ModuleBase { [Command("8ball"), Summary("Makes an incredibly wise judgement on absolutely anything!")] public async Task ThrowBall([Remainder, Summary("The query to judge!")] string query) { string[] responses = {"Noooo!", "Yes!", "Certainly!", "Nope.", "Try again.", "Too tired to answer your question... zZZz *yawnnnn*~", "Positive!", "Senses point otherwise!", "Definitely!", "Nah." }; await ReplyAsync($"{Context.User.Mention}\n{responses[new Random().Next(0, responses.Length)]}"); } } public class Rate : ModuleBase { [Command("rate"), Summary("Rates something totally random!")] public async Task RateQuery([Remainder, Summary("The query to rate!")] string query) { await ReplyAsync($"{Context.User.Mention}\nI rate `{query}` a {new Random().Next(0, 10)}/10!"); } } public class Roll : ModuleBase { [Command("roll"), Summary("Rolls a random number between <0-100>!")] public async Task RollNumbers() { await ReplyAsync($"{Context.User.Mention}\n{new Random().Next(0, 100)}/100!"); } } public class Help : ModuleBase { [Command("help"), Summary("Sends a pre-written help message!")] public async Task help([Summary("The help message to send!")] string arg) { // Frequently Asked Questions (FAQ's): string faq = "Here are a list of Frequently Asked Questions (FAQ):\n\n" + "Q. Is LunarBot complete?\n" + "A. *Definitely not.* LunarBot is an actively-developed project written in C# " + "(specifically, using the Discord.Net 1.0 Wrapper by RogueException. It was only " + "meant to be a side-project as a way to interactively learn C#, and it's still obviously " + "under development!\n\n"; faq += "Q. Who works on LunarBot?\n" + "A. Currently, as of the 16th March 2017, there is only one developer working on LunarBot. " + "I (the creator, who just so happens to be writing this message) don't need the help right now " + "as I am notorious for abandoning team projects. The source for LunarBot is currently closed-source!\n\n"; faq += "Q. How do I use LunarBot?\n" + "A. It's very simple! LunarBot uses the dash symbol as a command prefix, and it's **always** placed " + "just before the command you wish to use at the start of the message. Command parameters are also **always** " + "separated by spaces.\n\n*More FAQ's will be placed elsewhere so as to prevent major spam.*"; // Commands string commands = "LunarBot commands are **always** placed succeeding a dash (`-`) prefix at the " + "start of a message. In the case of an error/exception raised by a Command Module, LunarBot will " + "send a neatly-formatted embed message to the guild's default channel detailing the cause of the exception.\n\n"; commands += "It should be noted that a lot of LunarBot commands can only be used in a guild where LunarBot " + "is online and present. This is because LunarBot was meant to play a server-administrator role, and not " + "a personal assistant/fun bot role! Commands like `-help`, `-roll`, and others which don't involve a guild " + "still (and will always) work!\n\n"; commands += "At the end of every embed error message, there is a suggestion to contact me (the creator) " + "if the error reoccurs multiple times without a clear cause. Please only contact me if you cannot " + "fix it yourself (i.e. using a decimal instead of an integer)! Furthermore, to view a command's " + "detailed information, say `-cmdinfo <commandname>`!"; // Bugs string bugs = "If you are ever so unfortunate enough so as to find a bug within LunarBot, please " + "***immediately*** contact me so I can push out a fix before it affects others. Once fixed, " + "an announcement will be made within the LunarBot server congratulating you for finding a bug!"; // New/Changelist string newA = "LunarBot, as of Version Beta-0.1.4, is taking a more server-helper-centered role. `Emote` commands " + "will still work and be further expanded onto, though for now the focus is on making it easier for server/guild " + "owners to administrate their server. I'm open to suggestions through the official LunarBot server, so " + "ask away while the chance is still here! c:\n\n Link: https://discord.gg/k9NU6Z6"; switch(arg) { case "cmds": case "commands": await ReplyAsync(commands); break; case "bugs": case "bug": await ReplyAsync(bugs); break; case "faq": await ReplyAsync(faq); break; case "new": await ReplyAsync(newA); break; default: await ReplyAsync("Please enter a valid help parameter! (`cmds`, `bugs`, `faq` or `new`)"); break; } } } // Admin/Owner Commands public class CreateChannel : ModuleBase { [Command("createchannel"), Summary("Creates a text channel!")] [Alias("createc")] [RequireBotPermission(GuildPermission.Administrator)] [RequireUserPermission(GuildPermission.Administrator)] [RequireContext(ContextType.Guild)] public async Task createc([Summary("The name of the channel")] string name) { await Context.Guild.CreateTextChannelAsync(name); await ReplyAsync($"Created channel \"{name}\"!"); } } public class DeleteChannel : ModuleBase { [Command("removechannel"), Summary("Removes a text channel")] [Alias("deletechannel", "deletec", "removec")] [RequireBotPermission(GuildPermission.Administrator)] [RequireUserPermission(GuildPermission.Administrator)] [RequireContext(ContextType.Guild)] public async Task deletec([Summary("The channel to delete")] ITextChannel channel) { await channel.DeleteAsync(); await ReplyAsync($"Removed channel \"#{channel.Name}\""); } } public class Kick : ModuleBase { [Command("kick"), Summary("Kicks a user!")] [RequireBotPermission(GuildPermission.KickMembers)] [RequireUserPermission(GuildPermission.KickMembers)] [RequireContext(ContextType.Guild)] public async Task kick([Summary("The user to kick")] IUser user) { IGuildUser userx = user as IGuildUser; if (userx != null && user.Id != Context.Guild.OwnerId) { await ReplyAsync($"Bye {userx.Mention}!"); await userx.KickAsync(); } else throw new MemberRemovalException(); } } public class Ban : ModuleBase { [Command("ban"), Summary("Bans a user!")] [RequireBotPermission(GuildPermission.BanMembers)] [RequireUserPermission(GuildPermission.BanMembers)] [RequireContext(ContextType.Guild)] public async Task ban([Summary("The user to ban")] IUser user) { IGuildUser userx = user as IGuildUser; if (userx != null && user.Id != Context.Guild.OwnerId) { await ReplyAsync($"Enjoy the ban, my friend! {userx.Mention}"); await Context.Guild.AddBanAsync(userx, 30, null); } else throw new MemberRemovalException(); } } public class Prune : ModuleBase { [Command("prune"), Summary("Prunes a user's messages!")] [RequireBotPermission(GuildPermission.ManageMessages)] [RequireUserPermission(ChannelPermission.ManageMessages)] [RequireContext(ContextType.Guild)] public async Task prune([Summary("The user to prune!")] IUser user) { SocketGuildUser userx = user as SocketGuildUser; if (userx != null) { IEnumerable<IMessage> messages = await Context.Channel.GetMessagesAsync().Flatten(); uint count = 0; foreach (IMessage msg in messages) { SocketGuildUser author = msg.Author as SocketGuildUser; if (msg.Author.Id == userx.Id && author.Hierarchy <= userx.Hierarchy) { count++; await msg.DeleteAsync(); } } await ReplyAsync($"Removed {count} messages from {user.Mention}!"); } } [Command("prune"), Summary("Prunes all messages!")] [RequireBotPermission(GuildPermission.ManageMessages)] [RequireUserPermission(ChannelPermission.ManageMessages)] [RequireContext(ContextType.Guild)] public async Task prune() { IEnumerable<IMessage> messages = await Context.Channel.GetMessagesAsync().Flatten(); SocketGuildUser author = Context.User as SocketGuildUser; if (author == null) return; uint count = 0; foreach (IMessage msg in messages) { SocketGuildUser user = msg.Author as SocketGuildUser; if (user.Hierarchy <= author.Hierarchy) { count++; await msg.DeleteAsync(); } } await ReplyAsync($"Removed {count} messages from channel \"{Context.Channel.Name}\"!"); } } public class PruneByName : ModuleBase { [Command("prunebyname"), Summary("Deletes a removed user's messages!")] [RequireBotPermission(GuildPermission.ManageMessages)] [RequireUserPermission(ChannelPermission.ManageMessages)] [RequireContext(ContextType.Guild)] public async Task prune([Summary("The name of the user to remove messages from!")] string name) { IEnumerable<IMessage> messages = await Context.Channel.GetMessagesAsync().Flatten(); SocketGuildUser user = Context.User as SocketGuildUser; uint count = 0; foreach (IMessage msg in messages) { SocketGuildUser author = msg.Author as SocketGuildUser; if (author.Username == name && author.Hierarchy <= user.Hierarchy) { count++; await msg.DeleteAsync(); } } await ReplyAsync($"Removed {count} messages from \"{name}\"!"); } } public class RemoveRole : ModuleBase { [Command("remover"), Summary("Removes a role from the current guild!")] [Alias("removerole", "rrole")] [RequireBotPermission(GuildPermission.Administrator)] [RequireOwner] [RequireContext(ContextType.Guild)] public async Task rrole([Summary("The role to delete!")] IRole role) { await ReplyAsync($"Deleted role \"{role.Name}\"!"); await role.DeleteAsync(); } } public class AddRole : ModuleBase { [Command("addrole"), Summary("Adds a role to the current guild!")] [Alias("addr")] [RequireBotPermission(GuildPermission.Administrator)] [RequireOwner] [RequireContext(ContextType.Guild)] public async Task addrole([Summary("The role to create!")] string name) { await Context.Guild.CreateRoleAsync(name); await ReplyAsync($"Created role \"{name}\"!"); } } public class GiveRole : ModuleBase { [Command("giverole"), Summary("Gives a user a role!")] [Alias("giver")] [RequireBotPermission(GuildPermission.Administrator)] [RequireContext(ContextType.Guild), RequireOwner] public async Task giver([Summary("The user to promote!")] IUser user, [Summary("The role to give to the user!")] IRole role) { await (user as IGuildUser)?.AddRoleAsync(role); await ReplyAsync($"Gave **{user.Mention}** the **{role.Name}** role!"); } } public class RevokeRole : ModuleBase { [Command("revokerole"), Summary("Revokes a role from a user!")] [Alias("revoker")] [RequireBotPermission(GuildPermission.Administrator)] [RequireContext(ContextType.Guild), RequireOwner] public async Task revr([Summary("The user to revoke <role> from!")] IUser user, [Summary("The role to revoke!")] IRole role) { await (user as IGuildUser)?.RemoveRoleAsync(role); await ReplyAsync($"Removed the **{role.Name}** role from **{user.Mention}**"); } } public class Announce : ModuleBase { [Command("announce"), Summary("Makes a guild-wide announcement, providing you have an #announcements channel!")] [Alias("shout", "global")] [RequireOwner] [RequireContext(ContextType.Guild)] public async Task announce([Remainder, Summary("The message to announce!")] string message) { IEnumerable<ITextChannel> channels = await Context.Guild.GetTextChannelsAsync(); ITextChannel channel = null; foreach (ITextChannel ch in channels) { if (ch.Name == "announcements") { channel = ch; break; } } if (channel == null) throw new MissingChannelException(); else await channel.SendMessageAsync($"@here (announcement from server owner):\n\n\"{message}\""); } } public class EditChannel : ModuleBase { [Command("editchannel"), Summary("Modifies a Guild Text Channel!")] [RequireContext(ContextType.Guild)] [RequireBotPermission(GuildPermission.Administrator)] [RequireUserPermission(GuildPermission.Administrator)] public async Task edit1(ITextChannel channel, string field, int pos) { if (field.ToLower() != "position") throw new IncorrectParameterException(); else await channel.ModifyAsync(x => x.Position = pos + 1); await ReplyAsync($"Attempted to change the `{field}` field to `{pos}`!"); } // separate methods [Command("editchannel"), Summary("Modifies a Guild Text Channel!")] [RequireBotPermission(GuildPermission.Administrator)] [RequireUserPermission(GuildPermission.Administrator), RequireContext(ContextType.Guild)] public async Task edit1(ITextChannel channel, string field, [Remainder]string modify = null) { field = field.ToLower(); if (field != "name" && field != "topic") throw new IncorrectParameterException(); else { if (field == "name") await channel.ModifyAsync(x => x.Name = modify); else await channel.ModifyAsync(x => x.Topic = modify); await ReplyAsync($"Attempted to change the `{field}` field to `{modify}`!"); } } } // Fun emote-like commands public class Hug : ModuleBase { [Command("hug"), Summary("For when people need virtual hugs :p")] public async Task hug([Summary("The user to hug!")] IUser user) { await ReplyAsync($"{Context.User.Mention} hugs {user.Mention}!"); await Context.Channel.SendFileAsync("assets/hug.gif"); } } public class Kiss : ModuleBase { [Command("kiss"), Summary("Kisses someone!")] public async Task kiss([Summary("The user to kiss!")] IUser user) { await ReplyAsync($"{Context.User.Mention} kisses {user.Mention}! awww c:"); await Context.Channel.SendFileAsync("assets/kiss_censor.gif"); } } public class Snuggle : ModuleBase { [Command("snuggle"), Summary("Snuggles with somebody!")] public async Task snuggle([Summary("The user to snuggle with!")] IUser user) { await ReplyAsync($"{Context.User.Mention} snuggles with {user.Mention}! How adorable! c:"); await Context.Channel.SendFileAsync("assets/snuggle.gif"); } } // Hateful emotes! :( public class Stab : ModuleBase { [Command("stab"), Summary("Virtually stabs somebody!")] public async Task stab([Summary("The user to stab!")] IUser user) { await ReplyAsync($"{Context.User.Mention} stabs {user.Mention} with a very pointy knife! :cry:"); } } // Bot Owner commands public class Shutdown : ModuleBase { [Command("shutdown"), Summary("Shuts the bot down!")] public async Task shutdown() { if (Context.User.Id != 199217346911404032) return; DiscordSocketClient cl = Context.Client as DiscordSocketClient; await cl.LogoutAsync(); await cl.StopAsync(); cl.Dispose(); } } public class GlobalGuildAnnouncement : ModuleBase { [Command("globalannounce"), Summary("Makes a global announcement to all connected guilds!")] [Alias("gannounce", "globalshout")] public async Task shout([Remainder, Summary("The message to annonce!")] string arg) { if (Context.User.Id != 199217346911404032) return; IEnumerable<IGuild> guilds = await Context.Client.GetGuildsAsync(); foreach (IGuild guild in guilds) { IEnumerable<ITextChannel> channels = await guild.GetTextChannelsAsync(); ITextChannel announcements = null; foreach (ITextChannel channel in channels) { if (channel.Name == "announcements") { announcements = channel; break; } } if (announcements != null) await announcements.SendMessageAsync($"Global announcement from Ophis (Bot owner):\n\n\"{arg}\""); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void OrDouble() { var test = new SimpleBinaryOpTest__OrDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__OrDouble { private const int VectorSize = 32; private const int ElementCount = VectorSize / sizeof(Double); private static Double[] _data1 = new Double[ElementCount]; private static Double[] _data2 = new Double[ElementCount]; private static Vector256<Double> _clsVar1; private static Vector256<Double> _clsVar2; private Vector256<Double> _fld1; private Vector256<Double> _fld2; private SimpleBinaryOpTest__DataTable<Double> _dataTable; static SimpleBinaryOpTest__OrDouble() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__OrDouble() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Double>(_data1, _data2, new Double[ElementCount], VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.Or( Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx.Or( Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx.Or( Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx).GetMethod(nameof(Avx.Or), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx).GetMethod(nameof(Avx.Or), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx).GetMethod(nameof(Avx.Or), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx.Or( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr); var result = Avx.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__OrDouble(); var result = Avx.Or(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx.Or(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Double> left, Vector256<Double> right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[ElementCount]; Double[] inArray2 = new Double[ElementCount]; Double[] outArray = new Double[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[ElementCount]; Double[] inArray2 = new Double[ElementCount]; Double[] outArray = new Double[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { if ((BitConverter.DoubleToInt64Bits(left[0]) | BitConverter.DoubleToInt64Bits(right[0])) != BitConverter.DoubleToInt64Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if ((BitConverter.DoubleToInt64Bits(left[i]) | BitConverter.DoubleToInt64Bits(right[i])) != BitConverter.DoubleToInt64Bits(result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.Or)}<Double>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: booking/reservations/complete_open_reservation.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Booking.Reservations { /// <summary>Holder for reflection information generated from booking/reservations/complete_open_reservation.proto</summary> public static partial class CompleteOpenReservationReflection { #region Descriptor /// <summary>File descriptor for booking/reservations/complete_open_reservation.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static CompleteOpenReservationReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjRib29raW5nL3Jlc2VydmF0aW9ucy9jb21wbGV0ZV9vcGVuX3Jlc2VydmF0", "aW9uLnByb3RvEiBob2xtcy50eXBlcy5ib29raW5nLnJlc2VydmF0aW9ucxoq", "cHJpbWl0aXZlL3BiX2luY2x1c2l2ZV9vcHNkYXRlX3JhbmdlLnByb3RvGi5i", "b29raW5nL2luZGljYXRvcnMvcmVzZXJ2YXRpb25faW5kaWNhdG9yLnByb3Rv", "Gixib29raW5nL3Jlc2VydmF0aW9ucy9yZXNlcnZhdGlvbl9zdGF0ZS5wcm90", "bxoWY3JtL2d1ZXN0cy9ndWVzdC5wcm90bxohc3VwcGx5L3Jvb21fdHlwZXMv", "cm9vbV90eXBlLnByb3RvGi9vcGVyYXRpb25zL2hvdXNla2VlcGluZy9ob3Vz", "ZWtlZXBpbmdfdGltZS5wcm90bxolb3BlcmF0aW9ucy9yb29tcy9yb29tX2lu", "ZGljYXRvci5wcm90bxo2Ym9va2luZy9pbmRpY2F0b3JzL2NhbmNlbGxhdGlv", "bl9wb2xpY3lfaW5kaWNhdG9yLnByb3RvGid0ZW5hbmN5X2NvbmZpZy9yZXNl", "cnZhdGlvbl9zb3VyY2UucHJvdG8ixQkKF0NvbXBsZXRlT3BlblJlc2VydmF0", "aW9uEkcKCWVudGl0eV9pZBgBIAEoCzI0LmhvbG1zLnR5cGVzLmJvb2tpbmcu", "aW5kaWNhdG9ycy5SZXNlcnZhdGlvbkluZGljYXRvchISCgpib29raW5nX2lk", "GAIgASgJEkEKBXN0YXRlGAMgASgOMjIuaG9sbXMudHlwZXMuYm9va2luZy5y", "ZXNlcnZhdGlvbnMuUmVzZXJ2YXRpb25TdGF0ZRIsCgVndWVzdBgEIAEoCzId", "LmhvbG1zLnR5cGVzLmNybS5ndWVzdHMuR3Vlc3QSQgoKZGF0ZV9yYW5nZRgF", "IAEoCzIuLmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5QYkluY2x1c2l2ZU9wc2Rh", "dGVSYW5nZRIVCg1udW1iZXJfYWR1bHRzGAYgASgFEhcKD251bWJlcl9jaGls", "ZHJlbhgHIAEoBRI6Cglyb29tX3R5cGUYCCABKAsyJy5ob2xtcy50eXBlcy5z", "dXBwbHkucm9vbV90eXBlcy5Sb29tVHlwZRI4ChFhZGRpdGlvbmFsX2d1ZXN0", "cxgJIAMoCzIdLmhvbG1zLnR5cGVzLmNybS5ndWVzdHMuR3Vlc3QSEgoKdGF4", "X2V4ZW1wdBgKIAEoCBJRChJoa190aW1lX3ByZWZlcmVuY2UYCyABKAsyNS5o", "b2xtcy50eXBlcy5vcGVyYXRpb25zLmhvdXNla2VlcGluZy5Ib3VzZWtlZXBp", "bmdUaW1lEiEKGXZlaGljbGVfcGxhdGVfaW5mb3JtYXRpb24YDCABKAkSJAoc", "Y3VycmVudF9vY2N1cGllZF9yb29tX251bWJlchgPIAEoCRJKChVjdXJyZW50", "X29jY3VwaWVkX3Jvb20YECABKAsyKy5ob2xtcy50eXBlcy5vcGVyYXRpb25z", "LnJvb21zLlJvb21JbmRpY2F0b3ISJQoddGVybWluYWxfb2NjdXBpZWRfcm9v", "bV9udW1iZXIYESABKAkSSwoWdGVybWluYWxfb2NjdXBpZWRfcm9vbRgSIAEo", "CzIrLmhvbG1zLnR5cGVzLm9wZXJhdGlvbnMucm9vbXMuUm9vbUluZGljYXRv", "chIhChlmaXJzdF9uaWdodF9hc3NpZ25lZF9yb29tGBMgASgJEhMKC2FjdGl2", "ZV90YWdzGBUgAygJEhoKEmNoYW5uZWxfbWFuYWdlcl9pZBgWIAEoCRIZChFz", "b3VyY2VfY2hhbm5lbF9pZBgXIAEoCRJYChNjYW5jZWxsYXRpb25fcG9saWN5", "GBggASgLMjsuaG9sbXMudHlwZXMuYm9va2luZy5pbmRpY2F0b3JzLkNhbmNl", "bGxhdGlvblBvbGljeUluZGljYXRvchIjChtyZXNlcnZhdGlvbl9pZF9mcm9t", "X2NoYW5uZWwYGSABKAkSKAogcnVzaF9yZXNlcnZhdGlvbl9pZF9mcm9tX2No", "YW5uZWwYGiABKAkSHwoXc291cmNlX2luZGlyZWN0X2NoYW5uZWwYGyABKAkS", "SQoScmVzZXJ2YXRpb25fc291cmNlGBwgASgLMi0uaG9sbXMudHlwZXMudGVu", "YW5jeV9jb25maWcuUmVzZXJ2YXRpb25Tb3VyY2VCOVoUYm9va2luZy9yZXNl", "cnZhdGlvbnOqAiBIT0xNUy5UeXBlcy5Cb29raW5nLlJlc2VydmF0aW9uc2IG", "cHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.PbInclusiveOpsdateRangeReflection.Descriptor, global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Reservations.ReservationStateReflection.Descriptor, global::HOLMS.Types.CRM.Guests.GuestReflection.Descriptor, global::HOLMS.Types.Supply.RoomTypes.RoomTypeReflection.Descriptor, global::HOLMS.Types.Operations.Housekeeping.HousekeepingTimeReflection.Descriptor, global::HOLMS.Types.Operations.Rooms.RoomIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicatorReflection.Descriptor, global::HOLMS.Types.TenancyConfig.ReservationSourceReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Reservations.CompleteOpenReservation), global::HOLMS.Types.Booking.Reservations.CompleteOpenReservation.Parser, new[]{ "EntityId", "BookingId", "State", "Guest", "DateRange", "NumberAdults", "NumberChildren", "RoomType", "AdditionalGuests", "TaxExempt", "HkTimePreference", "VehiclePlateInformation", "CurrentOccupiedRoomNumber", "CurrentOccupiedRoom", "TerminalOccupiedRoomNumber", "TerminalOccupiedRoom", "FirstNightAssignedRoom", "ActiveTags", "ChannelManagerId", "SourceChannelId", "CancellationPolicy", "ReservationIdFromChannel", "RushReservationIdFromChannel", "SourceIndirectChannel", "ReservationSource" }, null, null, null) })); } #endregion } #region Messages public sealed partial class CompleteOpenReservation : pb::IMessage<CompleteOpenReservation> { private static readonly pb::MessageParser<CompleteOpenReservation> _parser = new pb::MessageParser<CompleteOpenReservation>(() => new CompleteOpenReservation()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CompleteOpenReservation> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Booking.Reservations.CompleteOpenReservationReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CompleteOpenReservation() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CompleteOpenReservation(CompleteOpenReservation other) : this() { EntityId = other.entityId_ != null ? other.EntityId.Clone() : null; bookingId_ = other.bookingId_; state_ = other.state_; Guest = other.guest_ != null ? other.Guest.Clone() : null; DateRange = other.dateRange_ != null ? other.DateRange.Clone() : null; numberAdults_ = other.numberAdults_; numberChildren_ = other.numberChildren_; RoomType = other.roomType_ != null ? other.RoomType.Clone() : null; additionalGuests_ = other.additionalGuests_.Clone(); taxExempt_ = other.taxExempt_; HkTimePreference = other.hkTimePreference_ != null ? other.HkTimePreference.Clone() : null; vehiclePlateInformation_ = other.vehiclePlateInformation_; currentOccupiedRoomNumber_ = other.currentOccupiedRoomNumber_; CurrentOccupiedRoom = other.currentOccupiedRoom_ != null ? other.CurrentOccupiedRoom.Clone() : null; terminalOccupiedRoomNumber_ = other.terminalOccupiedRoomNumber_; TerminalOccupiedRoom = other.terminalOccupiedRoom_ != null ? other.TerminalOccupiedRoom.Clone() : null; firstNightAssignedRoom_ = other.firstNightAssignedRoom_; activeTags_ = other.activeTags_.Clone(); channelManagerId_ = other.channelManagerId_; sourceChannelId_ = other.sourceChannelId_; CancellationPolicy = other.cancellationPolicy_ != null ? other.CancellationPolicy.Clone() : null; reservationIdFromChannel_ = other.reservationIdFromChannel_; rushReservationIdFromChannel_ = other.rushReservationIdFromChannel_; sourceIndirectChannel_ = other.sourceIndirectChannel_; ReservationSource = other.reservationSource_ != null ? other.ReservationSource.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CompleteOpenReservation Clone() { return new CompleteOpenReservation(this); } /// <summary>Field number for the "entity_id" field.</summary> public const int EntityIdFieldNumber = 1; private global::HOLMS.Types.Booking.Indicators.ReservationIndicator entityId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Indicators.ReservationIndicator EntityId { get { return entityId_; } set { entityId_ = value; } } /// <summary>Field number for the "booking_id" field.</summary> public const int BookingIdFieldNumber = 2; private string bookingId_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string BookingId { get { return bookingId_; } set { bookingId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "state" field.</summary> public const int StateFieldNumber = 3; private global::HOLMS.Types.Booking.Reservations.ReservationState state_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Reservations.ReservationState State { get { return state_; } set { state_ = value; } } /// <summary>Field number for the "guest" field.</summary> public const int GuestFieldNumber = 4; private global::HOLMS.Types.CRM.Guests.Guest guest_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.CRM.Guests.Guest Guest { get { return guest_; } set { guest_ = value; } } /// <summary>Field number for the "date_range" field.</summary> public const int DateRangeFieldNumber = 5; private global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange dateRange_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange DateRange { get { return dateRange_; } set { dateRange_ = value; } } /// <summary>Field number for the "number_adults" field.</summary> public const int NumberAdultsFieldNumber = 6; private int numberAdults_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int NumberAdults { get { return numberAdults_; } set { numberAdults_ = value; } } /// <summary>Field number for the "number_children" field.</summary> public const int NumberChildrenFieldNumber = 7; private int numberChildren_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int NumberChildren { get { return numberChildren_; } set { numberChildren_ = value; } } /// <summary>Field number for the "room_type" field.</summary> public const int RoomTypeFieldNumber = 8; private global::HOLMS.Types.Supply.RoomTypes.RoomType roomType_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Supply.RoomTypes.RoomType RoomType { get { return roomType_; } set { roomType_ = value; } } /// <summary>Field number for the "additional_guests" field.</summary> public const int AdditionalGuestsFieldNumber = 9; private static readonly pb::FieldCodec<global::HOLMS.Types.CRM.Guests.Guest> _repeated_additionalGuests_codec = pb::FieldCodec.ForMessage(74, global::HOLMS.Types.CRM.Guests.Guest.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.CRM.Guests.Guest> additionalGuests_ = new pbc::RepeatedField<global::HOLMS.Types.CRM.Guests.Guest>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.CRM.Guests.Guest> AdditionalGuests { get { return additionalGuests_; } } /// <summary>Field number for the "tax_exempt" field.</summary> public const int TaxExemptFieldNumber = 10; private bool taxExempt_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool TaxExempt { get { return taxExempt_; } set { taxExempt_ = value; } } /// <summary>Field number for the "hk_time_preference" field.</summary> public const int HkTimePreferenceFieldNumber = 11; private global::HOLMS.Types.Operations.Housekeeping.HousekeepingTime hkTimePreference_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.Housekeeping.HousekeepingTime HkTimePreference { get { return hkTimePreference_; } set { hkTimePreference_ = value; } } /// <summary>Field number for the "vehicle_plate_information" field.</summary> public const int VehiclePlateInformationFieldNumber = 12; private string vehiclePlateInformation_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string VehiclePlateInformation { get { return vehiclePlateInformation_; } set { vehiclePlateInformation_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "current_occupied_room_number" field.</summary> public const int CurrentOccupiedRoomNumberFieldNumber = 15; private string currentOccupiedRoomNumber_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string CurrentOccupiedRoomNumber { get { return currentOccupiedRoomNumber_; } set { currentOccupiedRoomNumber_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "current_occupied_room" field.</summary> public const int CurrentOccupiedRoomFieldNumber = 16; private global::HOLMS.Types.Operations.Rooms.RoomIndicator currentOccupiedRoom_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.Rooms.RoomIndicator CurrentOccupiedRoom { get { return currentOccupiedRoom_; } set { currentOccupiedRoom_ = value; } } /// <summary>Field number for the "terminal_occupied_room_number" field.</summary> public const int TerminalOccupiedRoomNumberFieldNumber = 17; private string terminalOccupiedRoomNumber_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string TerminalOccupiedRoomNumber { get { return terminalOccupiedRoomNumber_; } set { terminalOccupiedRoomNumber_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "terminal_occupied_room" field.</summary> public const int TerminalOccupiedRoomFieldNumber = 18; private global::HOLMS.Types.Operations.Rooms.RoomIndicator terminalOccupiedRoom_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.Rooms.RoomIndicator TerminalOccupiedRoom { get { return terminalOccupiedRoom_; } set { terminalOccupiedRoom_ = value; } } /// <summary>Field number for the "first_night_assigned_room" field.</summary> public const int FirstNightAssignedRoomFieldNumber = 19; private string firstNightAssignedRoom_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string FirstNightAssignedRoom { get { return firstNightAssignedRoom_; } set { firstNightAssignedRoom_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "active_tags" field.</summary> public const int ActiveTagsFieldNumber = 21; private static readonly pb::FieldCodec<string> _repeated_activeTags_codec = pb::FieldCodec.ForString(170); private readonly pbc::RepeatedField<string> activeTags_ = new pbc::RepeatedField<string>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> ActiveTags { get { return activeTags_; } } /// <summary>Field number for the "channel_manager_id" field.</summary> public const int ChannelManagerIdFieldNumber = 22; private string channelManagerId_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ChannelManagerId { get { return channelManagerId_; } set { channelManagerId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "source_channel_id" field.</summary> public const int SourceChannelIdFieldNumber = 23; private string sourceChannelId_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string SourceChannelId { get { return sourceChannelId_; } set { sourceChannelId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "cancellation_policy" field.</summary> public const int CancellationPolicyFieldNumber = 24; private global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicator cancellationPolicy_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicator CancellationPolicy { get { return cancellationPolicy_; } set { cancellationPolicy_ = value; } } /// <summary>Field number for the "reservation_id_from_channel" field.</summary> public const int ReservationIdFromChannelFieldNumber = 25; private string reservationIdFromChannel_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ReservationIdFromChannel { get { return reservationIdFromChannel_; } set { reservationIdFromChannel_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "rush_reservation_id_from_channel" field.</summary> public const int RushReservationIdFromChannelFieldNumber = 26; private string rushReservationIdFromChannel_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string RushReservationIdFromChannel { get { return rushReservationIdFromChannel_; } set { rushReservationIdFromChannel_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "source_indirect_channel" field.</summary> public const int SourceIndirectChannelFieldNumber = 27; private string sourceIndirectChannel_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string SourceIndirectChannel { get { return sourceIndirectChannel_; } set { sourceIndirectChannel_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "reservation_source" field.</summary> public const int ReservationSourceFieldNumber = 28; private global::HOLMS.Types.TenancyConfig.ReservationSource reservationSource_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.TenancyConfig.ReservationSource ReservationSource { get { return reservationSource_; } set { reservationSource_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CompleteOpenReservation); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CompleteOpenReservation other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(EntityId, other.EntityId)) return false; if (BookingId != other.BookingId) return false; if (State != other.State) return false; if (!object.Equals(Guest, other.Guest)) return false; if (!object.Equals(DateRange, other.DateRange)) return false; if (NumberAdults != other.NumberAdults) return false; if (NumberChildren != other.NumberChildren) return false; if (!object.Equals(RoomType, other.RoomType)) return false; if(!additionalGuests_.Equals(other.additionalGuests_)) return false; if (TaxExempt != other.TaxExempt) return false; if (!object.Equals(HkTimePreference, other.HkTimePreference)) return false; if (VehiclePlateInformation != other.VehiclePlateInformation) return false; if (CurrentOccupiedRoomNumber != other.CurrentOccupiedRoomNumber) return false; if (!object.Equals(CurrentOccupiedRoom, other.CurrentOccupiedRoom)) return false; if (TerminalOccupiedRoomNumber != other.TerminalOccupiedRoomNumber) return false; if (!object.Equals(TerminalOccupiedRoom, other.TerminalOccupiedRoom)) return false; if (FirstNightAssignedRoom != other.FirstNightAssignedRoom) return false; if(!activeTags_.Equals(other.activeTags_)) return false; if (ChannelManagerId != other.ChannelManagerId) return false; if (SourceChannelId != other.SourceChannelId) return false; if (!object.Equals(CancellationPolicy, other.CancellationPolicy)) return false; if (ReservationIdFromChannel != other.ReservationIdFromChannel) return false; if (RushReservationIdFromChannel != other.RushReservationIdFromChannel) return false; if (SourceIndirectChannel != other.SourceIndirectChannel) return false; if (!object.Equals(ReservationSource, other.ReservationSource)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (entityId_ != null) hash ^= EntityId.GetHashCode(); if (BookingId.Length != 0) hash ^= BookingId.GetHashCode(); if (State != 0) hash ^= State.GetHashCode(); if (guest_ != null) hash ^= Guest.GetHashCode(); if (dateRange_ != null) hash ^= DateRange.GetHashCode(); if (NumberAdults != 0) hash ^= NumberAdults.GetHashCode(); if (NumberChildren != 0) hash ^= NumberChildren.GetHashCode(); if (roomType_ != null) hash ^= RoomType.GetHashCode(); hash ^= additionalGuests_.GetHashCode(); if (TaxExempt != false) hash ^= TaxExempt.GetHashCode(); if (hkTimePreference_ != null) hash ^= HkTimePreference.GetHashCode(); if (VehiclePlateInformation.Length != 0) hash ^= VehiclePlateInformation.GetHashCode(); if (CurrentOccupiedRoomNumber.Length != 0) hash ^= CurrentOccupiedRoomNumber.GetHashCode(); if (currentOccupiedRoom_ != null) hash ^= CurrentOccupiedRoom.GetHashCode(); if (TerminalOccupiedRoomNumber.Length != 0) hash ^= TerminalOccupiedRoomNumber.GetHashCode(); if (terminalOccupiedRoom_ != null) hash ^= TerminalOccupiedRoom.GetHashCode(); if (FirstNightAssignedRoom.Length != 0) hash ^= FirstNightAssignedRoom.GetHashCode(); hash ^= activeTags_.GetHashCode(); if (ChannelManagerId.Length != 0) hash ^= ChannelManagerId.GetHashCode(); if (SourceChannelId.Length != 0) hash ^= SourceChannelId.GetHashCode(); if (cancellationPolicy_ != null) hash ^= CancellationPolicy.GetHashCode(); if (ReservationIdFromChannel.Length != 0) hash ^= ReservationIdFromChannel.GetHashCode(); if (RushReservationIdFromChannel.Length != 0) hash ^= RushReservationIdFromChannel.GetHashCode(); if (SourceIndirectChannel.Length != 0) hash ^= SourceIndirectChannel.GetHashCode(); if (reservationSource_ != null) hash ^= ReservationSource.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (entityId_ != null) { output.WriteRawTag(10); output.WriteMessage(EntityId); } if (BookingId.Length != 0) { output.WriteRawTag(18); output.WriteString(BookingId); } if (State != 0) { output.WriteRawTag(24); output.WriteEnum((int) State); } if (guest_ != null) { output.WriteRawTag(34); output.WriteMessage(Guest); } if (dateRange_ != null) { output.WriteRawTag(42); output.WriteMessage(DateRange); } if (NumberAdults != 0) { output.WriteRawTag(48); output.WriteInt32(NumberAdults); } if (NumberChildren != 0) { output.WriteRawTag(56); output.WriteInt32(NumberChildren); } if (roomType_ != null) { output.WriteRawTag(66); output.WriteMessage(RoomType); } additionalGuests_.WriteTo(output, _repeated_additionalGuests_codec); if (TaxExempt != false) { output.WriteRawTag(80); output.WriteBool(TaxExempt); } if (hkTimePreference_ != null) { output.WriteRawTag(90); output.WriteMessage(HkTimePreference); } if (VehiclePlateInformation.Length != 0) { output.WriteRawTag(98); output.WriteString(VehiclePlateInformation); } if (CurrentOccupiedRoomNumber.Length != 0) { output.WriteRawTag(122); output.WriteString(CurrentOccupiedRoomNumber); } if (currentOccupiedRoom_ != null) { output.WriteRawTag(130, 1); output.WriteMessage(CurrentOccupiedRoom); } if (TerminalOccupiedRoomNumber.Length != 0) { output.WriteRawTag(138, 1); output.WriteString(TerminalOccupiedRoomNumber); } if (terminalOccupiedRoom_ != null) { output.WriteRawTag(146, 1); output.WriteMessage(TerminalOccupiedRoom); } if (FirstNightAssignedRoom.Length != 0) { output.WriteRawTag(154, 1); output.WriteString(FirstNightAssignedRoom); } activeTags_.WriteTo(output, _repeated_activeTags_codec); if (ChannelManagerId.Length != 0) { output.WriteRawTag(178, 1); output.WriteString(ChannelManagerId); } if (SourceChannelId.Length != 0) { output.WriteRawTag(186, 1); output.WriteString(SourceChannelId); } if (cancellationPolicy_ != null) { output.WriteRawTag(194, 1); output.WriteMessage(CancellationPolicy); } if (ReservationIdFromChannel.Length != 0) { output.WriteRawTag(202, 1); output.WriteString(ReservationIdFromChannel); } if (RushReservationIdFromChannel.Length != 0) { output.WriteRawTag(210, 1); output.WriteString(RushReservationIdFromChannel); } if (SourceIndirectChannel.Length != 0) { output.WriteRawTag(218, 1); output.WriteString(SourceIndirectChannel); } if (reservationSource_ != null) { output.WriteRawTag(226, 1); output.WriteMessage(ReservationSource); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (entityId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityId); } if (BookingId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(BookingId); } if (State != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) State); } if (guest_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Guest); } if (dateRange_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(DateRange); } if (NumberAdults != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(NumberAdults); } if (NumberChildren != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(NumberChildren); } if (roomType_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(RoomType); } size += additionalGuests_.CalculateSize(_repeated_additionalGuests_codec); if (TaxExempt != false) { size += 1 + 1; } if (hkTimePreference_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(HkTimePreference); } if (VehiclePlateInformation.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(VehiclePlateInformation); } if (CurrentOccupiedRoomNumber.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(CurrentOccupiedRoomNumber); } if (currentOccupiedRoom_ != null) { size += 2 + pb::CodedOutputStream.ComputeMessageSize(CurrentOccupiedRoom); } if (TerminalOccupiedRoomNumber.Length != 0) { size += 2 + pb::CodedOutputStream.ComputeStringSize(TerminalOccupiedRoomNumber); } if (terminalOccupiedRoom_ != null) { size += 2 + pb::CodedOutputStream.ComputeMessageSize(TerminalOccupiedRoom); } if (FirstNightAssignedRoom.Length != 0) { size += 2 + pb::CodedOutputStream.ComputeStringSize(FirstNightAssignedRoom); } size += activeTags_.CalculateSize(_repeated_activeTags_codec); if (ChannelManagerId.Length != 0) { size += 2 + pb::CodedOutputStream.ComputeStringSize(ChannelManagerId); } if (SourceChannelId.Length != 0) { size += 2 + pb::CodedOutputStream.ComputeStringSize(SourceChannelId); } if (cancellationPolicy_ != null) { size += 2 + pb::CodedOutputStream.ComputeMessageSize(CancellationPolicy); } if (ReservationIdFromChannel.Length != 0) { size += 2 + pb::CodedOutputStream.ComputeStringSize(ReservationIdFromChannel); } if (RushReservationIdFromChannel.Length != 0) { size += 2 + pb::CodedOutputStream.ComputeStringSize(RushReservationIdFromChannel); } if (SourceIndirectChannel.Length != 0) { size += 2 + pb::CodedOutputStream.ComputeStringSize(SourceIndirectChannel); } if (reservationSource_ != null) { size += 2 + pb::CodedOutputStream.ComputeMessageSize(ReservationSource); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CompleteOpenReservation other) { if (other == null) { return; } if (other.entityId_ != null) { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator(); } EntityId.MergeFrom(other.EntityId); } if (other.BookingId.Length != 0) { BookingId = other.BookingId; } if (other.State != 0) { State = other.State; } if (other.guest_ != null) { if (guest_ == null) { guest_ = new global::HOLMS.Types.CRM.Guests.Guest(); } Guest.MergeFrom(other.Guest); } if (other.dateRange_ != null) { if (dateRange_ == null) { dateRange_ = new global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange(); } DateRange.MergeFrom(other.DateRange); } if (other.NumberAdults != 0) { NumberAdults = other.NumberAdults; } if (other.NumberChildren != 0) { NumberChildren = other.NumberChildren; } if (other.roomType_ != null) { if (roomType_ == null) { roomType_ = new global::HOLMS.Types.Supply.RoomTypes.RoomType(); } RoomType.MergeFrom(other.RoomType); } additionalGuests_.Add(other.additionalGuests_); if (other.TaxExempt != false) { TaxExempt = other.TaxExempt; } if (other.hkTimePreference_ != null) { if (hkTimePreference_ == null) { hkTimePreference_ = new global::HOLMS.Types.Operations.Housekeeping.HousekeepingTime(); } HkTimePreference.MergeFrom(other.HkTimePreference); } if (other.VehiclePlateInformation.Length != 0) { VehiclePlateInformation = other.VehiclePlateInformation; } if (other.CurrentOccupiedRoomNumber.Length != 0) { CurrentOccupiedRoomNumber = other.CurrentOccupiedRoomNumber; } if (other.currentOccupiedRoom_ != null) { if (currentOccupiedRoom_ == null) { currentOccupiedRoom_ = new global::HOLMS.Types.Operations.Rooms.RoomIndicator(); } CurrentOccupiedRoom.MergeFrom(other.CurrentOccupiedRoom); } if (other.TerminalOccupiedRoomNumber.Length != 0) { TerminalOccupiedRoomNumber = other.TerminalOccupiedRoomNumber; } if (other.terminalOccupiedRoom_ != null) { if (terminalOccupiedRoom_ == null) { terminalOccupiedRoom_ = new global::HOLMS.Types.Operations.Rooms.RoomIndicator(); } TerminalOccupiedRoom.MergeFrom(other.TerminalOccupiedRoom); } if (other.FirstNightAssignedRoom.Length != 0) { FirstNightAssignedRoom = other.FirstNightAssignedRoom; } activeTags_.Add(other.activeTags_); if (other.ChannelManagerId.Length != 0) { ChannelManagerId = other.ChannelManagerId; } if (other.SourceChannelId.Length != 0) { SourceChannelId = other.SourceChannelId; } if (other.cancellationPolicy_ != null) { if (cancellationPolicy_ == null) { cancellationPolicy_ = new global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicator(); } CancellationPolicy.MergeFrom(other.CancellationPolicy); } if (other.ReservationIdFromChannel.Length != 0) { ReservationIdFromChannel = other.ReservationIdFromChannel; } if (other.RushReservationIdFromChannel.Length != 0) { RushReservationIdFromChannel = other.RushReservationIdFromChannel; } if (other.SourceIndirectChannel.Length != 0) { SourceIndirectChannel = other.SourceIndirectChannel; } if (other.reservationSource_ != null) { if (reservationSource_ == null) { reservationSource_ = new global::HOLMS.Types.TenancyConfig.ReservationSource(); } ReservationSource.MergeFrom(other.ReservationSource); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator(); } input.ReadMessage(entityId_); break; } case 18: { BookingId = input.ReadString(); break; } case 24: { state_ = (global::HOLMS.Types.Booking.Reservations.ReservationState) input.ReadEnum(); break; } case 34: { if (guest_ == null) { guest_ = new global::HOLMS.Types.CRM.Guests.Guest(); } input.ReadMessage(guest_); break; } case 42: { if (dateRange_ == null) { dateRange_ = new global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange(); } input.ReadMessage(dateRange_); break; } case 48: { NumberAdults = input.ReadInt32(); break; } case 56: { NumberChildren = input.ReadInt32(); break; } case 66: { if (roomType_ == null) { roomType_ = new global::HOLMS.Types.Supply.RoomTypes.RoomType(); } input.ReadMessage(roomType_); break; } case 74: { additionalGuests_.AddEntriesFrom(input, _repeated_additionalGuests_codec); break; } case 80: { TaxExempt = input.ReadBool(); break; } case 90: { if (hkTimePreference_ == null) { hkTimePreference_ = new global::HOLMS.Types.Operations.Housekeeping.HousekeepingTime(); } input.ReadMessage(hkTimePreference_); break; } case 98: { VehiclePlateInformation = input.ReadString(); break; } case 122: { CurrentOccupiedRoomNumber = input.ReadString(); break; } case 130: { if (currentOccupiedRoom_ == null) { currentOccupiedRoom_ = new global::HOLMS.Types.Operations.Rooms.RoomIndicator(); } input.ReadMessage(currentOccupiedRoom_); break; } case 138: { TerminalOccupiedRoomNumber = input.ReadString(); break; } case 146: { if (terminalOccupiedRoom_ == null) { terminalOccupiedRoom_ = new global::HOLMS.Types.Operations.Rooms.RoomIndicator(); } input.ReadMessage(terminalOccupiedRoom_); break; } case 154: { FirstNightAssignedRoom = input.ReadString(); break; } case 170: { activeTags_.AddEntriesFrom(input, _repeated_activeTags_codec); break; } case 178: { ChannelManagerId = input.ReadString(); break; } case 186: { SourceChannelId = input.ReadString(); break; } case 194: { if (cancellationPolicy_ == null) { cancellationPolicy_ = new global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicator(); } input.ReadMessage(cancellationPolicy_); break; } case 202: { ReservationIdFromChannel = input.ReadString(); break; } case 210: { RushReservationIdFromChannel = input.ReadString(); break; } case 218: { SourceIndirectChannel = input.ReadString(); break; } case 226: { if (reservationSource_ == null) { reservationSource_ = new global::HOLMS.Types.TenancyConfig.ReservationSource(); } input.ReadMessage(reservationSource_); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections; using System.Text; using System.Runtime.Remoting.Channels.Ipc; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Messaging; using System.Security; using System.Security.Permissions; namespace System.AddIn.Hosting { //This class exists only to do two security asserts, allowing us to use remoting with partial-trust app domains in external processes. internal class AddInIpcChannel : IpcChannel { ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IpcChannel..ctor(System.Collections.IDictionary,System.Runtime.Remoting.Channels.IClientChannelSinkProvider,System.Runtime.Remoting.Channels.IServerChannelSinkProvider)" /> ///</SecurityKernel> [System.Security.SecurityCritical] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2116:AptcaMethodsShouldOnlyCallAptcaMethods")] public AddInIpcChannel(IDictionary props, IClientChannelSinkProvider client, IServerChannelSinkProvider server) : base(props, new AddInBinaryClientFormaterSinkProvider(client), new AddInBinaryServerFormaterSinkProvider(server)) { } } internal class AddInBinaryServerFormaterSinkProvider : IServerChannelSinkProvider { internal IServerChannelSinkProvider _sinkProvider; public AddInBinaryServerFormaterSinkProvider(IServerChannelSinkProvider sink) { _sinkProvider = sink; } #region IServerChannelSinkProvider Members ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IServerChannelSinkProvider.CreateSink(System.Runtime.Remoting.Channels.IChannelReceiver):System.Runtime.Remoting.Channels.IServerChannelSink" /> ///</SecurityKernel> [System.Security.SecurityCritical] public IServerChannelSink CreateSink(IChannelReceiver channel) { return new AddInBinaryServerSink(_sinkProvider.CreateSink(channel)); } ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IServerChannelSinkProvider.GetChannelData(System.Runtime.Remoting.Channels.IChannelDataStore):System.Void" /> ///</SecurityKernel> [System.Security.SecurityCritical] public void GetChannelData(IChannelDataStore channelData) { _sinkProvider.GetChannelData(channelData); } public IServerChannelSinkProvider Next { ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IServerChannelSinkProvider.get_Next():System.Runtime.Remoting.Channels.IServerChannelSinkProvider" /> ///</SecurityKernel> [System.Security.SecurityCritical] get { return _sinkProvider.Next; } ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IServerChannelSinkProvider.set_Next(System.Runtime.Remoting.Channels.IServerChannelSinkProvider):System.Void" /> ///</SecurityKernel> [System.Security.SecurityCritical] set { _sinkProvider.Next = value; } } #endregion } internal class AddInBinaryServerSink : IServerChannelSink { #region IServerChannelSink Members private IServerChannelSink _sink; public AddInBinaryServerSink(IServerChannelSink sink) { _sink = sink; } ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IServerChannelSink.AsyncProcessResponse(System.Runtime.Remoting.Channels.IServerResponseChannelSinkStack,System.Object,System.Runtime.Remoting.Messaging.IMessage,System.Runtime.Remoting.Channels.ITransportHeaders,System.IO.Stream):System.Void" /> ///</SecurityKernel> [System.Security.SecurityCritical] public void AsyncProcessResponse(IServerResponseChannelSinkStack sinkStack, object state, IMessage msg, ITransportHeaders headers, System.IO.Stream stream) { _sink.AsyncProcessResponse(sinkStack, state, msg, headers, stream); } ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IServerChannelSink.GetResponseStream(System.Runtime.Remoting.Channels.IServerResponseChannelSinkStack,System.Object,System.Runtime.Remoting.Messaging.IMessage,System.Runtime.Remoting.Channels.ITransportHeaders):System.IO.Stream" /> ///</SecurityKernel> [System.Security.SecurityCritical] public System.IO.Stream GetResponseStream(IServerResponseChannelSinkStack sinkStack, object state, IMessage msg, ITransportHeaders headers) { return _sink.GetResponseStream(sinkStack, state, msg, headers); } public IServerChannelSink NextChannelSink { ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IServerChannelSink.get_NextChannelSink():System.Runtime.Remoting.Channels.IServerChannelSink" /> ///</SecurityKernel> [System.Security.SecurityCritical] get { return _sink.NextChannelSink; } } ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IServerChannelSink.ProcessMessage(System.Runtime.Remoting.Channels.IServerChannelSinkStack,System.Runtime.Remoting.Messaging.IMessage,System.Runtime.Remoting.Channels.ITransportHeaders,System.IO.Stream,System.Runtime.Remoting.Messaging.IMessage&amp;,System.Runtime.Remoting.Channels.ITransportHeaders&amp;,System.IO.Stream&amp;):System.Runtime.Remoting.Channels.ServerProcessing" /> ///<Asserts Name="Imperative: System.Security.Permissions.SecurityPermission" /> ///</SecurityKernel> [System.Security.SecurityCritical] public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, System.IO.Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { new System.Security.Permissions.SecurityPermission(SecurityPermissionFlag.SerializationFormatter | SecurityPermissionFlag.UnmanagedCode).Assert(); return _sink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); } #endregion #region IChannelSinkBase Members public IDictionary Properties { ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IChannelSinkBase.get_Properties():System.Collections.IDictionary" /> ///</SecurityKernel> [System.Security.SecurityCritical] get { return _sink.Properties; } } #endregion } internal class AddInBinaryClientFormaterSinkProvider : IClientChannelSinkProvider { IClientChannelSinkProvider _provider; public AddInBinaryClientFormaterSinkProvider(IClientChannelSinkProvider provider) { _provider = provider; } #region IClientChannelSinkProvider Members ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IClientChannelSinkProvider.CreateSink(System.Runtime.Remoting.Channels.IChannelSender,System.String,System.Object):System.Runtime.Remoting.Channels.IClientChannelSink" /> ///</SecurityKernel> [System.Security.SecurityCritical] public IClientChannelSink CreateSink(IChannelSender channel, string url, object remoteChannelData) { return new AddInBinaryClientFormaterSink(_provider.CreateSink(channel, url, remoteChannelData)); } public IClientChannelSinkProvider Next { ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IClientChannelSinkProvider.get_Next():System.Runtime.Remoting.Channels.IClientChannelSinkProvider" /> ///</SecurityKernel> [System.Security.SecurityCritical] get { return _provider.Next; } ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IClientChannelSinkProvider.set_Next(System.Runtime.Remoting.Channels.IClientChannelSinkProvider):System.Void" /> ///</SecurityKernel> [System.Security.SecurityCritical] set { _provider.Next = value; } } #endregion } internal class AddInBinaryClientFormaterSink : IClientChannelSink, IMessageSink { IClientChannelSink _sink; IMessageSink _mSink; public AddInBinaryClientFormaterSink(IClientChannelSink sink) { _sink = sink; _mSink = (IMessageSink)sink; } #region IClientChannelSink Members ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IClientChannelSink.AsyncProcessRequest(System.Runtime.Remoting.Channels.IClientChannelSinkStack,System.Runtime.Remoting.Messaging.IMessage,System.Runtime.Remoting.Channels.ITransportHeaders,System.IO.Stream):System.Void" /> ///</SecurityKernel> [System.Security.SecurityCritical] public void AsyncProcessRequest(IClientChannelSinkStack sinkStack, IMessage msg, ITransportHeaders headers, System.IO.Stream stream) { _sink.AsyncProcessRequest(sinkStack, msg, headers, stream); } ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IClientChannelSink.AsyncProcessResponse(System.Runtime.Remoting.Channels.IClientResponseChannelSinkStack,System.Object,System.Runtime.Remoting.Channels.ITransportHeaders,System.IO.Stream):System.Void" /> ///</SecurityKernel> [System.Security.SecurityCritical] public void AsyncProcessResponse(IClientResponseChannelSinkStack sinkStack, object state, ITransportHeaders headers, System.IO.Stream stream) { _sink.AsyncProcessResponse(sinkStack, state, headers, stream); } ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IClientChannelSink.GetRequestStream(System.Runtime.Remoting.Messaging.IMessage,System.Runtime.Remoting.Channels.ITransportHeaders):System.IO.Stream" /> ///</SecurityKernel> [System.Security.SecurityCritical] public System.IO.Stream GetRequestStream(IMessage msg, ITransportHeaders headers) { return _sink.GetRequestStream(msg, headers); } public IClientChannelSink NextChannelSink { ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IClientChannelSink.get_NextChannelSink():System.Runtime.Remoting.Channels.IClientChannelSink" /> ///</SecurityKernel> [System.Security.SecurityCritical] get { return _sink.NextChannelSink; } } ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IClientChannelSink.ProcessMessage(System.Runtime.Remoting.Messaging.IMessage,System.Runtime.Remoting.Channels.ITransportHeaders,System.IO.Stream,System.Runtime.Remoting.Channels.ITransportHeaders&amp;,System.IO.Stream&amp;):System.Void" /> ///</SecurityKernel> [System.Security.SecurityCritical] public void ProcessMessage(IMessage msg, ITransportHeaders requestHeaders, System.IO.Stream requestStream, out ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { _sink.ProcessMessage(msg, requestHeaders, requestStream, out responseHeaders,out responseStream); } #endregion #region IChannelSinkBase Members public IDictionary Properties { ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IChannelSinkBase.get_Properties():System.Collections.IDictionary" /> ///</SecurityKernel> [System.Security.SecurityCritical] get { return _sink.Properties; } } #endregion #region IMessageSink Members ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IMessageSink.AsyncProcessMessage(System.Runtime.Remoting.Messaging.IMessage,System.Runtime.Remoting.Messaging.IMessageSink):System.Runtime.Remoting.Messaging.IMessageCtrl" /> ///</SecurityKernel> [System.Security.SecurityCritical] public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink) { return _mSink.AsyncProcessMessage(msg, replySink); } public IMessageSink NextSink { ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IMessageSink.get_NextSink():System.Runtime.Remoting.Messaging.IMessageSink" /> ///</SecurityKernel> [System.Security.SecurityCritical] get { return _mSink.NextSink; } } ///<SecurityKernel Critical="True" Ring="0"> ///<SatisfiesLinkDemand Name="IMessageSink.SyncProcessMessage(System.Runtime.Remoting.Messaging.IMessage):System.Runtime.Remoting.Messaging.IMessage" /> ///<Asserts Name="Imperative: System.Security.Permissions.SecurityPermission" /> ///</SecurityKernel> [System.Security.SecurityCritical] public IMessage SyncProcessMessage(IMessage msg) { new System.Security.Permissions.SecurityPermission(SecurityPermissionFlag.SerializationFormatter | SecurityPermissionFlag.UnmanagedCode).Assert(); return _mSink.SyncProcessMessage(msg); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** Class: Privilege ** ** Purpose: Managed wrapper for NT privileges. ** ** Date: July 1, 2004 ** ===========================================================*/ using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Principal; using System.Threading; using CultureInfo = System.Globalization.CultureInfo; using FCall = System.Security.Principal.Win32; using Luid = Interop.Advapi32.LUID; namespace System.Security.AccessControl { #if false internal delegate void PrivilegedHelper(); #endif internal sealed class Privilege { [ThreadStatic] private static TlsContents t_tlsSlotData; private static Dictionary<Luid, string> privileges = new Dictionary<Luid, string>(); private static Dictionary<string, Luid> luids = new Dictionary<string, Luid>(); private static ReaderWriterLockSlim privilegeLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); private bool needToRevert = false; private bool initialState = false; private bool stateWasChanged = false; private Luid luid; private readonly Thread currentThread = Thread.CurrentThread; private TlsContents tlsContents = null; public const string CreateToken = "SeCreateTokenPrivilege"; public const string AssignPrimaryToken = "SeAssignPrimaryTokenPrivilege"; public const string LockMemory = "SeLockMemoryPrivilege"; public const string IncreaseQuota = "SeIncreaseQuotaPrivilege"; public const string UnsolicitedInput = "SeUnsolicitedInputPrivilege"; public const string MachineAccount = "SeMachineAccountPrivilege"; public const string TrustedComputingBase = "SeTcbPrivilege"; public const string Security = "SeSecurityPrivilege"; public const string TakeOwnership = "SeTakeOwnershipPrivilege"; public const string LoadDriver = "SeLoadDriverPrivilege"; public const string SystemProfile = "SeSystemProfilePrivilege"; public const string SystemTime = "SeSystemtimePrivilege"; public const string ProfileSingleProcess = "SeProfileSingleProcessPrivilege"; public const string IncreaseBasePriority = "SeIncreaseBasePriorityPrivilege"; public const string CreatePageFile = "SeCreatePagefilePrivilege"; public const string CreatePermanent = "SeCreatePermanentPrivilege"; public const string Backup = "SeBackupPrivilege"; public const string Restore = "SeRestorePrivilege"; public const string Shutdown = "SeShutdownPrivilege"; public const string Debug = "SeDebugPrivilege"; public const string Audit = "SeAuditPrivilege"; public const string SystemEnvironment = "SeSystemEnvironmentPrivilege"; public const string ChangeNotify = "SeChangeNotifyPrivilege"; public const string RemoteShutdown = "SeRemoteShutdownPrivilege"; public const string Undock = "SeUndockPrivilege"; public const string SyncAgent = "SeSyncAgentPrivilege"; public const string EnableDelegation = "SeEnableDelegationPrivilege"; public const string ManageVolume = "SeManageVolumePrivilege"; public const string Impersonate = "SeImpersonatePrivilege"; public const string CreateGlobal = "SeCreateGlobalPrivilege"; public const string TrustedCredentialManagerAccess = "SeTrustedCredManAccessPrivilege"; public const string ReserveProcessor = "SeReserveProcessorPrivilege"; // // This routine is a wrapper around a hashtable containing mappings // of privilege names to LUIDs // private static Luid LuidFromPrivilege(string privilege) { Luid luid; luid.LowPart = 0; luid.HighPart = 0; // // Look up the privilege LUID inside the cache // try { privilegeLock.EnterReadLock(); if (luids.ContainsKey(privilege)) { luid = luids[privilege]; privilegeLock.ExitReadLock(); } else { privilegeLock.ExitReadLock(); if (false == Interop.Advapi32.LookupPrivilegeValue(null, privilege, out luid)) { int error = Marshal.GetLastWin32Error(); if (error == Interop.Errors.ERROR_NOT_ENOUGH_MEMORY) { throw new OutOfMemoryException(); } else if (error == Interop.Errors.ERROR_ACCESS_DENIED) { throw new UnauthorizedAccessException(); } else if (error == Interop.Errors.ERROR_NO_SUCH_PRIVILEGE) { throw new ArgumentException( SR.Format(SR.Argument_InvalidPrivilegeName, privilege)); } else { System.Diagnostics.Debug.Fail($"LookupPrivilegeValue() failed with unrecognized error code {error}"); throw new InvalidOperationException(); } } privilegeLock.EnterWriteLock(); } } finally { if (privilegeLock.IsReadLockHeld) { privilegeLock.ExitReadLock(); } if (privilegeLock.IsWriteLockHeld) { if (!luids.ContainsKey(privilege)) { luids[privilege] = luid; privileges[luid] = privilege; } privilegeLock.ExitWriteLock(); } } return luid; } private sealed class TlsContents : IDisposable { private bool disposed = false; private int referenceCount = 1; private SafeTokenHandle threadHandle = new SafeTokenHandle(IntPtr.Zero); private bool isImpersonating = false; private static volatile SafeTokenHandle processHandle = new SafeTokenHandle(IntPtr.Zero); private static readonly object syncRoot = new object(); #region Constructor and Finalizer public TlsContents() { int error = 0; int cachingError = 0; bool success = true; if (processHandle.IsInvalid) { lock (syncRoot) { if (processHandle.IsInvalid) { SafeTokenHandle localProcessHandle; if (false == Interop.Advapi32.OpenProcessToken( Interop.Kernel32.GetCurrentProcess(), TokenAccessLevels.Duplicate, out localProcessHandle)) { cachingError = Marshal.GetLastWin32Error(); success = false; } processHandle = localProcessHandle; } } } try { // Make the sequence non-interruptible } finally { try { // // Open the thread token; if there is no thread token, get one from // the process token by impersonating self. // SafeTokenHandle threadHandleBefore = this.threadHandle; error = FCall.OpenThreadToken( TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges, WinSecurityContext.Process, out this.threadHandle); unchecked { error &= ~(int)0x80070000; } if (error != 0) { if (success == true) { this.threadHandle = threadHandleBefore; if (error != Interop.Errors.ERROR_NO_TOKEN) { success = false; } System.Diagnostics.Debug.Assert(this.isImpersonating == false, "Incorrect isImpersonating state"); if (success == true) { error = 0; if (false == Interop.Advapi32.DuplicateTokenEx( processHandle, TokenAccessLevels.Impersonate | TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges, IntPtr.Zero, Interop.Advapi32.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, System.Security.Principal.TokenType.TokenImpersonation, ref this.threadHandle)) { error = Marshal.GetLastWin32Error(); success = false; } } if (success == true) { error = FCall.SetThreadToken(this.threadHandle); unchecked { error &= ~(int)0x80070000; } if (error != 0) { success = false; } } if (success == true) { this.isImpersonating = true; } } else { error = cachingError; } } else { success = true; } } finally { if (!success) { Dispose(); } } } if (error == Interop.Errors.ERROR_NOT_ENOUGH_MEMORY) { throw new OutOfMemoryException(); } else if (error == Interop.Errors.ERROR_ACCESS_DENIED || error == Interop.Errors.ERROR_CANT_OPEN_ANONYMOUS) { throw new UnauthorizedAccessException(); } else if (error != 0) { System.Diagnostics.Debug.Fail($"WindowsIdentity.GetCurrentThreadToken() failed with unrecognized error code {error}"); throw new InvalidOperationException(); } } ~TlsContents() { if (!this.disposed) { Dispose(false); } } #endregion #region IDisposable implementation public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (this.disposed) return; if (disposing) { if (this.threadHandle != null) { this.threadHandle.Dispose(); this.threadHandle = null; } } if (this.isImpersonating) { Interop.Advapi32.RevertToSelf(); } this.disposed = true; } #endregion #region Reference Counting public void IncrementReferenceCount() { this.referenceCount++; } public int DecrementReferenceCount() { int result = --this.referenceCount; if (result == 0) { Dispose(); } return result; } public int ReferenceCountValue { get { return this.referenceCount; } } #endregion #region Properties public SafeTokenHandle ThreadHandle { get { return this.threadHandle; } } public bool IsImpersonating { get { return this.isImpersonating; } } #endregion } #region Constructors public Privilege(string privilegeName) { if (privilegeName == null) { throw new ArgumentNullException(nameof(privilegeName)); } this.luid = LuidFromPrivilege(privilegeName); } #endregion // // Finalizer simply ensures that the privilege was not leaked // ~Privilege() { System.Diagnostics.Debug.Assert(!this.needToRevert, "Must revert privileges that you alter!"); if (this.needToRevert) { Revert(); } } #region Public interface public void Enable() { this.ToggleState(true); } public bool NeedToRevert { get { return this.needToRevert; } } #endregion private unsafe void ToggleState(bool enable) { int error = 0; // // All privilege operations must take place on the same thread // if (!this.currentThread.Equals(Thread.CurrentThread)) { throw new InvalidOperationException(SR.InvalidOperation_MustBeSameThread); } // // This privilege was already altered and needs to be reverted before it can be altered again // if (this.needToRevert) { throw new InvalidOperationException(SR.InvalidOperation_MustRevertPrivilege); } // // Need to make this block of code non-interruptible so that it would preserve // consistency of thread oken state even in the face of catastrophic exceptions // try { // // The payload is entirely in the finally block // This is how we ensure that the code will not be // interrupted by catastrophic exceptions // } finally { try { // // Retrieve TLS state // this.tlsContents = t_tlsSlotData; if (this.tlsContents == null) { this.tlsContents = new TlsContents(); t_tlsSlotData = this.tlsContents; } else { this.tlsContents.IncrementReferenceCount(); } Interop.Advapi32.TOKEN_PRIVILEGE newState; newState.PrivilegeCount = 1; newState.Privileges.Luid = this.luid; newState.Privileges.Attributes = enable ? Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED : Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_DISABLED; Interop.Advapi32.TOKEN_PRIVILEGE previousState = new Interop.Advapi32.TOKEN_PRIVILEGE(); uint previousSize = 0; // // Place the new privilege on the thread token and remember the previous state. // if (!Interop.Advapi32.AdjustTokenPrivileges( this.tlsContents.ThreadHandle, false, &newState, (uint)sizeof(Interop.Advapi32.TOKEN_PRIVILEGE), &previousState, &previousSize)) { error = Marshal.GetLastWin32Error(); } else if (Interop.Errors.ERROR_NOT_ALL_ASSIGNED == Marshal.GetLastWin32Error()) { error = Interop.Errors.ERROR_NOT_ALL_ASSIGNED; } else { // // This is the initial state that revert will have to go back to // this.initialState = ((previousState.Privileges.Attributes & Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED) != 0); // // Remember whether state has changed at all // this.stateWasChanged = (this.initialState != enable); // // If we had to impersonate, or if the privilege state changed we'll need to revert // this.needToRevert = this.tlsContents.IsImpersonating || this.stateWasChanged; } } finally { if (!this.needToRevert) { this.Reset(); } } } if (error == Interop.Errors.ERROR_NOT_ALL_ASSIGNED) { throw new PrivilegeNotHeldException(privileges[this.luid]); } if (error == Interop.Errors.ERROR_NOT_ENOUGH_MEMORY) { throw new OutOfMemoryException(); } else if (error == Interop.Errors.ERROR_ACCESS_DENIED || error == Interop.Errors.ERROR_CANT_OPEN_ANONYMOUS) { throw new UnauthorizedAccessException(); } else if (error != 0) { System.Diagnostics.Debug.Fail($"AdjustTokenPrivileges() failed with unrecognized error code {error}"); throw new InvalidOperationException(); } } public unsafe void Revert() { int error = 0; if (!this.currentThread.Equals(Thread.CurrentThread)) { throw new InvalidOperationException(SR.InvalidOperation_MustBeSameThread); } if (!this.NeedToRevert) { return; } // // This code must be eagerly prepared and non-interruptible. // try { // // The payload is entirely in the finally block // This is how we ensure that the code will not be // interrupted by catastrophic exceptions // } finally { bool success = true; try { // // Only call AdjustTokenPrivileges if we're not going to be reverting to self, // on this Revert, since doing the latter obliterates the thread token anyway // if (this.stateWasChanged && (this.tlsContents.ReferenceCountValue > 1 || !this.tlsContents.IsImpersonating)) { Interop.Advapi32.TOKEN_PRIVILEGE newState; newState.PrivilegeCount = 1; newState.Privileges.Luid = this.luid; newState.Privileges.Attributes = (this.initialState ? Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED : Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_DISABLED); if (!Interop.Advapi32.AdjustTokenPrivileges( this.tlsContents.ThreadHandle, false, &newState, 0, null, null)) { error = Marshal.GetLastWin32Error(); success = false; } } } finally { if (success) { this.Reset(); } } } if (error == Interop.Errors.ERROR_NOT_ENOUGH_MEMORY) { throw new OutOfMemoryException(); } else if (error == Interop.Errors.ERROR_ACCESS_DENIED) { throw new UnauthorizedAccessException(); } else if (error != 0) { System.Diagnostics.Debug.Fail($"AdjustTokenPrivileges() failed with unrecognized error code {error}"); throw new InvalidOperationException(); } } #if false public static void RunWithPrivilege( string privilege, bool enabled, PrivilegedHelper helper ) { if ( helper == null ) { throw new ArgumentNullException( "helper" ); } Privilege p = new Privilege( privilege ); try { if (enabled) { p.Enable(); } else { p.Disable(); } helper(); } finally { p.Revert(); } } #endif private void Reset() { this.stateWasChanged = false; this.initialState = false; this.needToRevert = false; if (this.tlsContents != null) { if (0 == this.tlsContents.DecrementReferenceCount()) { this.tlsContents = null; t_tlsSlotData = null; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Signum.Engine.Basics; using Signum.Engine.DynamicQuery; using Signum.Engine.Maps; using Signum.Engine.Operations; using Signum.Entities; using Signum.Entities.DynamicQuery; using Signum.Utilities; using Signum.Utilities.ExpressionTrees; using Signum.Entities.Isolation; using Signum.Entities.Templating; using Signum.Engine.UserAssets; using Signum.Entities.SMS; using System.Globalization; namespace Signum.Engine.SMS { public interface ISMSModel { Entity UntypedEntity { get; } List<Filter> GetFilters(QueryDescription qd); Pagination GetPagination(); List<Order> GetOrders(QueryDescription queryDescription); } public abstract class SMSModel<T> : ISMSModel where T : Entity { public SMSModel(T entity) { this.Entity = entity; } public T Entity { get; set; } Entity ISMSModel.UntypedEntity { get { return Entity; } } public virtual List<Filter> GetFilters(QueryDescription qd) { var imp = qd.Columns.SingleEx(a => a.IsEntity).Implementations!.Value; if (imp.IsByAll && typeof(Entity).IsAssignableFrom(typeof(T)) || imp.Types.Contains(typeof(T))) return new List<Filter> { new FilterCondition(QueryUtils.Parse("Entity", qd, 0), FilterOperation.EqualTo, Entity.ToLite()) }; throw new InvalidOperationException($"Since {typeof(T).Name} is not in {imp}, it's necessary to override ${nameof(GetFilters)} in ${this.GetType().Name}"); } public virtual List<Order> GetOrders(QueryDescription queryDescription) { return new List<Order>(); } public virtual Pagination GetPagination() { return new Pagination.All(); } } public static class SMSModelLogic { class SMSModelInfo { public object QueryName; public Func<SMSTemplateEntity>? DefaultTemplateConstructor; public SMSModelInfo(object queryName) { QueryName = queryName; } } static ResetLazy<Dictionary<Lite<SMSModelEntity>, List<SMSTemplateEntity>>> SMSModelToTemplates = null!; static Dictionary<Type, SMSModelInfo> registeredModels = new Dictionary<Type, SMSModelInfo>(); static ResetLazy<Dictionary<Type, SMSModelEntity>> typeToEntity = null!; static ResetLazy<Dictionary<SMSModelEntity, Type>> entityToType = null!; public static void Start(SchemaBuilder sb) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { sb.Schema.Generating += Schema_Generating; sb.Schema.Synchronizing += Schema_Synchronizing; sb.Include<SMSModelEntity>() .WithQuery(() => model => new { Entity = model, model.Id, model.FullClassName, }); new Graph<SMSTemplateEntity>.ConstructFrom<SMSModelEntity>(SMSTemplateOperation.CreateSMSTemplateFromModel) { Construct = (model, _) => CreateDefaultTemplate(model) }.Register(); SMSModelToTemplates = sb.GlobalLazy(() => ( from et in Database.Query<SMSTemplateEntity>() where et.Model != null select KeyValuePair.Create(et.Model!.ToLite(), et)) .GroupToDictionary(), new InvalidateWith(typeof(SMSTemplateEntity), typeof(SMSModelEntity))); typeToEntity = sb.GlobalLazy(() => { var dbModels = Database.RetrieveAll<SMSModelEntity>(); return EnumerableExtensions.JoinRelaxed( dbModels, registeredModels.Keys, entity => entity.FullClassName, type => type.FullName!, (entity, type) => KeyValuePair.Create(type, entity), "caching " + nameof(SMSModelEntity)) .ToDictionary(); }, new InvalidateWith(typeof(SMSModelEntity))); sb.Schema.Initializing += () => typeToEntity.Load(); entityToType = sb.GlobalLazy(() => typeToEntity.Value.Inverse(), new InvalidateWith(typeof(SMSModelEntity))); } } static readonly string SMSModelReplacementKey = "SMSModel"; static SqlPreCommand? Schema_Synchronizing(Replacements replacements) { Table table = Schema.Current.Table<SMSModelEntity>(); Dictionary<string, SMSModelEntity> should = GenerateSMSModelEntities().ToDictionary(s => s.FullClassName); Dictionary<string, SMSModelEntity> old = Administrator.TryRetrieveAll<SMSModelEntity>(replacements).ToDictionary(c => c.FullClassName); replacements.AskForReplacements( old.Keys.ToHashSet(), should.Keys.ToHashSet(), SMSModelReplacementKey); Dictionary<string, SMSModelEntity> current = replacements.ApplyReplacementsToOld(old, SMSModelReplacementKey); using (replacements.WithReplacedDatabaseName()) return Synchronizer.SynchronizeScript(Spacing.Double, should, current, createNew: (tn, s) => table.InsertSqlSync(s), removeOld: (tn, c) => table.DeleteSqlSync(c, se => se.FullClassName == c.FullClassName), mergeBoth: (tn, s, c) => { var oldClassName = c.FullClassName; c.FullClassName = s.FullClassName; return table.UpdateSqlSync(c, se => se.FullClassName == c.FullClassName, comment: oldClassName); }); } public static void RegisterSMSModel<T>(Func<SMSTemplateEntity> defaultTemplateConstructor, object? queryName = null) where T : ISMSModel { RegisterSMSModel(typeof(T), defaultTemplateConstructor, queryName); } public static void RegisterSMSModel(Type model, Func<SMSTemplateEntity> defaultTemplateConstructor, object? queryName = null) { if (defaultTemplateConstructor == null) throw new ArgumentNullException(nameof(defaultTemplateConstructor)); registeredModels[model] = new SMSModelInfo(queryName ?? GetEntityType(model)) { DefaultTemplateConstructor = defaultTemplateConstructor, }; } public static Type GetEntityType(Type model) { var baseType = model.Follow(a => a.BaseType).FirstOrDefault(b => b.IsInstantiationOf(typeof(SMSModel<>))); if (baseType != null) { return baseType.GetGenericArguments()[0]; } throw new InvalidOperationException("Unknown queryName from {0}, set the argument queryName in RegisterSMSModel".FormatWith(model.TypeName())); } internal static List<SMSModelEntity> GenerateSMSModelEntities() { var list = (from type in registeredModels.Keys select new SMSModelEntity { FullClassName = type.FullName! }).ToList(); return list; } static SqlPreCommand? Schema_Generating() { Table table = Schema.Current.Table<SMSModelEntity>(); return (from ei in GenerateSMSModelEntities() select table.InsertSqlSync(ei)).Combine(Spacing.Simple); } public static SMSModelEntity GetSMSModelEntity<T>() where T : ISMSModel { return ToSMSModelEntity(typeof(T)); } public static SMSModelEntity GetSMSModelEntity(string fullClassName) { return typeToEntity.Value.Where(x => x.Key.FullName == fullClassName).FirstOrDefault().Value; } public static SMSModelEntity ToSMSModelEntity(Type smsModelType) { return typeToEntity.Value.GetOrThrow(smsModelType, "The SMSModel {0} was not registered"); } public static Type ToType(this SMSModelEntity smsModelEntity) { return entityToType.Value.GetOrThrow(smsModelEntity, "The SMSModel {0} was not registered"); } public static void SendSMS(this ISMSModel smsModel, CultureInfo? forceCultureInfo = null) { var result = smsModel.CreateSMSMessage(forceCultureInfo); SMSLogic.SendSMS(result); } public static void SendAsyncSMS(this ISMSModel smsModel, CultureInfo? forceCultureInfo = null) { var result = smsModel.CreateSMSMessage(forceCultureInfo); SMSLogic.SendAsyncSMS(result); } public static SMSMessageEntity CreateSMSMessage(this ISMSModel smsModel, CultureInfo? forceCultureInfo = null) { if (smsModel.UntypedEntity == null) throw new InvalidOperationException("Entity property not set on SMSModel"); using (IsolationEntity.Override((smsModel.UntypedEntity as Entity)?.TryIsolation())) { var smsModelEntity = ToSMSModelEntity(smsModel.GetType()); var template = GetDefaultTemplate(smsModelEntity); return SMSLogic.CreateSMSMessage(template.ToLite(), smsModel.UntypedEntity, smsModel, forceCultureInfo); } } private static SMSTemplateEntity GetDefaultTemplate(SMSModelEntity smsModelEntity) { var isAllowed = Schema.Current.GetInMemoryFilter<SMSTemplateEntity>(userInterface: false); var templates = SMSModelToTemplates.Value.TryGetC(smsModelEntity.ToLite()).EmptyIfNull(); if (templates.IsNullOrEmpty()) { using (ExecutionMode.Global()) using (OperationLogic.AllowSave<SMSTemplateEntity>()) using (Transaction tr = Transaction.ForceNew()) { var template = CreateDefaultTemplate(smsModelEntity); template.Save(); return tr.Commit(template); } } templates = templates.Where(isAllowed); return templates.Where(t => t.IsActive).SingleEx(() => "Active EmailTemplates for SystemEmail {0}".FormatWith(smsModelEntity)); } internal static SMSTemplateEntity CreateDefaultTemplate(SMSModelEntity smsModel) { SMSModelInfo info = registeredModels.GetOrThrow(entityToType.Value.GetOrThrow(smsModel)); if (info.DefaultTemplateConstructor == null) throw new InvalidOperationException($"No EmailTemplate for {smsModel} found and DefaultTemplateConstructor = null"); SMSTemplateEntity template = info.DefaultTemplateConstructor.Invoke(); if (template.Name == null) template.Name = smsModel.FullClassName; template.Model = smsModel; template.Query = QueryLogic.GetQueryEntity(info.QueryName); template.ParseData(QueryLogic.Queries.QueryDescription(info.QueryName)); return template; } public static void GenerateAllTemplates() { foreach (var smsModelType in registeredModels.Keys) { var smsModelEntity = ToSMSModelEntity(smsModelType); var template = Database.Query<SMSTemplateEntity>().SingleOrDefaultEx(t => t.Model == smsModelEntity); if (template == null) { template = CreateDefaultTemplate(smsModelEntity); using (ExecutionMode.Global()) using (OperationLogic.AllowSave<SMSTemplateEntity>()) template.Save(); } } } public static bool RequiresExtraParameters(SMSModelEntity smsModelEntity) { return GetEntityConstructor(entityToType.Value.GetOrThrow(smsModelEntity)) == null; } internal static bool HasDefaultTemplateConstructor(SMSModelEntity smsModelEntity) { SMSModelInfo info = registeredModels.GetOrThrow(smsModelEntity.ToType()); return info.DefaultTemplateConstructor != null; } public static ISMSModel CreateModel(SMSModelEntity model, ModifiableEntity? entity) { return (ISMSModel)SMSModelLogic.GetEntityConstructor(model.ToType())!.Invoke(new[] { entity }); } public static ConstructorInfo? GetEntityConstructor(Type smsModel) { var entityType = GetEntityType(smsModel); return (from ci in smsModel.GetConstructors() let pi = ci.GetParameters().Only() where pi != null && pi.ParameterType == entityType select ci).SingleOrDefaultEx(); } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Castle.MicroKernel.Registration; using Glass.Mapper.Configuration; using Glass.Mapper.Pipelines.ObjectConstruction; using Glass.Mapper.Sc.CastleWindsor.Pipelines.ObjectConstruction; using NSubstitute; using NUnit.Framework; namespace Glass.Mapper.Sc.CastleWindsor.Tests.Pipelines.ObjectConstruction { [TestFixture] public class WindsorConstructionFixture { [Test] public void Execute_RequestInstanceOfClass_ReturnsInstance() { //Assign var task = new WindsorConstruction(); var context = Context.Create(DependencyResolver.CreateStandardResolver()); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof (StubClass); var typeCreationContext = Substitute.For<AbstractTypeCreationContext>(); var service = Substitute.For<AbstractService>(); var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig, service); Assert.IsNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNotNull(args.Result); Assert.IsTrue(args.Result is StubClass); } [Test] public void Execute_ResultAlreadySet_NoInstanceCreated() { //Assign var task = new WindsorConstruction(); var context = Context.Create(DependencyResolver.CreateStandardResolver()); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof(StubClass); var args = new ObjectConstructionArgs(context, null, typeConfig , null); var result = new StubClass2(); args.Result = result; Assert.IsNotNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNotNull(args.Result); Assert.IsTrue(args.Result is StubClass2); Assert.AreEqual(result, args.Result); } [Test] public void Execute_RequestInstanceOfInterface_ReturnsNullInterfaceNotSupported() { //Assign var task = new WindsorConstruction(); var context = Context.Create(DependencyResolver.CreateStandardResolver()); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof(StubInterface); var typeCreationContext = Substitute.For<AbstractTypeCreationContext>(); var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig , null); Assert.IsNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNull(args.Result); } [Test] public void Execute_RequestInstanceOfClassWithService_ReturnsInstanceWithService() { //Assign var task = new WindsorConstruction(); var resolver = DependencyResolver.CreateStandardResolver() as DependencyResolver; var context = Context.Create(resolver); var service = Substitute.For<AbstractService>(); resolver.Container.Register( Component.For<StubServiceInterface>().ImplementedBy<StubService>().LifestyleTransient() ); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof(StubClassWithService); var typeCreationContext = Substitute.For<AbstractTypeCreationContext>(); var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig , service); Assert.IsNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNotNull(args.Result); Assert.IsTrue(args.Result is StubClassWithService); var stub = args.Result as StubClassWithService; Assert.IsNotNull(stub.Service); Assert.IsTrue(stub.Service is StubService); } [Test] public void Execute_RequestInstanceOfClassWithParameters_NoInstanceReturnedDoesntHandle() { //Assign var task = new WindsorConstruction(); var context = Context.Create(DependencyResolver.CreateStandardResolver()); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof(StubClassWithParameters); string param1 = "test param1"; int param2 = 450; double param3 = 489; string param4 = "param4 test"; var typeCreationContext = Substitute.For<AbstractTypeCreationContext>(); typeCreationContext.ConstructorParameters = new object[]{param1, param2, param3, param4}; var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig , null); Assert.IsNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNull(args.Result); } #region Stubs public class StubClass { } public class StubClass2 { } public interface StubInterface { } public interface StubServiceInterface { } public class StubService: StubServiceInterface { } public class StubClassWithService { public StubServiceInterface Service { get; set; } public virtual string Field1 { get; set; } public virtual StubClassWithService Field2 { get; set; } public StubClassWithService(StubServiceInterface service) { Service = service; } } public class StubClassWithParameters { public string Param1 { get; set; } public int Param2 { get; set; } public double Param3 { get; set; } public string Param4 { get; set; } public StubClassWithParameters( string param1, int param2, double param3, string param4 ) { Param1 = param1; Param2 = param2; Param3 = param3; Param4 = param4; } } #endregion } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using System.Collections.Generic; using System; using System.Linq; namespace UIWidgets { /// <summary> /// TreeViewCustom. /// </summary> public class TreeViewCustom<TComponent,TItem> : ListViewCustom<TComponent,ListNode<TItem>> where TComponent : ListViewItem { /// <summary> /// NodeEvent. /// </summary> [Serializable] public class NodeEvent : UnityEvent<TreeNode<TItem>> { } [SerializeField] IObservableList<TreeNode<TItem>> nodes = new ObservableList<TreeNode<TItem>>(); /// <summary> /// Gets or sets the nodes. /// </summary> /// <value>The nodes.</value> public IObservableList<TreeNode<TItem>> Nodes { get { return nodes; } set { if (nodes!=null) { nodes.OnChange -= NodesChanged; nodes.OnChange -= CollectionChanged; } nodes = value; RootNode.Nodes = value; SetScrollValue(0f); Refresh(); if (nodes!=null) { nodes.OnChange += NodesChanged; nodes.OnChange += CollectionChanged; CollectionChanged(); } } } /// <summary> /// Gets the selected node. /// </summary> /// <value>The selected node.</value> public TreeNode<TItem> SelectedNode { get { var n = SelectedNodes.Count; if (n > 0) { return SelectedNodes[n - 1]; } return null; } } /// <summary> /// NodeToggle event. /// </summary> public NodeEvent NodeToggle = new NodeEvent(); /// <summary> /// NodeSelected event. /// </summary> public NodeEvent NodeSelected = new NodeEvent(); /// <summary> /// NodeDeselected event. /// </summary> public NodeEvent NodeDeselected = new NodeEvent(); /// <summary> /// Gets or sets the selected nodes. /// </summary> /// <value>The selected nodes.</value> public List<TreeNode<TItem>> SelectedNodes { get { if (SelectedIndex==-1) { return new List<TreeNode<TItem>>(); } return SelectedIndicies.Convert(x => NodesList[x].Node); } set { SelectedIndicies = Nodes2Indicies(value); } } /// <summary> /// Opened nodes converted to list. /// </summary> protected ObservableList<ListNode<TItem>> NodesList = new ObservableList<ListNode<TItem>>(); /// <summary> /// Awake this instance. /// </summary> protected override void Awake() { Start(); } [System.NonSerialized] bool isStartedTreeViewCustom = false; TreeNode<TItem> rootNode; /// <summary> /// Gets the root node. /// </summary> /// <value>The root node.</value> protected TreeNode<TItem> RootNode { get { return rootNode; } } /// <summary> /// Start this instance. /// </summary> public override void Start() { if (isStartedTreeViewCustom) { return ; } isStartedTreeViewCustom = true; rootNode = new TreeNode<TItem>(default(TItem)); setContentSizeFitter = false; base.Start(); Refresh(); OnSelect.AddListener(OnSelectNode); OnDeselect.AddListener(OnDeselectNode); KeepSelection = true; DataSource = NodesList; } void CollectionChanged() { if (nodes==null) { return ; } //nodes.ForEach(SetParent); } void SetParent(TreeNode<TItem> node) { if (node.Parent!=RootNode) { node.Parent = RootNode; } } /// <summary> /// Determines whether this instance can optimize. /// </summary> /// <returns><c>true</c> if this instance can optimize; otherwise, <c>false</c>.</returns> protected override bool CanOptimize() { var scrollRectSpecified = scrollRect!=null; var containerSpecified = Container!=null; var currentLayout = containerSpecified ? (layout ?? Container.GetComponent<LayoutGroup>()) : null; var validLayout = currentLayout is EasyLayout.EasyLayout; return scrollRectSpecified && validLayout; } /// <summary> /// Convert nodes tree to list. /// </summary> /// <returns>The list.</returns> /// <param name="sourceNodes">Source nodes.</param> /// <param name="depth">Depth.</param> /// <param name="list">List.</param> protected virtual int Nodes2List(IObservableList<TreeNode<TItem>> sourceNodes, int depth, ObservableList<ListNode<TItem>> list) { var added_nodes = 0; foreach (var node in sourceNodes) { if (!node.IsVisible) { continue ; } list.Add(new ListNode<TItem>(node, depth)); if ((node.IsExpanded) && (node.Nodes!=null) && (node.Nodes.Count > 0)) { var used = Nodes2List(node.Nodes, depth + 1, list); node.UsedNodesCount = used; } else { node.UsedNodesCount = 0; } added_nodes += 1; } return added_nodes; } /// <summary> /// Raises the toggle node event. /// </summary> /// <param name="index">Index.</param> protected void OnToggleNode(int index) { ToggleNode(index); NodeToggle.Invoke(NodesList[index].Node); } /// <summary> /// Raises the select node event. /// </summary> /// <param name="index">Index.</param> /// <param name="component">Component.</param> protected void OnSelectNode(int index, ListViewItem component) { NodeSelected.Invoke(NodesList[index].Node); } /// <summary> /// Raises the deselect node event. /// </summary> /// <param name="index">Index.</param> /// <param name="component">Component.</param> protected void OnDeselectNode(int index, ListViewItem component) { NodeDeselected.Invoke(NodesList[index].Node); } /// <summary> /// Toggles the node. /// </summary> /// <param name="index">Index.</param> protected void ToggleNode(int index) { var node = NodesList[index]; if (node.Node.Nodes==null) { return ; } NodesList.BeginUpdate(); if (node.Node.IsExpanded) { var range = node.Node.AllUsedNodesCount; if (range > 0) { MoveSelectedIndiciesUp(index, range); NodesList.RemoveRange(index + 1, range); } node.Node.PauseObservation = true; node.Node.IsExpanded = false; node.Node.PauseObservation = false; node.Node.UsedNodesCount = 0; } else { var sub_list = new ObservableList<ListNode<TItem>>(); var used = Nodes2List(node.Node.Nodes, node.Depth + 1, sub_list); MoveSelectedIndiciesDown(index, sub_list.Count); NodesList.InsertRange(index + 1, sub_list); node.Node.PauseObservation = true; node.Node.IsExpanded = true; node.Node.PauseObservation = false; node.Node.UsedNodesCount = used; } NodesList.EndUpdate(); } /// <summary> /// Moves the selected indicies up. /// </summary> /// <param name="index">Index.</param> /// <param name="range">Range.</param> void MoveSelectedIndiciesUp(int index, int range) { var start = index + 1; var end = start + range; //deselect indicies in removed range SelectedIndicies.Where(x => start <= x && x <= end).ForEach(Deselect); var remove_indicies = SelectedIndicies.Where(x => x > end).ToList(); var add_indicies = remove_indicies.Select(x => x - range).ToList(); SilentDeselect(remove_indicies); SilentSelect(add_indicies); } /// <summary> /// Moves the selected indicies down. /// </summary> /// <param name="index">Index.</param> /// <param name="range">Range.</param> void MoveSelectedIndiciesDown(int index, int range) { var start = index + 1; var end = start + range; var remove_indicies = SelectedIndicies.Where(x => start <= x && x <= end).ToList(); var add_indicies = remove_indicies.Convert(x => x + range); SilentDeselect(remove_indicies); SilentSelect(add_indicies); } /// <summary> /// Get indicies of specified nodes. /// </summary> /// <returns>The indicies.</returns> /// <param name="targetNodes">Target nodes.</param> protected List<int> Nodes2Indicies(IEnumerable<TreeNode<TItem>> targetNodes) { return targetNodes.Select(x => NodesList.FindIndex(y => x==y.Node)).Where(i => i!=-1).ToList(); } /// <summary> /// Process changes in node data. /// </summary> protected virtual void NodesChanged() { Refresh(); } /// <summary> /// Refresh this instance. /// </summary> public virtual void Refresh() { if (nodes==null) { NodesList.Clear(); return ; } NodesList.BeginUpdate(); var selected_nodes = SelectedNodes; NodesList.Clear(); Nodes2List(nodes, 0, NodesList); if (selected_nodes!=null) { SilentDeselect(SelectedIndicies); var indicies = Nodes2Indicies(selected_nodes); SilentSelect(indicies); } NodesList.EndUpdate(); } /// <summary> /// Clear items of this instance. /// </summary> public override void Clear() { nodes.Clear(); SetScrollValue(0f); } /// <summary> /// [Not supported for TreeView] Add the specified item. /// </summary> /// <param name="item">Item.</param> /// <returns>Index of added item.</returns> [Obsolete("Not supported for TreeView", true)] public int Add(TItem item) { return -1; } /// <summary> /// [Not supported for TreeView] Remove the specified item. /// </summary> /// <param name="item">Item.</param> /// <returns>Index of removed TItem.</returns> [Obsolete("Not supported for TreeView", true)] public int Remove(TItem item) { return -1; } /// <summary> /// [Not supported for TreeView] Remove item by specifieitemsex. /// </summary> /// <returns>Index of removed item.</returns> /// <param name="index">Index.</param> public override void Remove(int index) { throw new NotSupportedException("Not supported for TreeView."); } /// <summary> /// [Not supported for TreeView] Set the specified item. /// </summary> /// <param name="item">Item.</param> /// <param name="allowDuplicate">If set to <c>true</c> allow duplicate.</param> /// <returns>Index of item.</returns> [Obsolete("Not supported for TreeView", true)] public int Set(TItem item, bool allowDuplicate=true) { return -1; } /// <summary> /// Removes first elements that match the conditions defined by the specified predicate. /// </summary> /// <param name="match">Match.</param> /// <returns>true if item is successfully removed; otherwise, false.</returns> public bool Remove(Predicate<TreeNode<TItem>> match) { var index = FindIndex(nodes, match); if (index!=-1) { nodes.RemoveAt(index); return true; } foreach (var node in nodes) { if (node.Nodes==null) { continue ; } if (Remove(node.Nodes, match)) { return true; } } return false; } bool Remove(IObservableList<TreeNode<TItem>> nodes, Predicate<TreeNode<TItem>> match) { var index = FindIndex(nodes, match); if (index!=-1) { nodes.RemoveAt(index); return true; } foreach (var node in nodes) { if (node.Nodes==null) { continue ; } if (Remove(node.Nodes, match)) { return true; } } return false; } int FindIndex(IObservableList<TreeNode<TItem>> nodes, Predicate<TreeNode<TItem>> match) { if (nodes is ObservableList<TreeNode<TItem>>) { return (nodes as ObservableList<TreeNode<TItem>>).FindIndex(match); } for (var i = 0; i < nodes.Count; i++) { if (match(nodes[i])) { return i; } } return -1; } /// <summary> /// Sets component data with specified item. /// </summary> /// <param name="component">Component.</param> /// <param name="item">Item.</param> protected override void SetData(TComponent component, ListNode<TItem> item) { } /// <summary> /// Removes the callback. /// </summary> /// <param name="item">Item.</param> /// <param name="index">Index.</param> protected override void RemoveCallback(ListViewItem item, int index) { if (item!=null) { (item as TreeViewComponentBase<TItem>).ToggleEvent.RemoveListener(OnToggleNode); } base.RemoveCallback(item, index); } /// <summary> /// Adds the callback. /// </summary> /// <param name="item">Item.</param> /// <param name="index">Index.</param> protected override void AddCallback(ListViewItem item, int index) { base.AddCallback(item, index); (item as TreeViewComponentBase<TItem>).ToggleEvent.AddListener(OnToggleNode); } /// <summary> /// This function is called when the MonoBehaviour will be destroyed. /// </summary> protected override void OnDestroy() { OnSelect.RemoveListener(OnSelectNode); OnDeselect.RemoveListener(OnDeselectNode); if (Nodes!=null) { Nodes.Dispose(); //Nodes = null; } base.OnDestroy(); } } }
using System; using System.Runtime.InteropServices; using System.Security; using BulletSharp.Math; namespace BulletSharp { public class DbvtAabbMm { internal IntPtr _native; internal DbvtAabbMm(IntPtr native) { _native = native; } public int Classify(Vector3 n, float o, int s) { return btDbvtAabbMm_Classify(_native, ref n, o, s); } public bool Contain(DbvtAabbMm a) { return btDbvtAabbMm_Contain(_native, a._native); } public void Expand(Vector3 e) { btDbvtAabbMm_Expand(_native, ref e); } /* public static DbvtAabbMm FromCE(Vector3 c, Vector3 e) { return btDbvtAabbMm_FromCE(ref c, ref e); } public static DbvtAabbMm FromCR(Vector3 c, float r) { return btDbvtAabbMm_FromCR(ref c, r); } public static DbvtAabbMm FromMM(Vector3 mi, Vector3 mx) { return btDbvtAabbMm_FromMM(ref mi, ref mx); } public static DbvtAabbMm FromPoints(Vector3 ppts, int n) { return btDbvtAabbMm_FromPoints(ref ppts, n); } public static DbvtAabbMm FromPoints(Vector3 pts, int n) { return btDbvtAabbMm_FromPoints2(ref pts, n); } */ public float ProjectMinimum(Vector3 v, uint signs) { return btDbvtAabbMm_ProjectMinimum(_native, ref v, signs); } public void SignedExpand(Vector3 e) { btDbvtAabbMm_SignedExpand(_native, ref e); } public Vector3 Center { get { Vector3 value; btDbvtAabbMm_Center(_native, out value); return value; } } public Vector3 Extents { get { Vector3 value; btDbvtAabbMm_Extents(_native, out value); return value; } } public Vector3 Lengths { get { Vector3 value; btDbvtAabbMm_Lengths(_native, out value); return value; } } public Vector3 Maxs { get { Vector3 value; btDbvtAabbMm_Maxs(_native, out value); return value; } } public Vector3 Mins { get { Vector3 value; btDbvtAabbMm_Mins(_native, out value); return value; } } public Vector3 TMaxs { get { Vector3 value; btDbvtAabbMm_tMaxs(_native, out value); return value; } } public Vector3 TMins { get { Vector3 value; btDbvtAabbMm_tMins(_native, out value); return value; } } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvtAabbMm_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvtAabbMm_Center(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btDbvtAabbMm_Classify(IntPtr obj, [In] ref Vector3 n, float o, int s); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btDbvtAabbMm_Contain(IntPtr obj, IntPtr a); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvtAabbMm_Expand(IntPtr obj, [In] ref Vector3 e); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvtAabbMm_Extents(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvtAabbMm_FromCE([In] ref Vector3 c, [In] ref Vector3 e); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvtAabbMm_FromCR([In] ref Vector3 c, float r); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvtAabbMm_FromMM([In] ref Vector3 mi, [In] ref Vector3 mx); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvtAabbMm_FromPoints([In] ref Vector3 ppts, int n); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvtAabbMm_FromPoints2([In] ref Vector3 pts, int n); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvtAabbMm_Lengths(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvtAabbMm_Maxs(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvtAabbMm_Mins(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btDbvtAabbMm_ProjectMinimum(IntPtr obj, [In] ref Vector3 v, uint signs); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvtAabbMm_SignedExpand(IntPtr obj, [In] ref Vector3 e); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvtAabbMm_tMaxs(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvtAabbMm_tMins(IntPtr obj, [Out] out Vector3 value); } public class DbvtNode { internal IntPtr _native; internal DbvtNode(IntPtr native) { _native = native; } /* public DbvtNodePtrArray Childs { get { return btDbvtNode_getChilds(_native); } } */ public IntPtr Data { get { return btDbvtNode_getData(_native); } set { btDbvtNode_setData(_native, value); } } public int DataAsInt { get { return btDbvtNode_getDataAsInt(_native); } set { btDbvtNode_setDataAsInt(_native, value); } } public bool Isinternal { get { return btDbvtNode_isinternal(_native); } } public bool Isleaf { get { return btDbvtNode_isleaf(_native); } } public DbvtNode Parent { get { IntPtr ptr = btDbvtNode_getParent(_native); return (ptr != IntPtr.Zero) ? new DbvtNode(ptr) : null; } set { btDbvtNode_setParent(_native, (value != null) ? value._native : IntPtr.Zero); } } public DbvtVolume Volume { get { IntPtr ptr = btDbvtNode_getVolume(_native); return (ptr != IntPtr.Zero) ? new DbvtVolume(ptr) : null; } } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvtNode_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvtNode_getChilds(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvtNode_getData(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btDbvtNode_getDataAsInt(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvtNode_getParent(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvtNode_getVolume(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btDbvtNode_isinternal(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btDbvtNode_isleaf(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvtNode_setData(IntPtr obj, IntPtr value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvtNode_setDataAsInt(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvtNode_setParent(IntPtr obj, IntPtr value); } public class DbvtVolume : DbvtAabbMm { internal DbvtVolume(IntPtr native) : base(native) { } } public class Dbvt : IDisposable { public class IClone : IDisposable { internal IntPtr _native; internal IClone(IntPtr native) { _native = native; } public IClone() { _native = btDbvt_IClone_new(); } public void CloneLeaf(DbvtNode __unnamed0) { btDbvt_IClone_CloneLeaf(_native, __unnamed0._native); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { btDbvt_IClone_delete(_native); _native = IntPtr.Zero; } } ~IClone() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvt_IClone_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_IClone_CloneLeaf(IntPtr obj, IntPtr __unnamed0); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_IClone_delete(IntPtr obj); } public class ICollide : IDisposable { internal IntPtr _native; internal ICollide(IntPtr native) { _native = native; } public ICollide() { _native = btDbvt_ICollide_new(); } public bool AllLeaves(DbvtNode __unnamed0) { return btDbvt_ICollide_AllLeaves(_native, __unnamed0._native); } public bool Descent(DbvtNode __unnamed0) { return btDbvt_ICollide_Descent(_native, __unnamed0._native); } public void Process(DbvtNode __unnamed0, DbvtNode __unnamed1) { btDbvt_ICollide_Process(_native, __unnamed0._native, __unnamed1._native); } public void Process(DbvtNode __unnamed0) { btDbvt_ICollide_Process2(_native, __unnamed0._native); } public void Process(DbvtNode n, float __unnamed1) { btDbvt_ICollide_Process3(_native, n._native, __unnamed1); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { btDbvt_ICollide_delete(_native); _native = IntPtr.Zero; } } ~ICollide() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvt_ICollide_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btDbvt_ICollide_AllLeaves(IntPtr obj, IntPtr __unnamed0); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btDbvt_ICollide_Descent(IntPtr obj, IntPtr __unnamed0); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_ICollide_Process(IntPtr obj, IntPtr __unnamed0, IntPtr __unnamed1); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_ICollide_Process2(IntPtr obj, IntPtr __unnamed0); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_ICollide_Process3(IntPtr obj, IntPtr n, float __unnamed1); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_ICollide_delete(IntPtr obj); } public abstract class IWriter : IDisposable { internal IntPtr _native; internal IWriter(IntPtr native) { _native = native; } public void Prepare(DbvtNode root, int numnodes) { btDbvt_IWriter_Prepare(_native, root._native, numnodes); } public void WriteLeaf(DbvtNode __unnamed0, int index, int parent) { btDbvt_IWriter_WriteLeaf(_native, __unnamed0._native, index, parent); } public void WriteNode(DbvtNode __unnamed0, int index, int parent, int child0, int child1) { btDbvt_IWriter_WriteNode(_native, __unnamed0._native, index, parent, child0, child1); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { btDbvt_IWriter_delete(_native); _native = IntPtr.Zero; } } ~IWriter() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_IWriter_Prepare(IntPtr obj, IntPtr root, int numnodes); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_IWriter_WriteLeaf(IntPtr obj, IntPtr __unnamed0, int index, int parent); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_IWriter_WriteNode(IntPtr obj, IntPtr __unnamed0, int index, int parent, int child0, int child1); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_IWriter_delete(IntPtr obj); } public class StkCln : IDisposable { internal IntPtr _native; internal StkCln(IntPtr native) { _native = native; } public StkCln(DbvtNode n, DbvtNode p) { _native = btDbvt_sStkCLN_new(n._native, p._native); } public DbvtNode Node { get { IntPtr ptr = btDbvt_sStkCLN_getNode(_native); return (ptr != IntPtr.Zero) ? new DbvtNode(ptr) : null; } set { btDbvt_sStkCLN_setNode(_native, (value != null) ? value._native : IntPtr.Zero); } } public DbvtNode Parent { get { IntPtr ptr = btDbvt_sStkCLN_getParent(_native); return (ptr != IntPtr.Zero) ? new DbvtNode(ptr) : null; } set { btDbvt_sStkCLN_setParent(_native, (value != null) ? value._native : IntPtr.Zero); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { btDbvt_sStkCLN_delete(_native); _native = IntPtr.Zero; } } ~StkCln() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvt_sStkCLN_new(IntPtr n, IntPtr p); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvt_sStkCLN_getNode(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvt_sStkCLN_getParent(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_sStkCLN_setNode(IntPtr obj, IntPtr value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_sStkCLN_setParent(IntPtr obj, IntPtr value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_sStkCLN_delete(IntPtr obj); } public class StkNN : IDisposable { internal IntPtr _native; internal StkNN(IntPtr native) { _native = native; } public StkNN() { _native = btDbvt_sStkNN_new(); } public StkNN(DbvtNode na, DbvtNode nb) { _native = btDbvt_sStkNN_new2(na._native, nb._native); } public DbvtNode A { get { IntPtr ptr = btDbvt_sStkNN_getA(_native); return (ptr != IntPtr.Zero) ? new DbvtNode(ptr) : null; } set { btDbvt_sStkNN_setA(_native, (value != null) ? value._native : IntPtr.Zero); } } public DbvtNode B { get { IntPtr ptr = btDbvt_sStkNN_getB(_native); return (ptr != IntPtr.Zero) ? new DbvtNode(ptr) : null; } set { btDbvt_sStkNN_setB(_native, (value != null) ? value._native : IntPtr.Zero); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { btDbvt_sStkNN_delete(_native); _native = IntPtr.Zero; } } ~StkNN() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvt_sStkNN_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvt_sStkNN_new2(IntPtr na, IntPtr nb); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvt_sStkNN_getA(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvt_sStkNN_getB(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_sStkNN_setA(IntPtr obj, IntPtr value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_sStkNN_setB(IntPtr obj, IntPtr value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_sStkNN_delete(IntPtr obj); } public class StkNP : IDisposable { internal IntPtr _native; internal StkNP(IntPtr native) { _native = native; } public StkNP(DbvtNode n, uint m) { _native = btDbvt_sStkNP_new(n._native, m); } public int Mask { get { return btDbvt_sStkNP_getMask(_native); } set { btDbvt_sStkNP_setMask(_native, value); } } public DbvtNode Node { get { IntPtr ptr = btDbvt_sStkNP_getNode(_native); return (ptr != IntPtr.Zero) ? new DbvtNode(ptr) : null; } set { btDbvt_sStkNP_setNode(_native, (value != null) ? value._native : IntPtr.Zero); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { btDbvt_sStkNP_delete(_native); _native = IntPtr.Zero; } } ~StkNP() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvt_sStkNP_new(IntPtr n, uint m); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btDbvt_sStkNP_getMask(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvt_sStkNP_getNode(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_sStkNP_setMask(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_sStkNP_setNode(IntPtr obj, IntPtr value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_sStkNP_delete(IntPtr obj); } public class StkNps : IDisposable { internal IntPtr _native; internal StkNps(IntPtr native) { _native = native; } public StkNps() { _native = btDbvt_sStkNPS_new(); } public StkNps(DbvtNode n, uint m, float v) { _native = btDbvt_sStkNPS_new2(n._native, m, v); } public int Mask { get { return btDbvt_sStkNPS_getMask(_native); } set { btDbvt_sStkNPS_setMask(_native, value); } } public DbvtNode Node { get { IntPtr ptr = btDbvt_sStkNPS_getNode(_native); return (ptr != IntPtr.Zero) ? new DbvtNode(ptr) : null; } set { btDbvt_sStkNPS_setNode(_native, (value != null) ? value._native : IntPtr.Zero); } } public float Value { get { return btDbvt_sStkNPS_getValue(_native); } set { btDbvt_sStkNPS_setValue(_native, value); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { btDbvt_sStkNPS_delete(_native); _native = IntPtr.Zero; } } ~StkNps() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvt_sStkNPS_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvt_sStkNPS_new2(IntPtr n, uint m, float v); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btDbvt_sStkNPS_getMask(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvt_sStkNPS_getNode(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btDbvt_sStkNPS_getValue(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_sStkNPS_setMask(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_sStkNPS_setNode(IntPtr obj, IntPtr value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_sStkNPS_setValue(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_sStkNPS_delete(IntPtr obj); } internal IntPtr _native; bool _preventDelete; internal Dbvt(IntPtr native, bool preventDelete) { _native = native; _preventDelete = preventDelete; } public Dbvt() { _native = btDbvt_new(); } /* public static int Allocate(AlignedIntArray ifree, AlignedStkNpsArray stock, StkNps value) { return btDbvt_allocate(ifree._native, stock._native, value._native); } */ public static void Benchmark() { btDbvt_benchmark(); } public void Clear() { btDbvt_clear(_native); } public void Clone(Dbvt dest) { btDbvt_clone(_native, dest._native); } public void Clone(Dbvt dest, IClone iclone) { btDbvt_clone2(_native, dest._native, iclone._native); } /* public static void CollideKdop(DbvtNode root, Vector3 normals, float offsets, int count, ICollide policy) { btDbvt_collideKDOP(root._native, ref normals, offsets._native, count, policy._native); } public static void CollideOcl(DbvtNode root, Vector3 normals, float offsets, Vector3 sortaxis, int count, ICollide policy) { btDbvt_collideOCL(root._native, ref normals, offsets._native, ref sortaxis, count, policy._native); } public static void CollideOcl(DbvtNode root, Vector3 normals, float offsets, Vector3 sortaxis, int count, ICollide policy, bool fullsort) { btDbvt_collideOCL2(root._native, ref normals, offsets._native, ref sortaxis, count, policy._native, fullsort); } public void CollideTT(DbvtNode root0, DbvtNode root1, ICollide policy) { btDbvt_collideTT(_native, root0._native, root1._native, policy._native); } public void CollideTTPersistentStack(DbvtNode root0, DbvtNode root1, ICollide policy) { btDbvt_collideTTpersistentStack(_native, root0._native, root1._native, policy._native); } public static void CollideTU(DbvtNode root, ICollide policy) { btDbvt_collideTU(root._native, policy._native); } public void CollideTV(DbvtNode root, DbvtVolume volume, ICollide policy) { btDbvt_collideTV(_native, root._native, volume._native, policy._native); } */ public static int CountLeaves(DbvtNode node) { return btDbvt_countLeaves(node._native); } public bool Empty() { return btDbvt_empty(_native); } /* public static void EnumLeaves(DbvtNode root, ICollide policy) { btDbvt_enumLeaves(root._native, policy._native); } public static void EnumNodes(DbvtNode root, ICollide policy) { btDbvt_enumNodes(root._native, policy._native); } public static void ExtractLeaves(DbvtNode node, AlignedDbvtNodeArray leaves) { btDbvt_extractLeaves(node._native, leaves._native); } */ public DbvtNode Insert(DbvtVolume box, IntPtr data) { return new DbvtNode(btDbvt_insert(_native, box._native, data)); } public static int MaxDepth(DbvtNode node) { return btDbvt_maxdepth(node._native); } public static int Nearest(int[] i, StkNps a, float v, int l, int h) { return btDbvt_nearest(i, a._native, v, l, h); } public void OptimizeBottomUp() { btDbvt_optimizeBottomUp(_native); } public void OptimizeIncremental(int passes) { btDbvt_optimizeIncremental(_native, passes); } public void OptimizeTopDown() { btDbvt_optimizeTopDown(_native); } public void OptimizeTopDown(int buTreshold) { btDbvt_optimizeTopDown2(_native, buTreshold); } /* public static void RayTest(DbvtNode root, Vector3 rayFrom, Vector3 rayTo, ICollide policy) { btDbvt_rayTest(root._native, ref rayFrom, ref rayTo, policy._native); } public void RayTestInternal(DbvtNode root, Vector3 rayFrom, Vector3 rayTo, Vector3 rayDirectionInverse, uint[] signs, float lambdaMax, Vector3 aabbMin, Vector3 aabbMax, ICollide policy) { btDbvt_rayTestInternal(_native, root._native, ref rayFrom, ref rayTo, ref rayDirectionInverse, signs, lambdaMax, ref aabbMin, ref aabbMax, policy._native); } */ public void Remove(DbvtNode leaf) { btDbvt_remove(_native, leaf._native); } public void Update(DbvtNode leaf, DbvtVolume volume) { btDbvt_update(_native, leaf._native, volume._native); } public void Update(DbvtNode leaf) { btDbvt_update2(_native, leaf._native); } public void Update(DbvtNode leaf, int lookahead) { btDbvt_update3(_native, leaf._native, lookahead); } public bool Update(DbvtNode leaf, DbvtVolume volume, float margin) { return btDbvt_update4(_native, leaf._native, volume._native, margin); } public bool Update(DbvtNode leaf, DbvtVolume volume, Vector3 velocity) { return btDbvt_update5(_native, leaf._native, volume._native, ref velocity); } public bool Update(DbvtNode leaf, DbvtVolume volume, Vector3 velocity, float margin) { return btDbvt_update6(_native, leaf._native, volume._native, ref velocity, margin); } public void Write(IWriter iwriter) { btDbvt_write(_native, iwriter._native); } public DbvtNode Free { get { IntPtr ptr = btDbvt_getFree(_native); return (ptr != IntPtr.Zero) ? new DbvtNode(ptr) : null; } set { btDbvt_setFree(_native, (value != null) ? value._native : IntPtr.Zero); } } public int Leaves { get { return btDbvt_getLeaves(_native); } set { btDbvt_setLeaves(_native, value); } } public int Lkhd { get { return btDbvt_getLkhd(_native); } set { btDbvt_setLkhd(_native, value); } } public uint Opath { get { return btDbvt_getOpath(_native); } set { btDbvt_setOpath(_native, value); } } /* public AlignedObjectArray<DbvtNode> RayTestStack { get { return btDbvt_getRayTestStack(_native); } } */ public DbvtNode Root { get { IntPtr ptr = btDbvt_getRoot(_native); return (ptr != IntPtr.Zero) ? new DbvtNode(ptr) : null; } set { btDbvt_setRoot(_native, (value != null) ? value._native : IntPtr.Zero); } } /* public AlignedStkNNArray StkStack { get { return btDbvt_getStkStack(_native); } } */ public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { if (!_preventDelete) { btDbvt_delete(_native); } _native = IntPtr.Zero; } } ~Dbvt() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvt_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btDbvt_allocate(IntPtr ifree, IntPtr stock, IntPtr value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_benchmark(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_clear(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_clone(IntPtr obj, IntPtr dest); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_clone2(IntPtr obj, IntPtr dest, IntPtr iclone); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern void btDbvt_collideKDOP(IntPtr root, [In] ref Vector3 normals, IntPtr offsets, int count, IntPtr policy); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern void btDbvt_collideOCL(IntPtr root, [In] ref Vector3 normals, IntPtr offsets, [In] ref Vector3 sortaxis, int count, IntPtr policy); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern void btDbvt_collideOCL2(IntPtr root, [In] ref Vector3 normals, IntPtr offsets, [In] ref Vector3 sortaxis, int count, IntPtr policy, bool fullsort); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern void btDbvt_collideTT(IntPtr obj, IntPtr root0, IntPtr root1, IntPtr policy); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern void btDbvt_collideTTpersistentStack(IntPtr obj, IntPtr root0, IntPtr root1, IntPtr policy); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern void btDbvt_collideTU(IntPtr root, IntPtr policy); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern void btDbvt_collideTV(IntPtr obj, IntPtr root, IntPtr volume, IntPtr policy); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btDbvt_countLeaves(IntPtr node); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btDbvt_empty(IntPtr obj); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern void btDbvt_enumLeaves(IntPtr root, IntPtr policy); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern void btDbvt_enumNodes(IntPtr root, IntPtr policy); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_extractLeaves(IntPtr node, IntPtr leaves); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvt_getFree(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btDbvt_getLeaves(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btDbvt_getLkhd(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern uint btDbvt_getOpath(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_getRayTestStack(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvt_getRoot(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_getStkStack(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDbvt_insert(IntPtr obj, IntPtr box, IntPtr data); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btDbvt_maxdepth(IntPtr node); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btDbvt_nearest(int[] i, IntPtr a, float v, int l, int h); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_optimizeBottomUp(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_optimizeIncremental(IntPtr obj, int passes); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_optimizeTopDown(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_optimizeTopDown2(IntPtr obj, int bu_treshold); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern void btDbvt_rayTest(IntPtr root, [In] ref Vector3 rayFrom, [In] ref Vector3 rayTo, IntPtr policy); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern void btDbvt_rayTestInternal(IntPtr obj, IntPtr root, [In] ref Vector3 rayFrom, [In] ref Vector3 rayTo, [In] ref Vector3 rayDirectionInverse, uint[] signs, float lambda_max, [In] ref Vector3 aabbMin, [In] ref Vector3 aabbMax, IntPtr policy); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_remove(IntPtr obj, IntPtr leaf); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_setFree(IntPtr obj, IntPtr value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_setLeaves(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_setLkhd(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_setOpath(IntPtr obj, uint value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_setRoot(IntPtr obj, IntPtr value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_update(IntPtr obj, IntPtr leaf, IntPtr volume); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_update2(IntPtr obj, IntPtr leaf); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_update3(IntPtr obj, IntPtr leaf, int lookahead); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btDbvt_update4(IntPtr obj, IntPtr leaf, IntPtr volume, float margin); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btDbvt_update5(IntPtr obj, IntPtr leaf, IntPtr volume, [In] ref Vector3 velocity); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btDbvt_update6(IntPtr obj, IntPtr leaf, IntPtr volume, [In] ref Vector3 velocity, float margin); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_write(IntPtr obj, IntPtr iwriter); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDbvt_delete(IntPtr obj); } }
//Copyright (c) 2014 geekdrums //Released under the MIT license //http://opensource.org/licenses/mit-license.php //Feel free to use this for your lovely musical games :) using UnityEngine; using System; using System.Collections; using System.Collections.Generic; [ExecuteInEditMode] public class Music : MonoBehaviour { //editor params public List<Section> sections; //indexer public Section this[int index] { get { if( 0 <= index && index < SectionCount_ ) { return sections[index]; } else { Debug.LogWarning( "Section index out of range! index = " + index + ", SectionCount = " + SectionCount_ ); return null; } } } /// <summary> /// Just for music that doesn't start with the first timesample. /// if so, specify time samples before music goes into first timing = (0,0,0). /// </summary> public int delayTimeSamples = 0; /// <summary> /// put your debug GUIText to see current musical time & section info. /// </summary> public GUIText debugText; [Serializable] public class Section { public string name; /// <summary> /// how many MusicTime in a beat. maybe 4 or 3. /// </summary> public int mtBeat_; /// <summary> /// how many MusicTime in a bar. /// </summary> public int mtBar_; /// <summary> /// Musical Tempo. how many beats in a minutes. /// </summary> public double Tempo_; public Timing StartTiming_; public int StartTimeSamples_; public int StartTotalUnit_ { get; private set; } public bool isValidated_ { get; private set; } public Section( Timing startTiming, int mtBeat = 4, int mtBar = 16, double Tempo = 120 ) { StartTiming_ = startTiming; mtBeat_ = mtBeat; mtBar_ = mtBar; Tempo_ = Tempo; } public void OnValidate( int startTimeSample, int startTotalUnit ) { StartTimeSamples_ = startTimeSample; StartTotalUnit_ = startTotalUnit; isValidated_ = true; } public override string ToString() { return string.Format( "\"{0}\" startTiming:{1}, Tempo:{2}", name, StartTiming_.ToString(), Tempo_ ); } } public class SoundCue { public SoundCue( AudioSource source ) { this.source = source; } public AudioSource source { get; private set; } public void Play() { source.Play(); } public void Stop() { source.Stop(); } public void Pause() { source.Pause(); } public bool IsPlaying() { return source.isPlaying; } public long GetTimeSamples() { return source.timeSamples; } public float GetTime() { return source.time; } public void SetVolume( float volume ) { source.volume = volume; } } static Music Current; static List<Music> MusicList = new List<Music>(); #region public static properties /// <summary> /// means last timing. /// </summary> public static Timing Just { get { return Current.Just_; } } /// <summary> /// means nearest timing. /// </summary> public static Timing Now { get { return Current.Now_; } } /// <summary> /// is Just changed in this frame or not. /// </summary> public static bool isJustChanged { get { return Current.isJustChanged_; } } /// <summary> /// is Now changed in this frame or not. /// </summary> public static bool isNowChanged { get { return Current.isNowChanged_; } } /// <summary> /// is currently former half in a MusicTimeUnit, or last half. /// </summary> public static bool isFormerHalf { get { return Current.isFormerHalf_; } } /// <summary> /// delta time from JustChanged. /// </summary> public static double dtFromJust { get { return Current.dtFromJust_; } } /// <summary> /// how many times you repeat current music/block. /// </summary> public static int numRepeat { get { return Current.numRepeat_; } } /// <summary> /// returns how long from nearest Just timing with sign. /// </summary> public static double lag{ get{ return Current.lag_; } } /// <summary> /// returns how long from nearest Just timing absolutely. /// </summary> public static double lagAbs{ get{ return Current.lagAbs_; } } /// <summary> /// returns normalized lag. /// </summary> public static double lagUnit{ get{ return Current.lagUnit_; } } public static double MusicalTime { get { return Current.MusicalTime_; } } //sec per MusicTimeUnit public static float AudioTime { get{ return Current.AudioTime_; } } //sec public static long TimeSamples { get{ return Current.TimeSamples_; } } //sample public static int mtBar { get { return Current.mtBar_; } } public static int mtBeat { get { return Current.mtBeat_; } } public static double MusicTimeUnit { get { return Current.MusicTimeUnit_; } } public static string CurrentMusicName { get { return Current.name; } } public static SoundCue CurrentSource { get { return Current.MusicSource; } } public static Section CurrentSection { get { return Current.CurrentSection_; } } public static int SectionCount { get { return Current.SectionCount_; } } #endregion #region public static predicates public static bool IsJustChangedWhen( System.Predicate<Timing> pred ) { return Current.IsJustChangedWhen_( pred ); } public static bool IsJustChangedBar() { return Current.IsJustChangedBar_(); } public static bool IsJustChangedBeat() { return Current.IsJustChangedBeat_(); } public static bool IsJustChangedAt( int bar = 0, int beat = 0, int unit = 0 ) { return Current.IsJustChangedAt_( bar, beat, unit ); } public static bool IsJustChangedAt( Timing t ) { return Current.IsJustChangedAt_( t.bar, t.beat, t.unit ); } public static bool IsJustChangedSection( string sectionName = "" ) { Section targetSection = (sectionName == "" ? CurrentSection : GetSection( sectionName )); if( targetSection != null ) { return IsJustChangedAt( targetSection.StartTiming_ ); } else { Debug.LogWarning( "Can't find section name: " + sectionName ); return false; } } public static bool IsNowChangedWhen( System.Predicate<Timing> pred ) { return Current.IsNowChangedWhen_(pred); } public static bool IsNowChangedBar() { return Current.IsNowChangedBar_(); } public static bool IsNowChangedBeat() { return Current.IsNowChangedBeat_(); } public static bool IsNowChangedAt( int bar, int beat = 0, int unit = 0 ) { return Current.IsNowChangedAt_(bar,beat,unit); } public static bool IsNowChangedAt( Timing t ) { return Current.IsNowChangedAt_( t.bar, t.beat, t.unit ); } public static Section GetSection( int index ) { return Current[index]; } public static Section GetSection( string name ) { return Current.sections.Find( ( Section s ) => s.name == name ); } public static float MusicalTimeFrom( Timing timing ) { return (Now - timing) + (float)lagUnit; } #endregion #region public static functions /// <summary> /// Change Current Music. /// </summary> /// <param name="MusicName">name of the GameObject that include Music</param> public static void Play( string MusicName ) { MusicList.Find( ( Music m ) => m.name == MusicName ).PlayStart(); } /// <summary> /// Quantize to musical time. /// </summary> public static void QuantizePlay( AudioSource source, int transpose = 0 ) { source.pitch = Mathf.Pow( pitchUnit, transpose ); if( isFormerHalf && lagUnit < 0.3f ) { source.Play(); } else { Current.QuantizedCue.Add( source ); } } public static bool IsPlaying() { return Current.MusicSource.IsPlaying(); } public static void Pause() { Current.MusicSource.Pause(); } public static void Resume() { Current.MusicSource.Play(); } public static void Stop() { Current.MusicSource.Stop(); } public static void Seek( Timing timing ) { Current.MusicSource.source.timeSamples = (int)(timing.totalUnit * MusicTimeUnit * Current.SamplingRate); } public static void SeekToSection( string sectionName ) { Section targetSection = GetSection( sectionName ); if( targetSection != null ) { Current.MusicSource.source.timeSamples = targetSection.StartTimeSamples_; Current.SectionIndex = Current.sections.IndexOf( targetSection ); Current.OnSectionChanged(); } else { Debug.LogWarning( "Can't find section name: " + sectionName ); } } public static void SetVolume( float volume ) { Current.MusicSource.SetVolume( volume ); } #endregion #region private properties private Timing Now_; private Timing Just_; private bool isJustChanged_; private bool isNowChanged_; private bool isFormerHalf_; private double dtFromJust_; private int numRepeat_; private double MusicTimeUnit_; private double lag_ { get { if ( isFormerHalf_ ) return dtFromJust_; else return dtFromJust_ - MusicTimeUnit_; } } private double lagAbs_ { get { if ( isFormerHalf_ ) return dtFromJust_; else return MusicTimeUnit_ - dtFromJust_; } } private double lagUnit_ { get { return lag / MusicTimeUnit_; } } private double MusicalTime_ { get { return Just.totalUnit + dtFromJust / MusicTimeUnit; } } private float AudioTime_ { get { return MusicSource.GetTime(); } } private long TimeSamples_ { get { return MusicSource.GetTimeSamples(); } } private int SectionCount_ { get { return sections.Count; } } private int mtBar_ { get { return CurrentSection.mtBar_; } } private int mtBeat_ { get { return CurrentSection.mtBeat_; } } private bool isPlaying { get { return MusicSource != null && MusicSource.IsPlaying(); } } #endregion #region private predicates private bool IsNowChangedWhen_( System.Predicate<Timing> pred ) { return isNowChanged_ && pred( Now_ ); } private bool IsNowChangedBar_() { return isNowChanged_ && Now_.barUnit == 0; } private bool IsNowChangedBeat_() { return isNowChanged_ && Now_.unit == 0; } private bool IsNowChangedAt_( int bar, int beat = 0, int unit = 0 ) { return isNowChanged_ && Now_.bar == bar && Now_.beat == beat && Now_.unit == unit; } private bool IsJustChangedWhen_( System.Predicate<Timing> pred ) { return isJustChanged_ && pred( Just_ ); } private bool IsJustChangedBar_() { return isJustChanged_ && Just_.barUnit == 0; } private bool IsJustChangedBeat_() { return isJustChanged_ && Just_.unit == 0; } private bool IsJustChangedAt_( int bar = 0, int beat = 0, int unit = 0 ) { return isJustChanged_ && Just_.bar == bar && Just_.beat == beat && Just_.unit == unit; } #endregion #region private params //music current params SoundCue MusicSource; int SectionIndex; Section CurrentSection_ { get { return sections[SectionIndex]; } } List<AudioSource> QuantizedCue = new List<AudioSource>(); //readonly params static readonly float pitchUnit = Mathf.Pow( 2.0f, 1.0f / 12.0f ); int SamplingRate;// = 44100; long SamplesPerUnit; long SamplesPerBeat; long SamplesPerBar; long SamplesInLoop; //others Timing OldNow, OldJust; int NumLoopBar; #endregion #region Initialize & Update void Awake() { #if UNITY_EDITOR if( !UnityEditor.EditorApplication.isPlaying ) { OnValidate(); return; } #endif MusicList.Add( this ); if( Current == null || audio.playOnAwake ) { Current = this; } MusicSource = new SoundCue( audio ); SamplingRate = audio.clip.frequency; if( audio.loop ) { SamplesInLoop = audio.clip.samples; Section lastSection = sections[sections.Count - 1]; long samplesPerUnit = (long)(SamplingRate * (60.0 / (lastSection.Tempo_ * lastSection.mtBeat_))); long samplesPerBar = samplesPerUnit * lastSection.mtBar_; NumLoopBar = lastSection.StartTiming_.bar + Mathf.RoundToInt( (float)(SamplesInLoop - lastSection.StartTimeSamples_) / (float)samplesPerBar ); } Initialize(); OnSectionChanged(); } // Use this for initialization void Start() { } // Update is called once per frame void Update() { if( isPlaying ) { UpdateTiming(); } } void OnValidate() { if( SamplingRate == 0 ) { SamplingRate = (audio != null ? audio.clip.frequency : 44100); } if( sections == null || sections.Count == 0 ) { sections = new List<Section>(); sections.Add( new Section( new Timing( 0 ), 4, 16, 120 ) ); sections[0].OnValidate( delayTimeSamples, 0 ); } else { bool isValidated = true; int timeSamples = delayTimeSamples; int totalUnit = 0; for( int i = 0; i < sections.Count; i++ ) { if( sections[i].StartTotalUnit_ != totalUnit || sections[i].StartTimeSamples_ != timeSamples ) isValidated = false; if( !isValidated ) { isValidated = false; sections[i].OnValidate( timeSamples, totalUnit ); } if( i+1 < sections.Count ) { int d = (sections[i+1].StartTiming_.bar - sections[i].StartTiming_.bar) * sections[i].mtBar_ +(sections[i+1].StartTiming_.beat - sections[i].StartTiming_.beat) * sections[i].mtBeat_ +(sections[i+1].StartTiming_.unit - sections[i].StartTiming_.unit); totalUnit += d; timeSamples += (int)((d / sections[i].mtBeat_) * (60.0f / sections[i].Tempo_) * SamplingRate); } } } } void Initialize() { if( Current != null && isJustChanged && Just.totalUnit == 0 ) { Now_ = new Timing( 0, 0, 0 ); isJustChanged_ = true; } else { Now_ = new Timing( 0, 0, -1 ); isJustChanged_ = false; } Just_ = new Timing( Now_ ); OldNow = new Timing( Now_ ); OldJust = new Timing( Just_ ); dtFromJust_ = 0; isFormerHalf_ = true; numRepeat_ = 0; } void OnSectionChanged() { if( sections == null || sections.Count == 0 ) return; if( CurrentSection_.Tempo_ > 0.0f ) { SamplesPerUnit = (long)( SamplingRate * ( 60.0 / ( CurrentSection_.Tempo_ * CurrentSection_.mtBeat_ ) ) ); SamplesPerBeat = SamplesPerUnit*CurrentSection_.mtBeat_; SamplesPerBar = SamplesPerUnit*CurrentSection_.mtBar_; MusicTimeUnit_ = (double)SamplesPerUnit / (double)SamplingRate; } else { SamplesPerUnit = int.MaxValue; SamplesPerBeat = int.MaxValue; SamplesPerBar = int.MaxValue; MusicTimeUnit_ = int.MaxValue; } } void PlayStart() { if ( Current != null && IsPlaying() ) { Stop(); } if( Current.debugText != null ) { Current.debugText.text = ""; } Current = this; Initialize(); MusicSource.Play(); } void UpdateTiming() { isNowChanged_ = false; isJustChanged_ = false; if( SectionIndex < 0 || sections.Count <= SectionIndex ) { Debug.LogWarning( "Music:" + name + " has invalid SectionIndex = " + SectionIndex + ", sections.Count = " + sections.Count ); return; } long numSamples = MusicSource.GetTimeSamples(); int NewIndex = -1; for( int i = SectionIndex; i < sections.Count; i++ ) { if( sections[i].StartTimeSamples_ <= numSamples && (sections.Count <= i + 1 || numSamples < sections[i + 1].StartTimeSamples_) ) { NewIndex = i; break; } } if( NewIndex < 0 ) { if( 0 <= numSamples && numSamples < delayTimeSamples ) { NewIndex = 0; Initialize(); OnSectionChanged(); } else { for( int i = 0; i < SectionIndex; i++ ) { if( sections[i].StartTimeSamples_ <= numSamples && numSamples < sections[i + 1].StartTimeSamples_ ) { NewIndex = i; } } } } if( NewIndex != SectionIndex ) { SectionIndex = NewIndex; OnSectionChanged(); } numSamples -= CurrentSection_.StartTimeSamples_; if ( numSamples >= 0 ) { Just_.bar = (int)( numSamples / SamplesPerBar ) + CurrentSection_.StartTiming_.bar; Just_.beat = (int)((numSamples % SamplesPerBar) / SamplesPerBeat) +CurrentSection_.StartTiming_.beat; Just_.unit = (int)(((numSamples % SamplesPerBar) % SamplesPerBeat) / SamplesPerUnit) +CurrentSection_.StartTiming_.unit; if( Just_.unit >= CurrentSection_.mtBeat_ ) { Just_.beat += (int)(Just_.unit / CurrentSection_.mtBeat_); Just_.unit %= CurrentSection_.mtBeat_; } int barUnit = Just_.beat * CurrentSection_.mtBeat_ + Just_.unit; if( barUnit >= CurrentSection_.mtBar_ ) { Just_.bar += (int)(barUnit / CurrentSection_.mtBar_); Just_.beat = 0; Just_.unit = (barUnit % CurrentSection_.mtBar_); if( Just_.unit >= CurrentSection_.mtBeat_ ) { Just_.beat += (int)(Just_.unit / CurrentSection_.mtBeat_); Just_.unit %= CurrentSection_.mtBeat_; } } if ( NumLoopBar > 0 ) Just_.bar %= NumLoopBar; isFormerHalf_ = ( numSamples % SamplesPerUnit ) < SamplesPerUnit / 2; dtFromJust_ = (double)( numSamples % SamplesPerUnit ) / (double)SamplingRate; Now_.Copy( Just_ ); if ( !isFormerHalf_ ) Now_.Increment(); if ( SamplesInLoop != 0 && numSamples + SamplesPerUnit/2 >= SamplesInLoop ) { Now_.Init(); } isNowChanged_ = Now_.totalUnit != OldNow.totalUnit; isJustChanged_ = Just_.totalUnit != OldJust.totalUnit; CallEvents(); OldNow.Copy( Now_ ); OldJust.Copy( Just_ ); } else { //Debug.LogWarning( "Warning!! Failed to GetNumPlayedSamples" ); } DebugUpdateText(); } void DebugUpdateText() { if( debugText != null ) { debugText.text = "Just = " + Just_.ToString() + ", MusicalTime = " + MusicalTime_; if( sections.Count > 0 ) { debugText.text += System.Environment.NewLine + "section[" + SectionIndex + "] = " + CurrentSection_.ToString(); } } } #endregion #region Events void CallEvents() { if ( isNowChanged_ ) OnNowChanged(); if ( isNowChanged_ && OldNow > Now_ ) { WillRepeat(); } if ( isJustChanged_ ) OnJustChanged(); if ( isJustChanged_ && Just_.unit == 0 ) OnBeat(); if ( isJustChanged_ && Just_.barUnit == 0 ) OnBar(); if ( isJustChanged_ && OldJust > Just_ ) { OnRepeated(); } /* if ( isJustChanged_ && Just_.totalUnit > 0 ) { Timing tempOld = new Timing( OldJust ); tempOld.Increment(); if ( tempOld.totalUnit != Just_.totalUnit ) { //This often happens when the frame rate is slow. Debug.LogWarning( "Skipped some timing: OldJust = " + OldJust.ToString() + ", Just = " + Just_.ToString() ); } } */ } //On events (when isJustChanged) void OnNowChanged() { } void OnJustChanged() { foreach ( AudioSource cue in QuantizedCue ) { cue.Play(); } QuantizedCue.Clear(); } void OnBeat() { } void OnBar() { } void OnRepeated() { ++numRepeat_; } //Will events (when isNowChanged) void WillRepeat() { } #endregion } [Serializable] public class Timing : IComparable<Timing>, IEquatable<Timing> { public Timing( int b = 0, int be = 0, int u = 0 ) { bar = b; beat = be; unit = u; _cachedSectionIndex = 0; } public Timing( Timing copy ) { Copy( copy ); } public Timing() { this.Init(); } public void Init() { bar = 0; beat = 0; unit = 0; _cachedSectionIndex = 0; } public void Copy( Timing copy ) { bar = copy.bar; beat = copy.beat; unit = copy.unit; _cachedSectionIndex = copy._cachedSectionIndex; } public int bar, beat, unit; public int totalUnit { get { return CurrentSection.StartTotalUnit_ + ( bar - CurrentSection.StartTiming_.bar ) * CurrentSection.mtBar_ + ( beat - CurrentSection.StartTiming_.beat ) * CurrentSection.mtBeat_ + ( unit - CurrentSection.StartTiming_.unit ); } } public int barUnit { get { return ( unit < 0 ? CurrentSection.mtBar_ - unit : CurrentSection.mtBeat_ * beat + unit )%CurrentSection.mtBar_; } } public void Increment() { unit++; if ( CurrentSection.mtBeat_ * beat + unit >= CurrentSection.mtBar_ ) { unit = 0; beat = 0; bar += 1; } else if ( unit >= CurrentSection.mtBeat_ ) { unit = 0; beat += 1; } } public void IncrementBeat() { beat++; if ( CurrentSection.mtBeat_ * beat + unit >= CurrentSection.mtBar_ ) { beat = 0; bar += 1; } } int _cachedSectionIndex = 0; int sectionIndex { get { if( _cachedSectionIndex >= Music.SectionCount || this < Music.GetSection(_cachedSectionIndex).StartTiming_ || ( _cachedSectionIndex < Music.SectionCount-1 && Music.GetSection(_cachedSectionIndex+1).StartTiming_ <= this ) ) { if( Music.GetSection(Music.SectionCount-1).StartTiming_ <= this ) { _cachedSectionIndex = Music.SectionCount-1; } else { _cachedSectionIndex = 0; for( int i=1; i<Music.SectionCount; i++ ) { if( this < Music.GetSection(i).StartTiming_ ) { _cachedSectionIndex = i - 1; break; } } } } return _cachedSectionIndex; } } Music.Section CurrentSection{ get{ return Music.GetSection(sectionIndex); } } public static bool operator >( Timing t, Timing t2 ) { return t.bar > t2.bar || ( t.bar == t2.bar && t.beat > t2.beat ) || ( t.bar == t2.bar && t.beat == t2.beat && t.unit > t2.unit ) ; } public static bool operator <( Timing t, Timing t2 ) { return !( t > t2 ) && !( t.Equals( t2 ) ); } public static bool operator <=( Timing t, Timing t2 ) { return !( t > t2 ); } public static bool operator >=( Timing t, Timing t2 ) { return t > t2 || t.Equals( t2 ); } public static int operator -( Timing t, Timing t2 ) { return t.totalUnit - t2.totalUnit; } public override bool Equals( object obj ) { if ( object.ReferenceEquals( obj, null ) ) { return false; } if ( object.ReferenceEquals( obj, this ) ) { return true; } if ( this.GetType() != obj.GetType() ) { return false; } return this.Equals( obj as Timing ); } public override int GetHashCode() { return base.GetHashCode(); } public bool Equals( Timing other ) { return ( this.bar == other.bar && this.beat == other.beat && this.unit == other.unit ); } public int CompareTo( Timing tother ) { if ( this.Equals( tother ) ) return 0; else if ( this > tother ) return 1; else return -1; } public override string ToString() { return bar + " " + beat + " " + unit; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Security.Claims { public partial class Claim { public Claim(System.IO.BinaryReader reader) { } public Claim(System.IO.BinaryReader reader, System.Security.Claims.ClaimsIdentity subject) { } protected Claim(System.Security.Claims.Claim other) { } protected Claim(System.Security.Claims.Claim other, System.Security.Claims.ClaimsIdentity subject) { } public Claim(string type, string value) { } public Claim(string type, string value, string valueType) { } public Claim(string type, string value, string valueType, string issuer) { } public Claim(string type, string value, string valueType, string issuer, string originalIssuer) { } public Claim(string type, string value, string valueType, string issuer, string originalIssuer, System.Security.Claims.ClaimsIdentity subject) { } protected virtual byte[] CustomSerializationData { get { throw null; } } public string Issuer { get { throw null; } } public string OriginalIssuer { get { throw null; } } public System.Collections.Generic.IDictionary<string, string> Properties { get { throw null; } } public System.Security.Claims.ClaimsIdentity Subject { get { throw null; } } public string Type { get { throw null; } } public string Value { get { throw null; } } public string ValueType { get { throw null; } } public virtual System.Security.Claims.Claim Clone() { throw null; } public virtual System.Security.Claims.Claim Clone(System.Security.Claims.ClaimsIdentity identity) { throw null; } public override string ToString() { throw null; } public virtual void WriteTo(System.IO.BinaryWriter writer) { } protected virtual void WriteTo(System.IO.BinaryWriter writer, byte[] userData) { } } public partial class ClaimsIdentity : System.Security.Principal.IIdentity { public const string DefaultIssuer = "LOCAL AUTHORITY"; public const string DefaultNameClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"; public const string DefaultRoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"; public ClaimsIdentity() { } public ClaimsIdentity(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims) { } public ClaimsIdentity(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims, string authenticationType) { } public ClaimsIdentity(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims, string authenticationType, string nameType, string roleType) { } public ClaimsIdentity(System.IO.BinaryReader reader) { } protected ClaimsIdentity(System.Security.Claims.ClaimsIdentity other) { } public ClaimsIdentity(System.Security.Principal.IIdentity identity) { } public ClaimsIdentity(System.Security.Principal.IIdentity identity, System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims) { } public ClaimsIdentity(System.Security.Principal.IIdentity identity, System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims, string authenticationType, string nameType, string roleType) { } public ClaimsIdentity(string authenticationType) { } public ClaimsIdentity(string authenticationType, string nameType, string roleType) { } protected ClaimsIdentity(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } protected ClaimsIdentity(System.Runtime.Serialization.SerializationInfo info) { } public System.Security.Claims.ClaimsIdentity Actor { get { throw null; } set { } } public virtual string AuthenticationType { get { throw null; } } public object BootstrapContext { get { throw null; }[System.Security.SecurityCriticalAttribute]set { } } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { throw null; } } protected virtual byte[] CustomSerializationData { get { throw null; } } public virtual bool IsAuthenticated { get { throw null; } } public string Label { get { throw null; } set { } } public virtual string Name { get { throw null; } } public string NameClaimType { get { throw null; } } public string RoleClaimType { get { throw null; } } [System.Security.SecurityCriticalAttribute] public virtual void AddClaim(System.Security.Claims.Claim claim) { } [System.Security.SecurityCriticalAttribute] public virtual void AddClaims(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims) { } public virtual System.Security.Claims.ClaimsIdentity Clone() { throw null; } protected virtual System.Security.Claims.Claim CreateClaim(System.IO.BinaryReader reader) { throw null; } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(System.Predicate<System.Security.Claims.Claim> match) { throw null; } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(string type) { throw null; } public virtual System.Security.Claims.Claim FindFirst(System.Predicate<System.Security.Claims.Claim> match) { throw null; } public virtual System.Security.Claims.Claim FindFirst(string type) { throw null; } protected virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual bool HasClaim(System.Predicate<System.Security.Claims.Claim> match) { throw null; } public virtual bool HasClaim(string type, string value) { throw null; } [System.Security.SecurityCriticalAttribute] public virtual void RemoveClaim(System.Security.Claims.Claim claim) { } [System.Security.SecurityCriticalAttribute] public virtual bool TryRemoveClaim(System.Security.Claims.Claim claim) { throw null; } public virtual void WriteTo(System.IO.BinaryWriter writer) { } protected virtual void WriteTo(System.IO.BinaryWriter writer, byte[] userData) { } } public partial class ClaimsPrincipal : System.Security.Principal.IPrincipal { public ClaimsPrincipal() { } public ClaimsPrincipal(System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity> identities) { } public ClaimsPrincipal(System.IO.BinaryReader reader) { } public ClaimsPrincipal(System.Security.Principal.IIdentity identity) { } public ClaimsPrincipal(System.Security.Principal.IPrincipal principal) { } protected ClaimsPrincipal(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { throw null; } } public static System.Func<System.Security.Claims.ClaimsPrincipal> ClaimsPrincipalSelector { get { throw null; }[System.Security.SecurityCriticalAttribute]set { } } public static System.Security.Claims.ClaimsPrincipal Current { get { throw null; } } protected virtual byte[] CustomSerializationData { get { throw null; } } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity> Identities { get { throw null; } } public virtual System.Security.Principal.IIdentity Identity { get { throw null; } } public static System.Func<System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity>, System.Security.Claims.ClaimsIdentity> PrimaryIdentitySelector { get { throw null; }[System.Security.SecurityCriticalAttribute]set { } } [System.Security.SecurityCriticalAttribute] public virtual void AddIdentities(System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity> identities) { } [System.Security.SecurityCriticalAttribute] public virtual void AddIdentity(System.Security.Claims.ClaimsIdentity identity) { } public virtual System.Security.Claims.ClaimsPrincipal Clone() { throw null; } protected virtual System.Security.Claims.ClaimsIdentity CreateClaimsIdentity(System.IO.BinaryReader reader) { throw null; } protected virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(System.Predicate<System.Security.Claims.Claim> match) { throw null; } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(string type) { throw null; } public virtual System.Security.Claims.Claim FindFirst(System.Predicate<System.Security.Claims.Claim> match) { throw null; } public virtual System.Security.Claims.Claim FindFirst(string type) { throw null; } public virtual bool HasClaim(System.Predicate<System.Security.Claims.Claim> match) { throw null; } public virtual bool HasClaim(string type, string value) { throw null; } public virtual bool IsInRole(string role) { throw null; } public virtual void WriteTo(System.IO.BinaryWriter writer) { } protected virtual void WriteTo(System.IO.BinaryWriter writer, byte[] userData) { } } public static partial class ClaimTypes { public const string Actor = "http://schemas.xmlsoap.org/ws/2009/09/identity/claims/actor"; public const string Anonymous = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/anonymous"; public const string Authentication = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authentication"; public const string AuthenticationInstant = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant"; public const string AuthenticationMethod = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod"; public const string AuthorizationDecision = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authorizationdecision"; public const string CookiePath = "http://schemas.microsoft.com/ws/2008/06/identity/claims/cookiepath"; public const string Country = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country"; public const string DateOfBirth = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth"; public const string DenyOnlyPrimaryGroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarygroupsid"; public const string DenyOnlyPrimarySid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarysid"; public const string DenyOnlySid = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/denyonlysid"; public const string DenyOnlyWindowsDeviceGroup = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlywindowsdevicegroup"; public const string Dns = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dns"; public const string Dsa = "http://schemas.microsoft.com/ws/2008/06/identity/claims/dsa"; public const string Email = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"; public const string Expiration = "http://schemas.microsoft.com/ws/2008/06/identity/claims/expiration"; public const string Expired = "http://schemas.microsoft.com/ws/2008/06/identity/claims/expired"; public const string Gender = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/gender"; public const string GivenName = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"; public const string GroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid"; public const string Hash = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/hash"; public const string HomePhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/homephone"; public const string IsPersistent = "http://schemas.microsoft.com/ws/2008/06/identity/claims/ispersistent"; public const string Locality = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality"; public const string MobilePhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/mobilephone"; public const string Name = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"; public const string NameIdentifier = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"; public const string OtherPhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/otherphone"; public const string PostalCode = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode"; public const string PrimaryGroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarygroupsid"; public const string PrimarySid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid"; public const string Role = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"; public const string Rsa = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/rsa"; public const string SerialNumber = "http://schemas.microsoft.com/ws/2008/06/identity/claims/serialnumber"; public const string Sid = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid"; public const string Spn = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/spn"; public const string StateOrProvince = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/stateorprovince"; public const string StreetAddress = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/streetaddress"; public const string Surname = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"; public const string System = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/system"; public const string Thumbprint = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint"; public const string Upn = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"; public const string Uri = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/uri"; public const string UserData = "http://schemas.microsoft.com/ws/2008/06/identity/claims/userdata"; public const string Version = "http://schemas.microsoft.com/ws/2008/06/identity/claims/version"; public const string Webpage = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/webpage"; public const string WindowsAccountName = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname"; public const string WindowsDeviceClaim = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdeviceclaim"; public const string WindowsDeviceGroup = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdevicegroup"; public const string WindowsFqbnVersion = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsfqbnversion"; public const string WindowsSubAuthority = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowssubauthority"; public const string WindowsUserClaim = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsuserclaim"; public const string X500DistinguishedName = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/x500distinguishedname"; } public static partial class ClaimValueTypes { public const string Base64Binary = "http://www.w3.org/2001/XMLSchema#base64Binary"; public const string Base64Octet = "http://www.w3.org/2001/XMLSchema#base64Octet"; public const string Boolean = "http://www.w3.org/2001/XMLSchema#boolean"; public const string Date = "http://www.w3.org/2001/XMLSchema#date"; public const string DateTime = "http://www.w3.org/2001/XMLSchema#dateTime"; public const string DaytimeDuration = "http://www.w3.org/TR/2002/WD-xquery-operators-20020816#dayTimeDuration"; public const string DnsName = "http://schemas.xmlsoap.org/claims/dns"; public const string Double = "http://www.w3.org/2001/XMLSchema#double"; public const string DsaKeyValue = "http://www.w3.org/2000/09/xmldsig#DSAKeyValue"; public const string Email = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"; public const string Fqbn = "http://www.w3.org/2001/XMLSchema#fqbn"; public const string HexBinary = "http://www.w3.org/2001/XMLSchema#hexBinary"; public const string Integer = "http://www.w3.org/2001/XMLSchema#integer"; public const string Integer32 = "http://www.w3.org/2001/XMLSchema#integer32"; public const string Integer64 = "http://www.w3.org/2001/XMLSchema#integer64"; public const string KeyInfo = "http://www.w3.org/2000/09/xmldsig#KeyInfo"; public const string Rfc822Name = "urn:oasis:names:tc:xacml:1.0:data-type:rfc822Name"; public const string Rsa = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/rsa"; public const string RsaKeyValue = "http://www.w3.org/2000/09/xmldsig#RSAKeyValue"; public const string Sid = "http://www.w3.org/2001/XMLSchema#sid"; public const string String = "http://www.w3.org/2001/XMLSchema#string"; public const string Time = "http://www.w3.org/2001/XMLSchema#time"; public const string UInteger32 = "http://www.w3.org/2001/XMLSchema#uinteger32"; public const string UInteger64 = "http://www.w3.org/2001/XMLSchema#uinteger64"; public const string UpnName = "http://schemas.xmlsoap.org/claims/UPN"; public const string X500Name = "urn:oasis:names:tc:xacml:1.0:data-type:x500Name"; public const string YearMonthDuration = "http://www.w3.org/TR/2002/WD-xquery-operators-20020816#yearMonthDuration"; } } namespace System.Security.Principal { public partial class GenericIdentity : System.Security.Claims.ClaimsIdentity { protected GenericIdentity(System.Security.Principal.GenericIdentity identity) { } public GenericIdentity(string name) { } public GenericIdentity(string name, string type) { } public override string AuthenticationType { get { throw null; } } public override System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { throw null; } } public override bool IsAuthenticated { get { throw null; } } public override string Name { get { throw null; } } public override System.Security.Claims.ClaimsIdentity Clone() { throw null; } } public partial class GenericPrincipal : System.Security.Claims.ClaimsPrincipal { public GenericPrincipal(System.Security.Principal.IIdentity identity, string[] roles) { } public override System.Security.Principal.IIdentity Identity { get { throw null; } } public override bool IsInRole(string role) { throw null; } } }
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; namespace Amazon.EC2.Model { /// <summary> /// Virtual Private Cloud /// </summary> [XmlRootAttribute(IsNullable = false)] public class Vpc { private string vpcIdField; private string vpcStateField; private string cidrBlockField; private string dhcpOptionsIdField; private List<Tag> tagField; private string instanceTenancyField; private bool? isDefaultField; /// <summary> /// The VPC's ID /// </summary> [XmlElementAttribute(ElementName = "VpcId")] public string VpcId { get { return this.vpcIdField; } set { this.vpcIdField = value; } } /// <summary> /// Sets the VPC's ID /// </summary> /// <param name="vpcId">The VPC's ID</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Vpc WithVpcId(string vpcId) { this.vpcIdField = vpcId; return this; } /// <summary> /// Checks if VpcId property is set /// </summary> /// <returns>true if VpcId property is set</returns> public bool IsSetVpcId() { return this.vpcIdField != null; } /// <summary> /// The current state of the VPC (pending or available). /// </summary> [XmlElementAttribute(ElementName = "VpcState")] public string VpcState { get { return this.vpcStateField; } set { this.vpcStateField = value; } } /// <summary> /// Sets the current state of the VPC (pending or available). /// </summary> /// <param name="vpcState">The current state of the VPC (pending or available).</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Vpc WithVpcState(string vpcState) { this.vpcStateField = vpcState; return this; } /// <summary> /// Checks if VpcState property is set /// </summary> /// <returns>true if VpcState property is set</returns> public bool IsSetVpcState() { return this.vpcStateField != null; } /// <summary> /// The CIDR block the VPC covers /// </summary> [XmlElementAttribute(ElementName = "CidrBlock")] public string CidrBlock { get { return this.cidrBlockField; } set { this.cidrBlockField = value; } } /// <summary> /// Sets the CIDR block the VPC covers /// </summary> /// <param name="cidrBlock">The CIDR block the VPC covers</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Vpc WithCidrBlock(string cidrBlock) { this.cidrBlockField = cidrBlock; return this; } /// <summary> /// Checks if CidrBlock property is set /// </summary> /// <returns>true if CidrBlock property is set</returns> public bool IsSetCidrBlock() { return this.cidrBlockField != null; } /// <summary> /// The ID of the set of DHCP options you've associated with the VPC /// (or "default" if the default options are associated with the VPC). /// </summary> [XmlElementAttribute(ElementName = "DhcpOptionsId")] public string DhcpOptionsId { get { return this.dhcpOptionsIdField; } set { this.dhcpOptionsIdField = value; } } /// <summary> /// Sets the ID of the set of DHCP options ve associated with the VPC /// (or "default" if the default options are associated with the VPC). /// </summary> /// <param name="dhcpOptionsId">The ID of the set of DHCP options you've /// associated with the VPC (or "default" if the default options are /// associated with the VPC).</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Vpc WithDhcpOptionsId(string dhcpOptionsId) { this.dhcpOptionsIdField = dhcpOptionsId; return this; } /// <summary> /// Checks if DhcpOptionsId property is set /// </summary> /// <returns>true if DhcpOptionsId property is set</returns> public bool IsSetDhcpOptionsId() { return this.dhcpOptionsIdField != null; } /// <summary> /// A list of tags for the VPC. /// </summary> [XmlElementAttribute(ElementName = "Tag")] public List<Tag> Tag { get { if (this.tagField == null) { this.tagField = new List<Tag>(); } return this.tagField; } set { this.tagField = value; } } /// <summary> /// Sets tags for the VPC. /// </summary> /// <param name="list">A list of tags for the Vpc.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Vpc WithTag(params Tag[] list) { foreach (Tag item in list) { Tag.Add(item); } return this; } /// <summary> /// Checks if Tag property is set /// </summary> /// <returns>true if Tag property is set</returns> public bool IsSetTag() { return (Tag.Count > 0); } /// <summary> /// The allowed tenancy of instances launched into the VPC. /// </summary> [XmlElementAttribute(ElementName = "InstanceTenancy")] public string InstanceTenancy { get { return this.instanceTenancyField; } set { this.instanceTenancyField = value; } } /// <summary> /// Checks if InstanceTenancy property is set /// </summary> /// <returns>true if InstanceTenancy property is set</returns> public bool IsSetInstanceTenancy() { return this.instanceTenancyField != null; } /// <summary> /// Sets the allowed tenancy of instances launched into the VPC. /// </summary> /// <param name="instanceTenancy">The allowed tenancy of instances launched into the VPC.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Vpc WithInstanceTenancy(string instanceTenancy) { this.instanceTenancyField = instanceTenancy; return this; } /// <summary> /// Whether this is a default VPC. /// </summary> [XmlElementAttribute(ElementName = "IsDefault")] public bool IsDefault { get { return this.isDefaultField.GetValueOrDefault(); } set { this.isDefaultField = value; } } /// <summary> /// Sets whether this is a default VPC. /// </summary> /// <param name="isDefault">Whether this is a default VPC.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Vpc WithIsDefault(bool isDefault) { this.isDefaultField = isDefault; return this; } /// <summary> /// Checks if the IsDefault property is set /// </summary> /// <returns>true if the IsDefault property is set</returns> public bool IsSetIsDefault() { return this.isDefaultField != null; } } }
// Copyright (c) 2009-2012 David Koontz // Please direct any bugs/comments/suggestions to [email protected] // // Thanks to Gabriel Gheorghiu ([email protected]) for his code submission // that lead to the integration with the iTween visual path editor. // // 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 UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Linq; [CustomEditor(typeof(iTweenEvent))] public class iTweenEventDataEditor : Editor { List<string> trueFalseOptions = new List<string>() {"True", "False"}; Dictionary<string, object> values; Dictionary<string, bool> propertiesEnabled = new Dictionary<string, bool>(); iTweenEvent.TweenType previousType; [MenuItem("Component/iTween/iTweenEvent")] static void AddiTweenEvent () { if(Selection.activeGameObject != null) { Selection.activeGameObject.AddComponent(typeof(iTweenEvent)); } } [MenuItem("Component/iTween/Prepare Visual Editor for Javascript Usage")] static void CopyFilesForJavascriptUsage() { if(Directory.Exists(Application.dataPath + "/iTweenEditor/Helper Classes")) { if(!Directory.Exists(Application.dataPath + "/Plugins")) { Directory.CreateDirectory(Application.dataPath + "/Plugins"); } if(!Directory.Exists(Application.dataPath + "/Plugins/iTweenEditor")) { Directory.CreateDirectory(Application.dataPath + "/Plugins/iTweenEditor"); } FileUtil.MoveFileOrDirectory(Application.dataPath + "/iTweenEditor/Helper Classes", Application.dataPath + "/Plugins/iTweenEditor/Helper Classes"); FileUtil.MoveFileOrDirectory(Application.dataPath + "/iTweenEditor/iTweenEvent.cs", Application.dataPath + "/Plugins/iTweenEvent.cs"); FileUtil.MoveFileOrDirectory(Application.dataPath + "/iTweenEditor/iTween.cs", Application.dataPath + "/Plugins/iTween.cs"); FileUtil.MoveFileOrDirectory(Application.dataPath + "/iTweenEditor/iTweenPath.cs", Application.dataPath + "/Plugins/iTweenPath.cs"); AssetDatabase.Refresh(); } else { EditorUtility.DisplayDialog("Can't move files", "Your files have already been moved", "Ok"); } } [MenuItem("Component/iTween/Donate to support the Visual Editor")] static void Donate() { Application.OpenURL("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WD3GQ6HHD257C"); } public void OnEnable() { var evt = (iTweenEvent)target; foreach(var key in EventParamMappings.mappings[evt.type].Keys) { propertiesEnabled[key] = false; } previousType = evt.type; if(!Directory.Exists(Application.dataPath + "/Gizmos")) { Directory.CreateDirectory(Application.dataPath + "/Gizmos"); } if(!File.Exists(Application.dataPath + "/Gizmos/iTweenIcon.tif")) { FileUtil.CopyFileOrDirectory(Application.dataPath + "/iTweenEditor/Gizmos/iTweenIcon.tif", Application.dataPath + "/Gizmos/iTweenIcon.tif"); } } public override void OnInspectorGUI() { var evt = (iTweenEvent)target; values = evt.Values; var keys = values.Keys.ToArray(); foreach(var key in keys) { propertiesEnabled[key] = true; if(typeof(Vector3OrTransform) == EventParamMappings.mappings[evt.type][key]) { var val = new Vector3OrTransform(); if(null == values[key] || typeof(Transform) == values[key].GetType()) { if(null == values[key]) { val.transform = null; } else { val.transform = (Transform)values[key]; } val.selected = Vector3OrTransform.transformSelected; } else if(typeof(Vector3) == values[key].GetType()) { val.vector = (Vector3)values[key]; val.selected = Vector3OrTransform.vector3Selected; } values[key] = val; } if(typeof(Vector3OrTransformArray) == EventParamMappings.mappings[evt.type][key]) { var val = new Vector3OrTransformArray(); if(null == values[key] || typeof(Transform[]) == values[key].GetType()) { if(null == values[key]) { val.transformArray = null; } else { val.transformArray = (Transform[])values[key]; } val.selected = Vector3OrTransformArray.transformSelected; } else if(typeof(Vector3[]) == values[key].GetType()) { val.vectorArray = (Vector3[])values[key]; val.selected = Vector3OrTransformArray.vector3Selected; } else if(typeof(string) == values[key].GetType()) { val.pathName = (string)values[key]; val.selected = Vector3OrTransformArray.iTweenPathSelected; } values[key] = val; } } GUILayout.Label(string.Format("iTween Event Editor v{0}", iTweenEvent.VERSION)); EditorGUILayout.Separator(); GUILayout.BeginHorizontal(); GUILayout.Label("Name"); evt.tweenName = EditorGUILayout.TextField(evt.tweenName); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); evt.showIconInInspector = GUILayout.Toggle(evt.showIconInInspector, " Show Icon In Scene"); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); evt.playAutomatically = GUILayout.Toggle(evt.playAutomatically, " Play Automatically"); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Initial Start Delay (delay begins once the iTweenEvent is played)"); evt.delay = EditorGUILayout.FloatField(evt.delay); GUILayout.EndHorizontal(); EditorGUILayout.Separator(); GUILayout.BeginHorizontal(); GUILayout.Label("Event Type"); evt.type = (iTweenEvent.TweenType)EditorGUILayout.EnumPopup(evt.type); GUILayout.EndHorizontal(); if(evt.type != previousType) { foreach(var key in EventParamMappings.mappings[evt.type].Keys) { propertiesEnabled[key] = false; } evt.Values = new Dictionary<string, object>(); previousType = evt.type; return; } var properties = EventParamMappings.mappings[evt.type]; foreach(var pair in properties) { var key = pair.Key; GUILayout.BeginHorizontal(); if(EditorGUILayout.BeginToggleGroup(key, propertiesEnabled[key])) { propertiesEnabled[key] = true; GUILayout.BeginVertical(); if(typeof(string) == pair.Value) { values[key] = EditorGUILayout.TextField(values.ContainsKey(key) ? (string)values[key] : ""); } else if(typeof(float) == pair.Value) { values[key] = EditorGUILayout.FloatField(values.ContainsKey(key) ? (float)values[key] : 0); } else if(typeof(int) == pair.Value) { values[key] = EditorGUILayout.IntField(values.ContainsKey(key) ? (int)values[key] : 0); } else if(typeof(bool) == pair.Value) { GUILayout.BeginHorizontal(); var currentValueString = (values.ContainsKey(key) ? (bool)values[key] : false).ToString(); currentValueString = currentValueString.Substring(0, 1).ToUpper() + currentValueString.Substring(1); var index = EditorGUILayout.Popup(trueFalseOptions.IndexOf(currentValueString), trueFalseOptions.ToArray()); GUILayout.EndHorizontal(); values[key] = bool.Parse(trueFalseOptions[index]); } else if(typeof(GameObject) == pair.Value) { values[key] = EditorGUILayout.ObjectField(values.ContainsKey(key) ? (GameObject)values[key] : null, typeof(GameObject), true); } else if(typeof(Vector3) == pair.Value) { values[key] = EditorGUILayout.Vector3Field("", values.ContainsKey(key) ? (Vector3)values[key] : Vector3.zero); } else if(typeof(Vector3OrTransform) == pair.Value) { if(!values.ContainsKey(key)) { values[key] = new Vector3OrTransform(); } var val = (Vector3OrTransform)values[key]; val.selected = GUILayout.SelectionGrid(val.selected, Vector3OrTransform.choices, 2); if(Vector3OrTransform.vector3Selected == val.selected) { val.vector = EditorGUILayout.Vector3Field("", val.vector); } else { val.transform = (Transform)EditorGUILayout.ObjectField(val.transform, typeof(Transform), true); } values[key] = val; } else if(typeof(Vector3OrTransformArray) == pair.Value) { if(!values.ContainsKey(key)) { values[key] = new Vector3OrTransformArray(); } var val = (Vector3OrTransformArray)values[key]; val.selected = GUILayout.SelectionGrid(val.selected, Vector3OrTransformArray.choices, Vector3OrTransformArray.choices.Length); if(Vector3OrTransformArray.vector3Selected == val.selected) { if(null == val.vectorArray) { val.vectorArray = new Vector3[0]; } var elements = val.vectorArray.Length; GUILayout.BeginHorizontal(); GUILayout.Label("Number of points"); elements = EditorGUILayout.IntField(elements); GUILayout.EndHorizontal(); if(elements != val.vectorArray.Length) { var resizedArray = new Vector3[elements]; val.vectorArray.CopyTo(resizedArray, 0); val.vectorArray = resizedArray; } for(var i = 0; i < val.vectorArray.Length; ++i) { val.vectorArray[i] = EditorGUILayout.Vector3Field("", val.vectorArray[i]); } } else if(Vector3OrTransformArray.transformSelected == val.selected) { if(null == val.transformArray) { val.transformArray = new Transform[0]; } var elements = val.transformArray.Length; GUILayout.BeginHorizontal(); GUILayout.Label("Number of points"); elements = EditorGUILayout.IntField(elements); GUILayout.EndHorizontal(); if(elements != val.transformArray.Length) { var resizedArray = new Transform[elements]; val.transformArray.CopyTo(resizedArray, 0); val.transformArray = resizedArray; } for(var i = 0; i < val.transformArray.Length; ++i) { val.transformArray[i] = (Transform)EditorGUILayout.ObjectField(val.transformArray[i], typeof(Transform), true); } } else if(Vector3OrTransformArray.iTweenPathSelected == val.selected) { var index = 0; var paths = (GameObject.FindObjectsOfType(typeof(iTweenPath)) as iTweenPath[]); if(0 == paths.Length) { val.pathName = ""; GUILayout.Label("No paths are defined"); } else { for(var i = 0; i < paths.Length; ++i) { if(paths[i].pathName == val.pathName) { index = i; } } index = EditorGUILayout.Popup(index, (GameObject.FindObjectsOfType(typeof(iTweenPath)) as iTweenPath[]).Select(path => path.pathName).ToArray()); val.pathName = paths[index].pathName; } } values[key] = val; } else if(typeof(iTween.LoopType) == pair.Value) { values[key] = EditorGUILayout.EnumPopup(values.ContainsKey(key) ? (iTween.LoopType)values[key] : iTween.LoopType.none); } else if(typeof(iTween.EaseType) == pair.Value) { values[key] = EditorGUILayout.EnumPopup(values.ContainsKey(key) ? (iTween.EaseType)values[key] : iTween.EaseType.linear); } else if(typeof(AudioSource) == pair.Value) { values[key] = (AudioSource)EditorGUILayout.ObjectField(values.ContainsKey(key) ? (AudioSource)values[key] : null, typeof(AudioSource), true); } else if(typeof(AudioClip) == pair.Value) { values[key] = (AudioClip)EditorGUILayout.ObjectField(values.ContainsKey(key) ? (AudioClip)values[key] : null, typeof(AudioClip), true); } else if(typeof(Color) == pair.Value) { values[key] = EditorGUILayout.ColorField(values.ContainsKey(key) ? (Color)values[key] : Color.white); } else if(typeof(Space) == pair.Value) { values[key] = EditorGUILayout.EnumPopup(values.ContainsKey(key) ? (Space)values[key] : Space.Self); } GUILayout.EndVertical(); } else { propertiesEnabled[key] = false; values.Remove(key); } EditorGUILayout.EndToggleGroup(); GUILayout.EndHorizontal(); EditorGUILayout.Separator(); } keys = values.Keys.ToArray(); foreach(var key in keys) { if(values[key] != null && values[key].GetType() == typeof(Vector3OrTransform)) { var val = (Vector3OrTransform)values[key]; if(Vector3OrTransform.vector3Selected == val.selected) { values[key] = val.vector; } else { values[key] = val.transform; } } else if(values[key] != null && values[key].GetType() == typeof(Vector3OrTransformArray)) { var val = (Vector3OrTransformArray)values[key]; if(Vector3OrTransformArray.vector3Selected == val.selected) { values[key] = val.vectorArray; } else if(Vector3OrTransformArray.transformSelected == val.selected) { values[key] = val.transformArray; } else if(Vector3OrTransformArray.iTweenPathSelected == val.selected) { values[key] = val.pathName; } } } evt.Values = values; previousType = evt.type; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Search { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for IndexersOperations. /// </summary> public static partial class IndexersOperationsExtensions { /// <summary> /// Resets the change tracking state associated with an Azure Search indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946897.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to reset. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static void Reset(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { Task.Factory.StartNew(s => ((IIndexersOperations)s).ResetAsync(indexerName, searchRequestOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Resets the change tracking state associated with an Azure Search indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946897.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to reset. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task ResetAsync(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { await operations.ResetWithHttpMessagesAsync(indexerName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Runs an Azure Search indexer on-demand. /// <see href="https://msdn.microsoft.com/library/azure/dn946885.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to run. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static void Run(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { Task.Factory.StartNew(s => ((IIndexersOperations)s).RunAsync(indexerName, searchRequestOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Runs an Azure Search indexer on-demand. /// <see href="https://msdn.microsoft.com/library/azure/dn946885.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to run. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task RunAsync(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { await operations.RunWithHttpMessagesAsync(indexerName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates a new Azure Search indexer or updates an indexer if it already /// exists. /// <see href="https://msdn.microsoft.com/library/azure/dn946899.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to create or update. /// </param> /// <param name='indexer'> /// The definition of the indexer to create or update. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='accessCondition'> /// Additional parameters for the operation /// </param> public static Indexer CreateOrUpdate(this IIndexersOperations operations, string indexerName, Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), AccessCondition accessCondition = default(AccessCondition)) { return Task.Factory.StartNew(s => ((IIndexersOperations)s).CreateOrUpdateAsync(indexerName, indexer, searchRequestOptions, accessCondition), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a new Azure Search indexer or updates an indexer if it already /// exists. /// <see href="https://msdn.microsoft.com/library/azure/dn946899.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to create or update. /// </param> /// <param name='indexer'> /// The definition of the indexer to create or update. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='accessCondition'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Indexer> CreateOrUpdateAsync(this IIndexersOperations operations, string indexerName, Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), AccessCondition accessCondition = default(AccessCondition), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(indexerName, indexer, searchRequestOptions, accessCondition, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an Azure Search indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946898.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to delete. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='accessCondition'> /// Additional parameters for the operation /// </param> public static void Delete(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), AccessCondition accessCondition = default(AccessCondition)) { Task.Factory.StartNew(s => ((IIndexersOperations)s).DeleteAsync(indexerName, searchRequestOptions, accessCondition), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes an Azure Search indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946898.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to delete. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='accessCondition'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), AccessCondition accessCondition = default(AccessCondition), CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(indexerName, searchRequestOptions, accessCondition, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Retrieves an indexer definition from Azure Search. /// <see href="https://msdn.microsoft.com/library/azure/dn946874.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to retrieve. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static Indexer Get(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return Task.Factory.StartNew(s => ((IIndexersOperations)s).GetAsync(indexerName, searchRequestOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieves an indexer definition from Azure Search. /// <see href="https://msdn.microsoft.com/library/azure/dn946874.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to retrieve. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Indexer> GetAsync(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(indexerName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all indexers available for an Azure Search service. /// <see href="https://msdn.microsoft.com/library/azure/dn946883.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static IndexerListResult List(this IIndexersOperations operations, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return Task.Factory.StartNew(s => ((IIndexersOperations)s).ListAsync(searchRequestOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all indexers available for an Azure Search service. /// <see href="https://msdn.microsoft.com/library/azure/dn946883.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IndexerListResult> ListAsync(this IIndexersOperations operations, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a new Azure Search indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946899.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexer'> /// The definition of the indexer to create. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static Indexer Create(this IIndexersOperations operations, Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return Task.Factory.StartNew(s => ((IIndexersOperations)s).CreateAsync(indexer, searchRequestOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a new Azure Search indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946899.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexer'> /// The definition of the indexer to create. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Indexer> CreateAsync(this IIndexersOperations operations, Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(indexer, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns the current status and execution history of an indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946884.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer for which to retrieve status. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static IndexerExecutionInfo GetStatus(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return Task.Factory.StartNew(s => ((IIndexersOperations)s).GetStatusAsync(indexerName, searchRequestOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns the current status and execution history of an indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946884.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer for which to retrieve status. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IndexerExecutionInfo> GetStatusAsync(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetStatusWithHttpMessagesAsync(indexerName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Management.Automation; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Xml; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Management.ServiceManagement.Extensions; using Microsoft.WindowsAzure.Management.ServiceManagement.Model; using Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.ConfigDataInfo; using Microsoft.WindowsAzure.Management.ServiceManagement.Test.Properties; using Microsoft.WindowsAzure.ServiceManagement; [TestClass] public class FunctionalTestCommonVhd : ServiceManagementTest { private const string vhdNamePrefix = "os.vhd"; private string vhdName; protected static string vhdBlobLocation; [ClassInitialize] public static void ClassInit(TestContext context) { //SetTestSettings(); if (defaultAzureSubscription.Equals(null)) { Assert.Inconclusive("No Subscription is selected!"); } vhdBlobLocation = string.Format("{0}{1}/{2}", blobUrlRoot, vhdContainerName, vhdNamePrefix); if (string.IsNullOrEmpty(localFile)) { try { CredentialHelper.CopyTestData(testDataContainer, osVhdName, vhdContainerName, vhdNamePrefix); } catch (Exception e) { Console.WriteLine(e.ToString()); Assert.Inconclusive("Upload vhd is not set!"); } } else { try { vmPowershellCmdlets.AddAzureVhd(new FileInfo(localFile), vhdBlobLocation); } catch (Exception e) { if (e.ToString().Contains("already exists")) { // Use the already uploaded vhd. Console.WriteLine("Using already uploaded blob.."); } else { throw; } } } } [TestInitialize] public void Initialize() { vhdName = Utilities.GetUniqueShortName(vhdNamePrefix); CopyCommonVhd(vhdContainerName, vhdNamePrefix, vhdName); pass = false; testStartTime = DateTime.Now; } [TestMethod(), TestCategory("Functional"), TestCategory("BVT"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Update,Remove)-AzureDisk)")] public void AzureDiskTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string mediaLocation = String.Format("{0}{1}/{2}", blobUrlRoot, vhdContainerName, vhdName); try { vmPowershellCmdlets.AddAzureDisk(vhdName, mediaLocation, vhdName, null); bool found = false; foreach (DiskContext disk in vmPowershellCmdlets.GetAzureDisk(vhdName)) { Console.WriteLine("Disk: Name - {0}, Label - {1}, Size - {2},", disk.DiskName, disk.Label, disk.DiskSizeInGB); if (disk.DiskName == vhdName && disk.Label == vhdName) { found = true; Console.WriteLine("{0} is found", disk.DiskName); } } Assert.IsTrue(found, "Error: Disk is not added"); string newLabel = "NewLabel"; vmPowershellCmdlets.UpdateAzureDisk(vhdName, newLabel); DiskContext disk2 = vmPowershellCmdlets.GetAzureDisk(vhdName)[0]; Console.WriteLine("Disk: Name - {0}, Label - {1}, Size - {2},", disk2.DiskName, disk2.Label, disk2.DiskSizeInGB); Assert.AreEqual(newLabel, disk2.Label); Console.WriteLine("Disk Label is successfully updated"); vmPowershellCmdlets.RemoveAzureDisk(vhdName, false); Assert.IsTrue(Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDisk, vhdName), "The disk was not removed"); pass = true; } catch (Exception e) { pass = false; if (e.ToString().Contains("ResourceNotFound")) { Console.WriteLine("Please upload {0} file to \\vhdtest\\ blob directory before running this test", vhdName); } Assert.Fail("Exception occurs: {0}", e.ToString()); } } private void CopyCommonVhd(string vhdContainerName, string vhdName, string myVhdName) { vmPowershellCmdlets.RunPSScript(string.Format("Start-AzureStorageBlobCopy -SrcContainer {0} -SrcBlob {1} -DestContainer {2} -DestBlob {3}", vhdContainerName, vhdName, vhdContainerName, myVhdName)); } [TestMethod(), TestCategory("Functional"), TestCategory("BVT"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Save,Update,Remove)-AzureVMImage)")] public void AzureVMImageTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newImageName = Utilities.GetUniqueShortName("vmimage"); string mediaLocation = string.Format("{0}{1}/{2}", blobUrlRoot, vhdContainerName, vhdName); string oldLabel = "old label"; string newLabel = "new label"; try { OSImageContext result = vmPowershellCmdlets.AddAzureVMImage(newImageName, mediaLocation, OS.Windows, oldLabel); OSImageContext resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0]; Assert.IsTrue(CompareContext<OSImageContext>(result, resultReturned)); result = vmPowershellCmdlets.UpdateAzureVMImage(newImageName, newLabel); resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0]; Assert.IsTrue(CompareContext<OSImageContext>(result, resultReturned)); vmPowershellCmdlets.RemoveAzureVMImage(newImageName, true); Assert.IsTrue(Utilities.CheckRemove(vmPowershellCmdlets.GetAzureVMImage, newImageName)); pass = true; } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } finally { if (!Utilities.CheckRemove(vmPowershellCmdlets.GetAzureVMImage, newImageName)) { vmPowershellCmdlets.RemoveAzureVMImage(newImageName, true); } } } /// <summary> /// /// </summary> [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Set-AzureVMSize)")] public void AzureVMImageSizeTest() { string newImageName = Utilities.GetUniqueShortName("vmimage"); string mediaLocation = string.Format("{0}{1}/{2}", blobUrlRoot, vhdContainerName, vhdName); try { Array instanceSizes = Enum.GetValues(typeof(InstanceSize)); int arrayLength = instanceSizes.GetLength(0); for (int i = 1; i < arrayLength; i++) { // Add-AzureVMImage test for VM size OSImageContext result = vmPowershellCmdlets.AddAzureVMImage(newImageName, mediaLocation, OS.Windows, (InstanceSize)instanceSizes.GetValue(i)); OSImageContext resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0]; Assert.IsTrue(CompareContext<OSImageContext>(result, resultReturned)); // Update-AzureVMImage test for VM size result = vmPowershellCmdlets.UpdateAzureVMImage(newImageName, (InstanceSize)instanceSizes.GetValue(Math.Max((i + 1) % arrayLength, 1))); resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0]; Assert.IsTrue(CompareContext<OSImageContext>(result, resultReturned)); vmPowershellCmdlets.RemoveAzureVMImage(newImageName); } } catch (Exception e) { pass = false; Console.WriteLine("Exception occurred: {0}", e.ToString()); throw; } } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Set-AzureVMSize)")] public void HiMemVMSizeTest() { string serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); string vmName = Utilities.GetUniqueShortName(vmNamePrefix); try { PersistentVMRoleContext result; // New-AzureQuickVM test for VM size vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, vmName, serviceName, imageName, username, password, locationName, InstanceSize.A6); result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); Assert.AreEqual(InstanceSize.A6.ToString(), result.InstanceSize); Console.WriteLine("VM size, {0}, is verified for New-AzureQuickVM", InstanceSize.A6.ToString()); vmPowershellCmdlets.RemoveAzureService(serviceName); // New-AzureVMConfig test for VM size AzureVMConfigInfo azureVMConfigInfo = new AzureVMConfigInfo(vmName, InstanceSize.A7, imageName); AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, username, password); PersistentVMConfigInfo persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null); PersistentVM vm = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo); vmPowershellCmdlets.NewAzureVM(serviceName, new[] { vm }, locationName); result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); Assert.AreEqual(InstanceSize.A7.ToString(), result.InstanceSize); Console.WriteLine("VM size, {0}, is verified for New-AzureVMConfig", InstanceSize.A7.ToString()); // Set-AzureVMSize test for Hi-MEM VM size vmPowershellCmdlets.SetVMSize(vmName, serviceName, new SetAzureVMSizeConfig(InstanceSize.A6)); result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); Assert.AreEqual(InstanceSize.A6.ToString(), result.InstanceSize); Console.WriteLine("SetVMSize is verified from A7 to A6"); vmPowershellCmdlets.SetVMSize(vmName, serviceName, new SetAzureVMSizeConfig(InstanceSize.A7)); result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); Assert.AreEqual(InstanceSize.A7.ToString(), result.InstanceSize); Console.WriteLine("SetVMSize is verified from A6 to A7"); } catch (Exception e) { pass = false; Console.WriteLine("Exception occurred: {0}", e.ToString()); throw; } finally { if (!Utilities.CheckRemove(vmPowershellCmdlets.GetAzureService, serviceName)) { if ((cleanupIfFailed && !pass) || (cleanupIfPassed && pass)) { vmPowershellCmdlets.RemoveAzureService(serviceName); } } } } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Set-AzureVMSize)")] public void RegularVMSizeTest() { string serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); string vmName = Utilities.GetUniqueShortName(vmNamePrefix); try { Array instanceSizes = Enum.GetValues(typeof(InstanceSize)); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, vmName, serviceName, imageName, username, password, locationName, InstanceSize.A6); PersistentVMRoleContext result; foreach (InstanceSize size in instanceSizes) { if (!size.Equals(InstanceSize.A6) && !size.Equals(InstanceSize.A7)) { // Set-AzureVMSize test for regular VM size vmPowershellCmdlets.SetVMSize(vmName, serviceName, new SetAzureVMSizeConfig(size)); result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); Assert.AreEqual(size.ToString(), result.InstanceSize); Console.WriteLine("VM size, {0}, is verified for Set-AzureVMSize", size.ToString()); } if (size.Equals(InstanceSize.ExtraLarge)) { vmPowershellCmdlets.SetVMSize(vmName, serviceName, new SetAzureVMSizeConfig(InstanceSize.Small)); result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); Assert.AreEqual(InstanceSize.Small.ToString(), result.InstanceSize); } } pass = true; } catch (Exception e) { pass = false; Console.WriteLine("Exception occurred: {0}", e.ToString()); throw; } finally { if (!Utilities.CheckRemove(vmPowershellCmdlets.GetAzureService, serviceName)) { if ((cleanupIfFailed && !pass) || (cleanupIfPassed && pass)) { vmPowershellCmdlets.RemoveAzureService(serviceName); } } } } private bool CompareContext<T>(T obj1, T obj2) { bool result = true; Type type = typeof(T); foreach(PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { string typeName = property.PropertyType.FullName; if (typeName.Equals("System.String") || typeName.Equals("System.Int32") || typeName.Equals("System.Uri") || typeName.Contains("Nullable")) { var obj1Value = property.GetValue(obj1, null); var obj2Value = property.GetValue(obj2, null); if (obj1Value == null) { result &= (obj2Value == null); } else { result &= (obj1Value.Equals(obj2Value)); } } else { Console.WriteLine("This type is not compared: {0}", typeName); } } return result; } [TestCleanup] public virtual void CleanUp() { Console.WriteLine("Test {0}", pass ? "passed" : "failed"); } } }
/* Vernash * Stream cipher based on the Vernam cipher and Variable-Length Hashes * * Author: * Stefano 'Shen139' Alimonti * * Website: * http://lab.openwebspider.org/vernash/ * */ using System; using System.Text; using System.IO; namespace Vernash { class vernash { private int BLOCKS = 256; private int EXPANSION = 2; private int RANDOM_EXPANSION = 2; public static string vernashFileHeader = "VERNASH"; private uint MAX_OUTPUT_LENGTH = 100000; //100k private static string msg001 = "Crypted text is too long. Please save it to a file using the \"Crypt a File To another File\" button!"; private static string msg002 = "DeCrypted text is too long. Please save it to a file using the \"DeCrypt a File To another File\" button!"; /* RotCharUp */ private char RotCharUp(int value, char lBound, char rBound) { value += (lBound * 2); return (char)(lBound + ((value - lBound) % (rBound - lBound))); } /* RotCharDown */ private char RotCharDown(int value, char lBound, char rBound) { value -= (lBound * 2); value = (value - lBound) % (rBound - lBound); if (value == 0) return lBound; return (char)(rBound + value); } private static void Swap(ref int a, ref int b) { int tmp = a; a = b; b = tmp; } /* genKeyPos * Generates pseudorandom order for the string to be shuffled. */ public int[] genKeyPos(int nPos, string key) { int[] iPos = new int[nPos]; int newPos; int curW = 0; //init for (int i = 0; i < nPos; i++) iPos[i] = i; for (int x = 0; x < nPos; x++) { for (int y = 0; y < key.Length; y++) { newPos = ((y + 1) * 2 + (x + 13) * 3 + nPos * 4 + (key.Length + 12) * 5 + key[y] * 13 + key[curW] * 7); newPos = (newPos + key[y] + 1) % nPos; curW++; if (curW >= key.Length) curW = 0; // swap Swap(ref iPos[x], ref iPos[newPos]); } } return iPos; } /* scrambleText * Shuffles a string. * * Example: * scrambleText ("12345", "password"); ==> "53241" * unScrambleText("53241", "password"); ==> "12345" * * scrambleText("abcdefghilmnopq1234567", "passphrase"); == "chan43mlopqdif6bg127e5" * */ public string scrambleText(string text, string key, int[] iPos) { char[] scrambled = new char[text.Length]; // Optimizations if (text.Length % 4 == 0) { for (int x = 0; x < text.Length / 4; x++) { // swap scrambled[x * 4] = text[iPos[x * 4]]; scrambled[(x * 4) + 1] = text[iPos[(x * 4) + 1]]; scrambled[(x * 4) + 2] = text[iPos[(x * 4) + 2]]; scrambled[(x * 4) + 3] = text[iPos[(x * 4) + 3]]; } } else if (text.Length % 2 == 0) { for (int x = 0; x < text.Length / 2; x++) { // swap scrambled[x * 2] = text[iPos[x * 2]]; scrambled[(x * 2) + 1] = text[iPos[(x * 2) + 1]]; } } else { for (int x = 0; x < text.Length; x++) { // swap scrambled[x] = text[iPos[x]]; } } return new string(scrambled); } /* unScrambleText * * Example: * scrambleText ("12345", "password"); ==> "53241" * unScrambleText("53241", "password"); ==> "12345" * * unScrambleText("chan43mlopqdif6bg127e5", "passphrase"); == "abcdefghilmnopq1234567" * */ public string unScrambleText(string text, string key, int[] iPos) { char[] scrambled = new char[text.Length]; // Swap for (int x = 0; x < text.Length; x++) { scrambled[iPos[x]] = text[x]; } return new string(scrambled); } /* hashum * Variable-Length Hashes Generator */ public string hashum(string sWord, int iTextLength) { char[] hash = new char[iTextLength]; if (sWord.Length < 1) return string.Empty; int x, y; int curC; int curW = 0; Array.Clear(hash, 0, hash.Length); for (x = 0; x < iTextLength; x++) { for (y = 0; y < iTextLength; y++) { curC = (sWord[curW] + hash[x] + hash[y] + x + y + curW) % 139; curW++; if (curW >= sWord.Length) curW = 0; hash[x] = RotCharUp(curC + sWord.Length, 'A', 'Z'); curC += sWord.Length + curW + iTextLength + x + y + (((x + y + curC) * 9) % 139); hash[y] = RotCharUp(curC, 'A', 'Z'); } } return new string(hash); } /* expandText * expandText("ABC") ==> "414243" */ private string expandText(byte[] text) { //string expandedText = string.Empty; // OLD Version /* foreach (byte c in text) { expandedText += String.Format("{0:X" + EXPANSION + "}", (int)c); } return expandedText; */ StringBuilder expandedText = new StringBuilder(); if (text.Length % 2 == 0) { for (uint i = 0; i < text.Length / 2; i++) { expandedText.Append(String.Format("{0:X" + EXPANSION + "}", (int)text[i * 2])); expandedText.Append(String.Format("{0:X" + EXPANSION + "}", (int)text[(i * 2 ) + 1])); } } else { for (uint i = 0; i < text.Length; i++) { expandedText.Append(String.Format("{0:X" + EXPANSION + "}", (int)text[i])); } } return expandedText.ToString(); } /* reduceString * reduceString("414243") = "ABC" */ private byte[] reduceString(string text) { byte[] reducedT = new byte[text.Length / EXPANSION]; int iTP; int i = 0; int pos = 0; try { for (i = 0; i < text.Length; i += EXPANSION) { iTP = Convert.ToInt32(text.Substring(i, EXPANSION), 16); reducedT[pos] = (byte)iTP; pos++; } } catch { reducedT = null; } return reducedT; } /* randomExpansion * Expand 1 byte to 2 bytes: * 1# byte is a random number from 0 to byte value * 2# is the rest. * * Example: randomExpansion('a') => * random_number = random number from 0 to 'a' * randomExpansion = random_number & ('a' - random_number) * ==> random_number + 'a' - random_number = 'a' */ private byte[] randomExpansion(byte[] text) { byte[] expandedText = new byte[text.Length * 2]; int i = 0; Random random = new Random(); for (uint c = 0; c < text.Length; c++) { expandedText[i++] = (byte)random.Next(0, ((int)text[c])); expandedText[i++] = (byte)(((int)text[c]) - expandedText[i - 2]); } return expandedText; } /* randomReduction * randomReduction("xyzkts") => x+y & z+k & t+s * x, z and t are random generated numbers; * y, k and s are complementary values of their respective random genetare value; * * x+y = original char1 * z+k = original char2 * t+s = original char3 */ private byte[] randomReduction(byte[] text) { byte[] reducedT = new byte[text.Length / 2]; for (int i = 0; i < text.Length / 2; i++) { reducedT[i] = (byte)((int)text[i * 2] + (int)text[(i * 2) + 1]); } return reducedT; } /* vernashCrypt * Crypt text with password (key) */ public string vernashCrypt(byte[] text, string key, bool saveToFile, string filename) { int textLen; StringBuilder res = new StringBuilder(vernashFileHeader); string hashKey = string.Empty; int lastLength = 0; string exKey = expandText(System.Text.Encoding.UTF8.GetBytes(key)); byte[] tmpExText; string exText; char[] crtText; int i; int[] scramblePos = null; // saveToFile ?!? FileStream fileStream; BinaryWriter bw = null; if (saveToFile) { try { fileStream = new FileStream(filename, FileMode.Create); bw = new BinaryWriter(fileStream); // writes header : "VERNASH" bw.Write(System.Text.Encoding.UTF8.GetBytes(vernashFileHeader)); } catch (Exception e) { return "ERROR: " + e.Message; } } for (int p = 0; p < text.Length; p += BLOCKS) { tmpExText = new byte[Math.Min(BLOCKS, text.Length - p)]; Buffer.BlockCopy(text, p, tmpExText, 0, Math.Min(BLOCKS, text.Length - p)); /* * 1) Expand text with pseudorandom chars * 2) Expand to HEX chars (example: "ABC" = "414243") * 3) Scramble text (example: "12345" => "43521") */ exText = expandText(randomExpansion(tmpExText)); if (exText.Length != lastLength) scramblePos = genKeyPos(exText.Length, key); exText = scrambleText(exText, key, scramblePos); textLen = exText.Length; crtText = new char[textLen]; if (exText.Length == 0 || key.Length == 0) return res.ToString(); if (lastLength != textLen) { hashKey = hashum(exKey, textLen); lastLength = textLen; } if (hashKey.Length == 0) return res.ToString(); for (i = 0; i < textLen; i++) crtText[i] = RotCharUp(hashKey[i] + exText[i], '0', 'Z'); if (saveToFile) { try { bw.Write(System.Text.Encoding.UTF8.GetBytes(new string(crtText, 0, textLen))); } catch (Exception e) { return "ERROR: " + e.Message; } } else { if (res.Length + textLen > MAX_OUTPUT_LENGTH) return msg001; res.Append(new string(crtText, 0, textLen)); } } if (saveToFile) bw.Close(); return res.ToString(); } /* vernashDeCrypt * DeCrypt text with password (key) */ public byte[] vernashDeCrypt(string text, string key, bool saveToFile, string filename) { int textLen; byte[] res = new byte[text.Length / EXPANSION / RANDOM_EXPANSION]; byte[] redString; string hashKey = string.Empty; int lastLength = 0; string exKey = expandText(System.Text.Encoding.UTF8.GetBytes(key)); string exText; char[] crtText; int i; int[] scramblePos = null; // check valid VERNASH Cipher if (text.Length < vernashFileHeader.Length + 4) return null; else if (text.Substring(0, vernashFileHeader.Length) != vernash.vernashFileHeader) return null; else text = text.Substring(vernashFileHeader.Length); // saveToFile ?!? FileStream fileStream; BinaryWriter bw = null; if (saveToFile) { try { fileStream = new FileStream(filename, FileMode.Create); bw = new BinaryWriter(fileStream); } catch (Exception e) { return System.Text.Encoding.UTF8.GetBytes("ERROR: " + e.Message); } } for (int p = 0; p < text.Length; p += BLOCKS * EXPANSION * RANDOM_EXPANSION) { exText = text.Substring(p, Math.Min(BLOCKS * EXPANSION * RANDOM_EXPANSION, text.Length - p)); textLen = exText.Length; crtText = new char[textLen]; if (exText.Length == 0 || key.Length == 0) return null; if (lastLength != textLen) { hashKey = hashum(exKey, textLen); lastLength = textLen; scramblePos = genKeyPos(exText.Length, key); } if (hashKey.Length == 0) return null; for (i = 0; i < textLen; i++) crtText[i] = RotCharDown(exText[i] - hashKey[i], '0', 'Z'); // Scramble the string to the origin; and reduce it (from HEX to bytes) redString = reduceString(unScrambleText(new string(crtText, 0, textLen), key, scramblePos)); if (redString == null) { return null; } // Remove pseudorandom characters (Example: randomReduction("xyzk") => x+y & z+k ) redString = randomReduction(redString); if (saveToFile) { try { bw.Write(redString, 0, redString.Length); } catch (Exception e) { return System.Text.Encoding.UTF8.GetBytes("ERROR: " + e.Message); } } else { if (res.Length + textLen > MAX_OUTPUT_LENGTH) return System.Text.Encoding.UTF8.GetBytes(msg002); Buffer.BlockCopy(redString, 0, res, p / EXPANSION / RANDOM_EXPANSION, redString.Length); } } if (saveToFile) bw.Close(); return res; } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// A secret /// First published in XenServer 5.6. /// </summary> public partial class Secret : XenObject<Secret> { #region Constructors public Secret() { } public Secret(string uuid, string value, Dictionary<string, string> other_config) { this.uuid = uuid; this.value = value; this.other_config = other_config; } /// <summary> /// Creates a new Secret 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 Secret(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new Secret from a Proxy_Secret. /// </summary> /// <param name="proxy"></param> public Secret(Proxy_Secret proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given Secret. /// </summary> public override void UpdateFrom(Secret update) { uuid = update.uuid; value = update.value; other_config = update.other_config; } internal void UpdateFrom(Proxy_Secret proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; value = proxy.value == null ? null : proxy.value; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_Secret ToProxy() { Proxy_Secret result_ = new Proxy_Secret(); result_.uuid = uuid ?? ""; result_.value = value ?? ""; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this Secret /// 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("value")) value = Marshalling.ParseString(table, "value"); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Secret other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._value, other._value) && Helper.AreEqual2(this._other_config, other._other_config); } internal static List<Secret> ProxyArrayToObjectList(Proxy_Secret[] input) { var result = new List<Secret>(); foreach (var item in input) result.Add(new Secret(item)); return result; } public override string SaveChanges(Session session, string opaqueRef, Secret server) { if (opaqueRef == null) { var reference = create(session, this); return reference == null ? null : reference.opaque_ref; } else { if (!Helper.AreEqual2(_value, server._value)) { Secret.set_value(session, opaqueRef, _value); } if (!Helper.AreEqual2(_other_config, server._other_config)) { Secret.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> public static Secret get_record(Session session, string _secret) { if (session.JsonRpcClient != null) return session.JsonRpcClient.secret_get_record(session.opaque_ref, _secret); else return new Secret(session.proxy.secret_get_record(session.opaque_ref, _secret ?? "").parse()); } /// <summary> /// Get a reference to the secret instance with the specified UUID. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<Secret> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.secret_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<Secret>.Create(session.proxy.secret_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Create a new secret instance, and return its handle. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<Secret> create(Session session, Secret _record) { if (session.JsonRpcClient != null) return session.JsonRpcClient.secret_create(session.opaque_ref, _record); else return XenRef<Secret>.Create(session.proxy.secret_create(session.opaque_ref, _record.ToProxy()).parse()); } /// <summary> /// Create a new secret instance, and return its handle. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<Task> async_create(Session session, Secret _record) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_secret_create(session.opaque_ref, _record); else return XenRef<Task>.Create(session.proxy.async_secret_create(session.opaque_ref, _record.ToProxy()).parse()); } /// <summary> /// Destroy the specified secret instance. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> public static void destroy(Session session, string _secret) { if (session.JsonRpcClient != null) session.JsonRpcClient.secret_destroy(session.opaque_ref, _secret); else session.proxy.secret_destroy(session.opaque_ref, _secret ?? "").parse(); } /// <summary> /// Destroy the specified secret instance. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> public static XenRef<Task> async_destroy(Session session, string _secret) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_secret_destroy(session.opaque_ref, _secret); else return XenRef<Task>.Create(session.proxy.async_secret_destroy(session.opaque_ref, _secret ?? "").parse()); } /// <summary> /// Get the uuid field of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> public static string get_uuid(Session session, string _secret) { if (session.JsonRpcClient != null) return session.JsonRpcClient.secret_get_uuid(session.opaque_ref, _secret); else return session.proxy.secret_get_uuid(session.opaque_ref, _secret ?? "").parse(); } /// <summary> /// Get the value field of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> public static string get_value(Session session, string _secret) { if (session.JsonRpcClient != null) return session.JsonRpcClient.secret_get_value(session.opaque_ref, _secret); else return session.proxy.secret_get_value(session.opaque_ref, _secret ?? "").parse(); } /// <summary> /// Get the other_config field of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> public static Dictionary<string, string> get_other_config(Session session, string _secret) { if (session.JsonRpcClient != null) return session.JsonRpcClient.secret_get_other_config(session.opaque_ref, _secret); else return Maps.convert_from_proxy_string_string(session.proxy.secret_get_other_config(session.opaque_ref, _secret ?? "").parse()); } /// <summary> /// Set the value field of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> /// <param name="_value">New value to set</param> public static void set_value(Session session, string _secret, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.secret_set_value(session.opaque_ref, _secret, _value); else session.proxy.secret_set_value(session.opaque_ref, _secret ?? "", _value ?? "").parse(); } /// <summary> /// Set the other_config field of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _secret, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) session.JsonRpcClient.secret_set_other_config(session.opaque_ref, _secret, _other_config); else session.proxy.secret_set_other_config(session.opaque_ref, _secret ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</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 _secret, string _key, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.secret_add_to_other_config(session.opaque_ref, _secret, _key, _value); else session.proxy.secret_add_to_other_config(session.opaque_ref, _secret ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given secret. If the key is not in that Map, then do nothing. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _secret, string _key) { if (session.JsonRpcClient != null) session.JsonRpcClient.secret_remove_from_other_config(session.opaque_ref, _secret, _key); else session.proxy.secret_remove_from_other_config(session.opaque_ref, _secret ?? "", _key ?? "").parse(); } /// <summary> /// Return a list of all the secrets known to the system. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> public static List<XenRef<Secret>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.secret_get_all(session.opaque_ref); else return XenRef<Secret>.Create(session.proxy.secret_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the secret Records at once, in a single XML RPC call /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Secret>, Secret> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.secret_get_all_records(session.opaque_ref); else return XenRef<Secret>.Create<Proxy_Secret>(session.proxy.secret_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; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// the secret /// </summary> public virtual string value { get { return _value; } set { if (!Helper.AreEqual(value, _value)) { _value = value; Changed = true; NotifyPropertyChanged("value"); } } } private string _value = ""; /// <summary> /// other_config /// </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; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Linq; using System.Runtime.InteropServices; using Xunit; using Roslyn.Test.PdbUtilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MissingAssemblyTests : ExpressionCompilerTestBase { [Fact] public void ErrorsWithAssemblyIdentityArguments() { var identity = new AssemblyIdentity(GetUniqueName()); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, identity)); } [Fact] public void ErrorsWithAssemblySymbolArguments() { var assembly = CreateCompilation("").Assembly; var identity = assembly.Identity; Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_GlobalSingleTypeNameNotFoundFwd, assembly)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd, assembly)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_SingleTypeNameNotFoundFwd, assembly)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_NameNotInContextPossibleMissingReference, assembly)); } [Fact] public void ErrorsRequiringSystemCore() { var identity = EvaluationContextBase.SystemCoreIdentity; Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_DynamicAttributeMissing)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_DynamicRequiredTypesMissing)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_QueryNoProviderStandard)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_ExtensionAttrNotFound)); } [Fact] public void MultipleAssemblyArguments() { var identity1 = new AssemblyIdentity(GetUniqueName()); var identity2 = new AssemblyIdentity(GetUniqueName()); Assert.Equal(identity1, GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, identity1, identity2)); Assert.Equal(identity2, GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, identity2, identity1)); } [Fact] public void NoAssemblyArguments() { Assert.Null(GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef)); Assert.Null(GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, "Not an assembly")); } [Fact] public void ERR_NoTypeDef() { var libSource = @" public class Missing { } "; var source = @" public class C { public void M(Missing parameter) { } } "; var libRef = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib").EmitToImageReference(); var comp = CreateCompilationWithMscorlib(source, new[] { libRef }, TestOptions.DebugDll); var context = CreateMethodContextWithReferences(comp, "C.M", MscorlibRef); var expectedError = "error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'."; var expectedMissingAssemblyIdentity = new AssemblyIdentity("Lib"); ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( DefaultInspectionContext.Instance, "parameter", DkmEvaluationFlags.TreatAsExpression, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } [Fact] public void ERR_QueryNoProviderStandard() { var source = @" public class C { public void M(int[] array) { } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef }, TestOptions.DebugDll); var context = CreateMethodContextWithReferences(comp, "C.M", MscorlibRef); var expectedError = "(1,11): error CS1935: Could not find an implementation of the query pattern for source type 'int[]'. 'Select' not found. Are you missing a reference to 'System.Core.dll' or a using directive for 'System.Linq'?"; var expectedMissingAssemblyIdentity = EvaluationContextBase.SystemCoreIdentity; ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( DefaultInspectionContext.Instance, "from i in array select i", DkmEvaluationFlags.TreatAsExpression, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } [Fact] public void ForwardingErrors() { var il = @" .assembly extern mscorlib { } .assembly extern pe2 { } .assembly pe1 { } .class extern forwarder Forwarded { .assembly extern pe2 } .class extern forwarder NS.Forwarded { .assembly extern pe2 } .class public auto ansi beforefieldinit Dummy extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; var csharp = @" class C { static void M(Dummy d) { } } "; var ilRef = CompileIL(il, appendDefaultHeader: false); var comp = CreateCompilationWithMscorlib(csharp, new[] { ilRef }); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var expectedMissingAssemblyIdentity = new AssemblyIdentity("pe2"); ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( DefaultInspectionContext.Instance, "new global::Forwarded()", DkmEvaluationFlags.TreatAsExpression, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal( "error CS1068: The type name 'Forwarded' could not be found in the global namespace. This type has been forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' Consider adding a reference to that assembly.", actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); context.CompileExpression( DefaultInspectionContext.Instance, "new Forwarded()", DkmEvaluationFlags.TreatAsExpression, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal( "error CS1070: The type name 'Forwarded' could not be found. This type has been forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Consider adding a reference to that assembly.", actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); context.CompileExpression( DefaultInspectionContext.Instance, "new NS.Forwarded()", DkmEvaluationFlags.TreatAsExpression, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal( "error CS1069: The type name 'Forwarded' could not be found in the namespace 'NS'. This type has been forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' Consider adding a reference to that assembly.", actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } [Fact] public unsafe void ShouldTryAgain_Success() { var comp = CreateCompilationWithMscorlib("public class C { }"); using (var pinned = new PinnedMetadata(GetMetadataBytes(comp))) { DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { uSize = (uint)pinned.Size; return pinned.Pointer; }; var references = ImmutableArray<MetadataBlock>.Empty; var missingAssemblyIdentity = new AssemblyIdentity("A"); var missingAssemblyIdentities = ImmutableArray.Create(missingAssemblyIdentity); Assert.True(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); var newReference = references.Single(); Assert.Equal(pinned.Pointer, newReference.Pointer); Assert.Equal(pinned.Size, newReference.Size); } } [Fact] public unsafe void ShouldTryAgain_Mixed() { var comp1 = CreateCompilationWithMscorlib("public class C { }", assemblyName: GetUniqueName()); var comp2 = CreateCompilationWithMscorlib("public class D { }", assemblyName: GetUniqueName()); using (PinnedMetadata pinned1 = new PinnedMetadata(GetMetadataBytes(comp1)), pinned2 = new PinnedMetadata(GetMetadataBytes(comp2))) { var assemblyIdentity1 = comp1.Assembly.Identity; var assemblyIdentity2 = comp2.Assembly.Identity; Assert.NotEqual(assemblyIdentity1, assemblyIdentity2); DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { if (assemblyIdentity == assemblyIdentity1) { uSize = (uint)pinned1.Size; return pinned1.Pointer; } else if (assemblyIdentity == assemblyIdentity2) { uSize = (uint)pinned2.Size; return pinned2.Pointer; } else { Marshal.ThrowExceptionForHR(unchecked((int)MetadataUtilities.CORDBG_E_MISSING_METADATA)); throw ExceptionUtilities.Unreachable; } }; var references = ImmutableArray.Create(default(MetadataBlock)); var unknownAssemblyIdentity = new AssemblyIdentity(GetUniqueName()); var missingAssemblyIdentities = ImmutableArray.Create(assemblyIdentity1, unknownAssemblyIdentity, assemblyIdentity2); Assert.True(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); Assert.Equal(3, references.Length); Assert.Equal(default(MetadataBlock), references[0]); Assert.Equal(pinned1.Pointer, references[1].Pointer); Assert.Equal(pinned1.Size, references[1].Size); Assert.Equal(pinned2.Pointer, references[2].Pointer); Assert.Equal(pinned2.Size, references[2].Size); } } [Fact] public void ShouldTryAgain_CORDBG_E_MISSING_METADATA() { DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { Marshal.ThrowExceptionForHR(unchecked((int)MetadataUtilities.CORDBG_E_MISSING_METADATA)); throw ExceptionUtilities.Unreachable; }; var references = ImmutableArray<MetadataBlock>.Empty; var missingAssemblyIdentities = ImmutableArray.Create(new AssemblyIdentity("A")); Assert.False(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); Assert.Empty(references); } [Fact] public void ShouldTryAgain_COR_E_BADIMAGEFORMAT() { DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { Marshal.ThrowExceptionForHR(unchecked((int)MetadataUtilities.COR_E_BADIMAGEFORMAT)); throw ExceptionUtilities.Unreachable; }; var references = ImmutableArray<MetadataBlock>.Empty; var missingAssemblyIdentities = ImmutableArray.Create(new AssemblyIdentity("A")); Assert.False(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); Assert.Empty(references); } [Fact] public void ShouldTryAgain_OtherException() { DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { throw new Exception(); }; var references = ImmutableArray<MetadataBlock>.Empty; var missingAssemblyIdentities = ImmutableArray.Create(new AssemblyIdentity("A")); Assert.Throws<Exception>(() => ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); } [WorkItem(1124725, "DevDiv")] [Fact] public void PseudoVariableType() { var source = @"class C { static void M() { } } "; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); var context = CreateMethodContextWithReferences(comp, "C.M", CSharpRef, ExpressionCompilerTestHelpers.IntrinsicAssemblyReference); const string expectedError = "error CS0012: The type 'Exception' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'."; var expectedMissingAssemblyIdentity = comp.Assembly.CorLibrary.Identity; ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; var result = context.CompileExpression( InspectionContextFactory.Empty.Add("$stowedexception", "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException, Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), "$stowedexception", DkmEvaluationFlags.TreatAsExpression, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } [WorkItem(1114866)] [ConditionalFact(typeof(OSVersionWin8))] public void NotYetLoadedWinMds() { var source = @"class C { static void M(Windows.Storage.StorageFolder f) { } }"; var comp = CreateCompilationWithMscorlib(source, WinRtRefs, TestOptions.DebugDll); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage"); Assert.True(runtimeAssemblies.Any()); var context = CreateMethodContextWithReferences(comp, "C.M", ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies)); const string expectedError = "error CS0234: The type or namespace name 'UI' does not exist in the namespace 'Windows' (are you missing an assembly reference?)"; var expectedMissingAssemblyIdentity = new AssemblyIdentity("Windows.UI", contentType: System.Reflection.AssemblyContentType.WindowsRuntime); ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( InspectionContextFactory.Empty, "typeof(@Windows.UI.Colors)", DkmEvaluationFlags.None, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } /// <remarks> /// Windows.UI.Xaml is the only (win8) winmd with more than two parts. /// </remarks> [WorkItem(1114866)] [ConditionalFact(typeof(OSVersionWin8))] public void NotYetLoadedWinMds_MultipleParts() { var source = @"class C { static void M(Windows.UI.Colors c) { } }"; var comp = CreateCompilationWithMscorlib(source, WinRtRefs, TestOptions.DebugDll); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.UI"); Assert.True(runtimeAssemblies.Any()); var context = CreateMethodContextWithReferences(comp, "C.M", ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies)); const string expectedError = "error CS0234: The type or namespace name 'Xaml' does not exist in the namespace 'Windows.UI' (are you missing an assembly reference?)"; var expectedMissingAssemblyIdentity = new AssemblyIdentity("Windows.UI.Xaml", contentType: System.Reflection.AssemblyContentType.WindowsRuntime); ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( InspectionContextFactory.Empty, "typeof([email protected])", DkmEvaluationFlags.None, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } private EvaluationContext CreateMethodContextWithReferences(Compilation comp, string methodName, params MetadataReference[] references) { return CreateMethodContextWithReferences(comp, methodName, ImmutableArray.CreateRange(references)); } private EvaluationContext CreateMethodContextWithReferences(Compilation comp, string methodName, ImmutableArray<MetadataReference> references) { byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> unusedReferences; var result = comp.EmitAndGetReferences(out exeBytes, out pdbBytes, out unusedReferences); Assert.True(result); var runtime = CreateRuntimeInstance(GetUniqueName(), references, exeBytes, new SymReader(pdbBytes)); return CreateMethodContext(runtime, methodName); } private static AssemblyIdentity GetMissingAssemblyIdentity(ErrorCode code, params object[] arguments) { var missingAssemblyIdentities = EvaluationContext.GetMissingAssemblyIdentitiesHelper(code, arguments); return missingAssemblyIdentities.IsDefault ? null : missingAssemblyIdentities.Single(); } private static ImmutableArray<byte> GetMetadataBytes(Compilation comp) { var imageReference = (MetadataImageReference)comp.EmitToImageReference(); var assemblyMetadata = (AssemblyMetadata)imageReference.GetMetadata(); var moduleMetadata = assemblyMetadata.GetModules()[0]; return moduleMetadata.Module.PEReaderOpt.GetMetadata().GetContent(); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Diagnostics; using System.Threading; using NUnit.Framework; using osu.Framework.Audio; using osu.Framework.Audio.Track; using osu.Framework.Bindables; using osu.Framework.Development; using osu.Framework.Threading; namespace osu.Framework.Tests.Audio { [TestFixture] public class TrackVirtualTest { private TrackVirtual track; [SetUp] public void Setup() { track = new TrackVirtual(60000); updateTrack(); } [Test] public void TestStart() { track.Start(); updateTrack(); Thread.Sleep(50); updateTrack(); Assert.IsTrue(track.IsRunning); Assert.Greater(track.CurrentTime, 0); } [Test] public void TestStartZeroLength() { // override default with custom length track = new TrackVirtual(0); track.Start(); updateTrack(); Thread.Sleep(50); Assert.IsTrue(!track.IsRunning); Assert.AreEqual(0, track.CurrentTime); } [Test] public void TestStop() { track.Start(); track.Stop(); updateTrack(); Assert.IsFalse(track.IsRunning); double expectedTime = track.CurrentTime; Thread.Sleep(50); Assert.AreEqual(expectedTime, track.CurrentTime); } [Test] public void TestStopAtEnd() { startPlaybackAt(track.Length - 1); Thread.Sleep(50); updateTrack(); track.Stop(); updateTrack(); Assert.IsFalse(track.IsRunning); Assert.AreEqual(track.Length, track.CurrentTime); } [Test] public void TestSeek() { track.Seek(1000); updateTrack(); Assert.IsFalse(track.IsRunning); Assert.AreEqual(1000, track.CurrentTime); } [Test] public void TestSeekWhileRunning() { track.Start(); track.Seek(1000); updateTrack(); Assert.IsTrue(track.IsRunning); Assert.GreaterOrEqual(track.CurrentTime, 1000); } [Test] public void TestSeekBackToSamePosition() { track.Seek(1000); track.Seek(0); updateTrack(); Thread.Sleep(50); updateTrack(); Assert.GreaterOrEqual(track.CurrentTime, 0); Assert.Less(track.CurrentTime, 1000); } [Test] public void TestPlaybackToEnd() { startPlaybackAt(track.Length - 1); Thread.Sleep(50); updateTrack(); Assert.IsFalse(track.IsRunning); Assert.AreEqual(track.Length, track.CurrentTime); } /// <summary> /// Bass restarts the track from the beginning if Start is called when the track has been completed. /// This is blocked locally in <see cref="TrackVirtual"/>, so this test expects the track to not restart. /// </summary> [Test] public void TestStartFromEndDoesNotRestart() { startPlaybackAt(track.Length - 1); Thread.Sleep(50); updateTrack(); track.Start(); updateTrack(); Assert.AreEqual(track.Length, track.CurrentTime); } [Test] public void TestRestart() { startPlaybackAt(1000); Thread.Sleep(50); updateTrack(); restartTrack(); Assert.IsTrue(track.IsRunning); Assert.Less(track.CurrentTime, 1000); } [Test] public void TestRestartAtEnd() { startPlaybackAt(track.Length - 1); Thread.Sleep(50); updateTrack(); restartTrack(); Assert.IsTrue(track.IsRunning); Assert.LessOrEqual(track.CurrentTime, 1000); } [Test] public void TestRestartFromRestartPoint() { track.RestartPoint = 1000; startPlaybackAt(3000); restartTrack(); Assert.IsTrue(track.IsRunning); Assert.GreaterOrEqual(track.CurrentTime, 1000); Assert.Less(track.CurrentTime, 3000); } [Test] public void TestLoopingRestart() { track.Looping = true; startPlaybackAt(track.Length - 1); Thread.Sleep(50); // The first update brings the track to its end time and restarts it updateTrack(); // The second update updates the IsRunning state updateTrack(); // In a perfect world the track will be running after the update above, but during testing it's possible that the track is in // a stalled state due to updates running on Bass' own thread, so we'll loop until the track starts running again // Todo: This should be fixed in the future if/when we invoke Bass.Update() ourselves int loopCount = 0; while (++loopCount < 50 && !track.IsRunning) { updateTrack(); Thread.Sleep(10); } if (loopCount == 50) throw new TimeoutException("Track failed to start in time."); Assert.LessOrEqual(track.CurrentTime, 1000); } [Test] public void TestSetTempoNegative() { Assert.IsFalse(track.IsReversed); track.Tempo.Value = 0.05f; Assert.IsFalse(track.IsReversed); Assert.AreEqual(0.05f, track.Tempo.Value); } [Test] public void TestRateWithAggregateTempoAdjustments() { track.AddAdjustment(AdjustableProperty.Tempo, new BindableDouble(1.5f)); Assert.AreEqual(1.5, track.Rate); testPlaybackRate(1.5); } [Test] public void TestRateWithAggregateFrequencyAdjustments() { track.AddAdjustment(AdjustableProperty.Frequency, new BindableDouble(1.5f)); Assert.AreEqual(1.5, track.Rate); testPlaybackRate(1.5); } [Test] public void TestCurrentTimeUpdatedAfterInlineSeek() { track.Start(); updateTrack(); RunOnAudioThread(() => track.Seek(20000)); Assert.That(track.CurrentTime, Is.EqualTo(20000).Within(100)); } private void testPlaybackRate(double expectedRate) { const double play_time = 1000; const double fudge = play_time * 0.1; track.Start(); var sw = new Stopwatch(); sw.Start(); while (sw.ElapsedMilliseconds < play_time) { Thread.Sleep(50); track.Update(); } sw.Stop(); Assert.GreaterOrEqual(track.CurrentTime, sw.ElapsedMilliseconds * expectedRate - fudge); Assert.LessOrEqual(track.CurrentTime, sw.ElapsedMilliseconds * expectedRate + fudge); } private void startPlaybackAt(double time) { track.Seek(time); track.Start(); updateTrack(); } private void updateTrack() => RunOnAudioThread(() => track.Update()); private void restartTrack() { RunOnAudioThread(() => { track.Restart(); track.Update(); }); } /// <summary> /// Certain actions are invoked on the audio thread. /// Here we simulate this process on a correctly named thread to avoid endless blocking. /// </summary> /// <param name="action">The action to perform.</param> public static void RunOnAudioThread(Action action) { var resetEvent = new ManualResetEvent(false); new Thread(() => { ThreadSafety.IsAudioThread = true; action(); resetEvent.Set(); }) { Name = GameThread.PrefixedThreadNameFor("Audio") }.Start(); if (!resetEvent.WaitOne(TimeSpan.FromSeconds(10))) throw new TimeoutException(); } } }
// ------------------------------------- // Domain : Avariceonline.com // Author : Nicholas Ventimiglia // Product : Unity3d Foundation // Published : 2015 // ------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Foundation.Server { /// <summary> /// Tool for constructing OData queries /// </summary> public class ODataQuery<T> where T : class { // ReSharper disable InconsistentNaming protected int skip; protected int take; protected string orderBy; protected List<string> filters = new List<string>(); protected void AddFilter(string format, params object[] values) { filters.Add(string.Format(format, values)); } ///<summary> /// Where the property contains /// </summary> /// <param name="key">property name</param> /// <param name="value">String, Number</param> /// <returns></returns> public ODataQuery<T> WhereContains(string key, object value) { AddFilter("substringof({1}, {0})", key, ReadValue(value)); return this; } ///<summary> /// Where the property string value starts with /// </summary> /// <param name="key">property name</param> /// <param name="value">String, Number</param> /// <returns></returns> public ODataQuery<T> WhereStartsWith(string key, object value) { AddFilter("{0} sw {1}", key, ReadValue(value)); return this; } ///<summary> /// Where the property string value ends with /// </summary> /// <param name="key">property name</param> /// <param name="value">String, Number</param> /// <returns></returns> public ODataQuery<T> WhereEndsWiths(string key, object value) { AddFilter("{0} ew {1}", key, ReadValue(value)); return this; } ///<summary> /// Where the property value equals /// </summary> /// <param name="key">property name</param> /// <param name="value">String, Number</param> /// <returns></returns> public ODataQuery<T> WhereEquals(string key, object value) { AddFilter("{0} eq {1}", key, ReadValue(value)); return this; } ///<summary> /// Where the property value does not equal /// </summary> /// <param name="key">property name</param> /// <param name="value">String, Number</param> /// <returns></returns> public ODataQuery<T> WhereNotEquals(string key, object value) { AddFilter("{0} ne {1}", key, ReadValue(value)); return this; } ///<summary> /// Where the (numeric) property value is greater than /// </summary> /// <param name="key">property name</param> /// <param name="value">Number, DateTime</param> /// <returns></returns> public ODataQuery<T> WhereGreaterThan(string key, object value) { AddFilter("{0} gt {1}", key, ReadValue(value)); return this; } ///<summary> /// Where the (numeric) property value is less than /// </summary> /// <param name="key">property name</param> /// <param name="value">Number, DateTime</param> /// <returns></returns> public ODataQuery<T> WhereLessThan(string key, object value) { AddFilter("{0} lt {1}", key, ReadValue(value)); return this; } ///<summary> /// Where the (numeric) property value is greater than or equal to /// </summary> /// <param name="key">property name</param> /// <param name="value">Number, DateTime</param> /// <returns></returns> public ODataQuery<T> WhereGreaterThanOrEqualTo(string key, object value) { AddFilter("{0} ge {1}", key, ReadValue(value)); return this; } ///<summary> /// Where the (numeric) property value is less than or equal to /// </summary> /// <param name="key">property name</param> /// <param name="value">Number, DateTime</param> /// <returns></returns> public ODataQuery<T> WhereLessThanOrEqualTo(string key, object value) { AddFilter("{0} le {1}", key, ReadValue(value)); return this; } ///<summary> /// Sorts with the highest value first /// </summary> /// <summary> /// Orders the selection by the property /// </summary> /// <param name="key">property name</param> /// <returns></returns> public ODataQuery<T> OrderByDescending(string key) { orderBy = string.Format("orderby={0} desc", key); return this; } /// <summary> /// Sorts with the lowest value first /// </summary> /// <param name="key">property name</param> /// <returns></returns> public ODataQuery<T> OrderBy(string key) { orderBy = string.Format("orderby={0}", key); return this; } /// <summary> /// Skip, For paging. /// </summary> /// <param name="count"></param> /// <returns></returns> public ODataQuery<T> Skip(int count) { skip = count; return this; } /// <summary> /// Truncate, For paging. /// </summary> /// <param name="count"></param> /// <returns></returns> public ODataQuery<T> Take(int count) { take = count; return this; } #region internal public int GetTake() { return skip; } public int GetSkip() { return skip; } protected string ReadValue(object value) { if (value is DateTime) { // return new DateTimeOffset(((DateTime)value).ToUniversalTime()).ToString(); return (new DateTimeOffset((DateTime)value)).ToString("yyyy-MM-ddTHH:mm"); } if (value is string) { return string.Format("'{0}'", value); } if (value is bool) { return ((bool)value) ? "true" : "false"; } if (value == null) { return "''"; } return value.ToString(); } public override string ToString() { var first = true; var sb = new StringBuilder(); if (filters.Any()) { ClausePrefix(sb, true); first = false; sb.AppendFormat("filter="); for (int i = 0;i < filters.Count;i++) { if (i > 0) sb.AppendFormat(" and "); sb.Append(filters[i]); } } if (!string.IsNullOrEmpty(orderBy)) { ClausePrefix(sb, first); first = false; sb.Append(orderBy); } if (skip > 0) { ClausePrefix(sb, first); first = false; sb.AppendFormat("skip={0}", skip); } if (take > 0) { ClausePrefix(sb, first); sb.AppendFormat("top={0}", take); } // Unity will throw a 400 BadRequest if there are spaces in the query string. // Convert them to %20 (ascii equivalent) to get around this. return sb.ToString().Replace(" ", "%20"); } void ClausePrefix(StringBuilder sb, bool first) { sb.Append(first ? "?$" : "&$"); } #endregion } }
using System; using ChatSharp; using System.Linq; using System.Collections.Generic; using ChatSharp.Events; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.IO; using Mono.CSharp; namespace Sirvant { public class BotController { public IrcClient PrimaryClient { get; set; } public List<IrcClient> SecondaryClients { get; set; } public Dictionary<string, IrcUser> NickMaps { get; set; } public Dictionary<string, StreamWriter> Logs { get; set; } public bool Active { get; set; } public Timer Timer { get; set; } public Evaluator Evaluator { get; set; } public BotController() { Active = true; Evaluator = new Evaluator(new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter())); Evaluator.ReferenceAssembly(typeof(BotController).Assembly); Evaluator.ReferenceAssembly(typeof(IrcClient).Assembly); SecondaryClients = new List<IrcClient>(); NickMaps = new Dictionary<string, IrcUser>(); PrimaryClient = new IrcClient(Program.Configuration.IrcServer, new IrcUser( Program.Configuration.Identity.Nick, Program.Configuration.Identity.User, Program.Configuration.Identity.Password)); Evaluator.Evaluate("var client = Program.Controller.PrimaryClient"); Logs = new Dictionary<string, StreamWriter>(); SetUpPrimaryEventHandlers(); } public void Run() { PrimaryClient.ConnectAsync(); } private void SetUpPrimaryEventHandlers() { PrimaryClient.ConnectionComplete += HandleConnectionComplete; PrimaryClient.UserJoinedChannel += HandleUserJoinedChannel; PrimaryClient.ModeChanged += HandleModeChanged; PrimaryClient.ChannelMessageRecieved += HandleChannelMessageRecieved; PrimaryClient.PrivateMessageRecieved += HandlePrivateMessageRecieved; PrimaryClient.ChannelListRecieved += HandleChannelListRecieved; PrimaryClient.UserPartedChannel += HandleUserPartedChannel; PrimaryClient.UserKicked += HandleUserKicked; Logs[PrimaryClient.User.Nick] = new StreamWriter(PrimaryClient.User.Nick + ".log"); PrimaryClient.RawMessageRecieved += (sender, e) => { Logs[(sender as IrcClient).User.Nick].WriteLine("<- " + e.Message); Logs[(sender as IrcClient).User.Nick].Flush(); }; PrimaryClient.RawMessageSent += (sender, e) => { Logs[(sender as IrcClient).User.Nick].WriteLine("-> " + e.Message); Logs[(sender as IrcClient).User.Nick].Flush(); }; } void HandleChannelListRecieved(object sender, ChannelEventArgs e) { Task.Factory.StartNew(() => { Thread.Sleep(3000); var autoReset = new AutoResetEvent(false); for (int i = 0; i < e.Channel.Users.Count(); i++) { var user = e.Channel.Users[i]; if (user.Hostname != null) continue; if (NickMaps.ContainsKey(user.Nick)) continue; autoReset.Reset(); PrimaryClient.WhoIs(user.Nick, whois => { if (whois != null && whois.User != null && whois.User.Nick != null) NickMaps[whois.User.Nick] = whois.User; autoReset.Set(); }); autoReset.WaitOne(); Thread.Sleep(1000); } Console.WriteLine("WHOIS complete"); }); } void HandlePrivateMessageRecieved(object sender, PrivateMessageEventArgs e) { if (Program.Configuration.TrustedMasks.Any(m => e.PrivateMessage.User.Match(m))) HandleTrustedCommand(e.PrivateMessage.Message, e.PrivateMessage, sender as IrcClient); } void HandleChannelMessageRecieved(object sender, PrivateMessageEventArgs e) { var client = sender as IrcClient; if (Program.Configuration.TrustedMasks.Any(m => e.PrivateMessage.User.Match(m))) { var message = e.PrivateMessage.Message; bool command = false; if (e.PrivateMessage.Message.StartsWith(client.User.Nick + ": ")) { message = message.Substring(client.User.Nick.Length + 2); command = true; } if (e.PrivateMessage.Message.StartsWith(".") && client == PrimaryClient) { message = message.Substring(1); command = true; } if (command) HandleTrustedCommand(message, e.PrivateMessage, client); } } void HandleTrustedCommand(string message, PrivateMessage originalMessage, IrcClient target) { var command = message; var parameters = new string[0]; if (message.Contains(" ")) { command = message.Remove(message.IndexOf(' ')); parameters = message.Substring(message.IndexOf(' ') + 1).Split(' '); } switch (command) { case "addchannel": bool multiclient = false; if (parameters.Length < 1 || parameters.Length > 2) break; if (parameters.Length == 2) { if (!bool.TryParse(parameters[1], out multiclient)) break; } Program.Configuration.Channels = Program.Configuration.Channels.Concat(new[] { new ChannelDescriptor { Name = parameters[0], EnableMultiClient = multiclient } }).ToArray(); Program.SaveConfiguration(); PrimaryClient.JoinChannel(parameters[0]); if (multiclient) { foreach (var client in SecondaryClients) client.JoinChannel(parameters[0]); } break; case "removechannel": if (originalMessage.IsChannelMessage) { PrimaryClient.PartChannel(originalMessage.Source); foreach (var client in SecondaryClients) client.PartChannel(originalMessage.Source); Program.Configuration.Channels = Program.Configuration.Channels.Where(c => c.Name != originalMessage.Source).ToArray(); Program.SaveConfiguration(); } break; case "addclients": int addAmount; if (parameters.Length != 1) break; if (!int.TryParse(parameters[0], out addAmount)) break; // Add that many clients var oldAmount = Program.Configuration.AlternateClients; Program.Configuration.AlternateClients += addAmount; Program.SaveConfiguration(); int newAmount = SecondaryClients.Count + addAmount; for (int i = oldAmount + 1; i <= newAmount; i++) { var newClient = new IrcClient(Program.Configuration.IrcServer,new IrcUser( Program.Configuration.Identity.Nick + i, Program.Configuration.Identity.User, Program.Configuration.Identity.Password)); SetUpSecondaryEventHandlers(newClient); SecondaryClients.Add(newClient); newClient.ConnectAsync(); } break; case "removeclients": int removeAmount; if (parameters.Length != 1) break; if (!int.TryParse(parameters[0], out removeAmount)) break; if (SecondaryClients.Count < removeAmount) break; // Remove a few clients Program.Configuration.AlternateClients -= removeAmount; Program.SaveConfiguration(); for (int i = 0; i < removeAmount; i++) { SecondaryClients.Last().Quit("Requested by " + originalMessage.User.Nick); SecondaryClients.RemoveAt(SecondaryClients.Count - 1); } break; case "killall": PrimaryClient.Quit("Requested by " + originalMessage.User.Nick); foreach (var client in SecondaryClients) client.Quit("Requested by " + originalMessage.User.Nick); Process.GetCurrentProcess().Kill(); while (true); case "listclients": var clients = string.Join(", ", new[] { PrimaryClient.User.Nick }.Concat( SecondaryClients.Select(c => c.User.Nick)).ToArray()); PrimaryClient.SendMessage(clients, originalMessage.Source); break; case "quit": target.Quit("Requested by " + originalMessage.User.Nick); SecondaryClients.Remove(target); break; case "join": if (parameters.Length != 1) break; target.JoinChannel(parameters[0]); break; case "suspend": Program.Configuration.RespondAggressively = false; Program.SaveConfiguration(); PrimaryClient.SendMessage("Bot operation suspended.", originalMessage.Source); break; case "resume": Program.Configuration.RespondAggressively = true; Program.SaveConfiguration(); PrimaryClient.SendMessage("Bot operation resumed.", originalMessage.Source); break; case "raw": PrimaryClient.SendRawMessage(message.Substring(4)); break; case "rawall": var raw = message.Substring(7); PrimaryClient.SendRawMessage(raw); foreach (var client in SecondaryClients) client.SendRawMessage(raw); break; case "timer": int period = int.Parse(parameters[0]); var timedCommand = string.Join(" ", parameters.Skip(1).ToArray()); PrimaryClient.SendMessage(string.Format("Repeating '{0}' every {1}ms", timedCommand, period), originalMessage.Source); Timer = new Timer(o => { HandleTrustedCommand(timedCommand, originalMessage, target); }, null, period, period); break; case "stop": Timer.Change(Timeout.Infinite, Timeout.Infinite); PrimaryClient.SendMessage("Timer stopped.", originalMessage.Source); break; case "execute": var code = message.Substring(8); object result; bool resultSet; Console.WriteLine(Evaluator.Evaluate(code, out result, out resultSet)); if (resultSet) PrimaryClient.SendMessage(result.ToString(), originalMessage.Source); break; } } void HandleUserJoinedChannel(object sender, ChannelUserEventArgs e) { if (SecondaryClients.Any(c => c.User.Nick == e.User.Nick) || Program.Configuration.TrustedMasks.Any(m => e.User.Match(m))) e.Channel.ChangeMode("+o " + e.User.Nick); NickMaps[e.User.Nick] = e.User; } void HandleUserPartedChannel(object sender, ChannelUserEventArgs e) { if (NickMaps.ContainsKey(e.User.Nick)) NickMaps.Remove(e.User.Nick); } void HandleUserKicked(object sender, KickEventArgs e) { if (!NickMaps.ContainsKey(e.Kicked.Nick) || !NickMaps.ContainsKey(e.Kicker.Nick)) return; var kicked = NickMaps[e.Kicked.Nick]; var kicker = NickMaps[e.Kicker.Nick]; if (Program.Configuration.TrustedMasks.Any(m => kicked.Match(m))) { RespondTo(kicker, e.Channel); e.Channel.Invite(kicked.Nick); } var client = SecondaryClients.FirstOrDefault(c => c.User.Nick == kicked.Nick); if (client != null) { client.JoinChannel(e.Channel.Name); RespondTo(kicker, e.Channel); } if (kicked.Nick == PrimaryClient.User.Nick) { PrimaryClient.JoinChannel(e.Channel.Name); RespondTo(kicker, e.Channel); } } private void SetUpSecondaryEventHandlers(IrcClient client) { // Secondary clients only provide support to the primary client client.ConnectionComplete += HandleConnectionComplete; client.ModeChanged += HandleModeChanged; client.ChannelMessageRecieved += HandleChannelMessageRecieved; Logs[client.User.Nick] = new StreamWriter(client.User.Nick + ".log"); client.RawMessageRecieved += (sender, e) => { Logs[(sender as IrcClient).User.Nick].WriteLine("<- " + e.Message); Logs[(sender as IrcClient).User.Nick].Flush(); }; client.RawMessageSent += (sender, e) => { Logs[(sender as IrcClient).User.Nick].WriteLine("-> " + e.Message); Logs[(sender as IrcClient).User.Nick].Flush(); }; } private void HandleModeChanged(object sender, ModeChangeEventArgs e) { var client = sender as IrcClient; if (e.Change.StartsWith("-o ")) { var target = e.Change.Substring(3); var channel = client.Channels[e.Target]; if (client.User.Nick == target || !channel.UsersByMode['o'].Contains(client.User.Nick)) return; // Let another bot deal with it if (PrimaryClient.User.Nick == target) { var designatedClient = SecondaryClients.FirstOrDefault(c => channel.UsersByMode['o'].Contains(c.User.Nick)); if (designatedClient == client) { channel.ChangeMode("+o " + PrimaryClient.User.Nick); RespondTo(e.User, channel); } } var affectedSecondaryClient = SecondaryClients.FirstOrDefault(c => c.User.Nick == target); if (affectedSecondaryClient != null) { channel.ChangeMode("+o " + affectedSecondaryClient.User.Nick); RespondTo(e.User, channel); } if (NickMaps.ContainsKey(target)) { if (Program.Configuration.TrustedMasks.Any(m => NickMaps[target].Match(m))) { var designatedClient = SecondaryClients.FirstOrDefault(c => channel.UsersByMode['o'].Contains(c.User.Nick)); if (channel.UsersByMode['o'].Contains(PrimaryClient.User.Nick)) designatedClient = PrimaryClient; if (client == designatedClient) { channel.ChangeMode("+o " + target); RespondTo(e.User, channel); } } } } else if (e.Change.StartsWith("+b ") || e.Change.StartsWith("-I ") || e.Change.StartsWith("-e ")) { string reverse = "-b "; if (e.Change.StartsWith("-I ") || e.Change.StartsWith("-e ")) reverse = "+" + e.Change[1].ToString() + " "; var mask = e.Change.Substring(3); var channel = client.Channels[e.Target]; var designatedClient = SecondaryClients.FirstOrDefault(c => channel.UsersByMode['o'].Contains(c.User.Nick)); if (channel.UsersByMode['o'].Contains(PrimaryClient.User.Nick)) designatedClient = PrimaryClient; if (mask.StartsWith("$a:")) { mask = mask.Substring(3); if (designatedClient == client) { var trusted = NickMaps.Where(nm => Program.Configuration.TrustedMasks.Any(t => nm.Value.Match(t))).ToArray(); if (IrcUser.Match(mask, PrimaryClient.User.User) || trusted.Any(t => IrcUser.Match(mask, t.Value.Nick))) { client.ChangeMode(channel.Name, reverse + "$a:" + mask); RespondTo(e.User, channel); return; } } return; } if (mask.StartsWith("$x:") || mask.StartsWith("$r")) { if (designatedClient == client) client.ChangeMode(channel.Name, reverse + mask); return; } var affectedUsers = NickMaps.Where(nm => nm.Value.Match(mask)); if (designatedClient == client) { if (affectedUsers.Any()) { foreach (var affectedUser in affectedUsers) { if (Program.Configuration.TrustedMasks.Any(m => affectedUser.Value.Match(m)) || PrimaryClient.User.Match(mask) || SecondaryClients.Any(c => c.User.Match(mask))) { channel.ChangeMode(reverse + mask); RespondTo(e.User, channel); break; } } } } } else if (e.Change.StartsWith("+l ")) { client.ChangeMode(e.Target, "-l"); } } void RespondTo(IrcUser user, IrcChannel channel) { if (Program.Configuration.RespondAggressively) { if (Program.Configuration.TrustedMasks.Any(m => user.Match(m))) return; if (PrimaryClient.User.Nick == user.Nick) return; if (SecondaryClients.Any(c => c.User.Nick == user.Nick)) return; try { PrimaryClient.GetModeList(channel.Name, 'e', mc => { channel.Kick(user.Nick, Program.Configuration.KickMessage); channel.ChangeMode("+b *!*@" + user.Hostname); while (mc.ContainsMatch(user)) { var match = mc.GetMatch(user); channel.ChangeMode("-e " + match.Value); mc.Remove(match); } }); } catch { } } } private void HandleConnectionComplete(object sender, EventArgs e) { var client = sender as IrcClient; Console.WriteLine("{0} successfully connected", client.User.Nick); var channels = Program.Configuration.Channels; if (client != PrimaryClient) channels = channels.Where(c => c.EnableMultiClient).ToArray(); foreach (var channel in channels) client.JoinChannel(channel.Name); if (client == PrimaryClient) { // Clear to connect alternate clients for (int i = 1; i <= Program.Configuration.AlternateClients; i++) { var newClient = new IrcClient(Program.Configuration.IrcServer,new IrcUser( Program.Configuration.Identity.Nick + i, Program.Configuration.Identity.User, Program.Configuration.Identity.Password)); SetUpSecondaryEventHandlers(newClient); SecondaryClients.Add(newClient); newClient.ConnectAsync(); } } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using System.Collections.Generic; using Tools; namespace OpenSim.Region.ScriptEngine.Shared.CodeTools { public class CSCodeGenerator : ICodeConverter { private SYMBOL m_astRoot = null; private Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> m_positionMap; private int m_indentWidth = 4; // for indentation private int m_braceCount; // for indentation private int m_CSharpLine; // the current line of generated C# code private int m_CSharpCol; // the current column of generated C# code private List<string> m_warnings = new List<string>(); /// <summary> /// Creates an 'empty' CSCodeGenerator instance. /// </summary> public CSCodeGenerator() { ResetCounters(); } /// <summary> /// Get the mapping between LSL and C# line/column number. /// </summary> /// <returns>Dictionary\<KeyValuePair\<int, int\>, KeyValuePair\<int, int\>\>.</returns> public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> PositionMap { get { return m_positionMap; } } /// <summary> /// Get the mapping between LSL and C# line/column number. /// </summary> /// <returns>SYMBOL pointing to root of the abstract syntax tree.</returns> public SYMBOL ASTRoot { get { return m_astRoot; } } /// <summary> /// Resets various counters and metadata. /// </summary> private void ResetCounters() { m_braceCount = 0; m_CSharpLine = 0; m_CSharpCol = 1; m_positionMap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>(); m_astRoot = null; } /// <summary> /// Generate the code from the AST we have. /// </summary> /// <param name="script">The LSL source as a string.</param> /// <returns>String containing the generated C# code.</returns> public string Convert(string script) { m_warnings.Clear(); ResetCounters(); Parser p = new LSLSyntax(new yyLSLSyntax(), new ErrorHandler(true)); LSL2CSCodeTransformer codeTransformer; try { codeTransformer = new LSL2CSCodeTransformer(p.Parse(script)); } catch (CSToolsException e) { string message; // LL start numbering lines at 0 - geeks! // Also need to subtract one line we prepend! // string emessage = e.Message; string slinfo = e.slInfo.ToString(); // Remove wrong line number info // if (emessage.StartsWith(slinfo+": ")) emessage = emessage.Substring(slinfo.Length+2); message = String.Format("Line ({0},{1}) {2}", e.slInfo.lineNumber - 2, e.slInfo.charPosition - 1, emessage); throw new Exception(message); } m_astRoot = codeTransformer.Transform(); string retstr = String.Empty; // standard preamble //retstr = GenerateLine("using OpenSim.Region.ScriptEngine.Common;"); //retstr += GenerateLine("using System.Collections.Generic;"); //retstr += GenerateLine(""); //retstr += GenerateLine("namespace SecondLife"); //retstr += GenerateLine("{"); m_braceCount++; //retstr += GenerateIndentedLine("public class Script : OpenSim.Region.ScriptEngine.Common"); //retstr += GenerateIndentedLine("{"); m_braceCount++; // line number m_CSharpLine += 3; // here's the payload retstr += GenerateLine(); foreach (SYMBOL s in m_astRoot.kids) retstr += GenerateNode(s); // close braces! m_braceCount--; //retstr += GenerateIndentedLine("}"); m_braceCount--; //retstr += GenerateLine("}"); // Removes all carriage return characters which may be generated in Windows platform. Is there // cleaner way of doing this? retstr=retstr.Replace("\r", ""); return retstr; } /// <summary> /// Get the set of warnings generated during compilation. /// </summary> /// <returns></returns> public string[] GetWarnings() { return m_warnings.ToArray(); } private void AddWarning(string warning) { if (!m_warnings.Contains(warning)) { m_warnings.Add(warning); } } /// <summary> /// Recursively called to generate each type of node. Will generate this /// node, then all it's children. /// </summary> /// <param name="s">The current node to generate code for.</param> /// <returns>String containing C# code for SYMBOL s.</returns> private string GenerateNode(SYMBOL s) { string retstr = String.Empty; // make sure to put type lower in the inheritance hierarchy first // ie: since IdentArgument and ExpressionArgument inherit from // Argument, put IdentArgument and ExpressionArgument before Argument if (s is GlobalFunctionDefinition) retstr += GenerateGlobalFunctionDefinition((GlobalFunctionDefinition) s); else if (s is GlobalVariableDeclaration) retstr += GenerateGlobalVariableDeclaration((GlobalVariableDeclaration) s); else if (s is State) retstr += GenerateState((State) s); else if (s is CompoundStatement) retstr += GenerateCompoundStatement((CompoundStatement) s); else if (s is Declaration) retstr += GenerateDeclaration((Declaration) s); else if (s is Statement) retstr += GenerateStatement((Statement) s); else if (s is ReturnStatement) retstr += GenerateReturnStatement((ReturnStatement) s); else if (s is JumpLabel) retstr += GenerateJumpLabel((JumpLabel) s); else if (s is JumpStatement) retstr += GenerateJumpStatement((JumpStatement) s); else if (s is StateChange) retstr += GenerateStateChange((StateChange) s); else if (s is IfStatement) retstr += GenerateIfStatement((IfStatement) s); else if (s is WhileStatement) retstr += GenerateWhileStatement((WhileStatement) s); else if (s is DoWhileStatement) retstr += GenerateDoWhileStatement((DoWhileStatement) s); else if (s is ForLoop) retstr += GenerateForLoop((ForLoop) s); else if (s is ArgumentList) retstr += GenerateArgumentList((ArgumentList) s); else if (s is Assignment) retstr += GenerateAssignment((Assignment) s); else if (s is BinaryExpression) retstr += GenerateBinaryExpression((BinaryExpression) s); else if (s is ParenthesisExpression) retstr += GenerateParenthesisExpression((ParenthesisExpression) s); else if (s is UnaryExpression) retstr += GenerateUnaryExpression((UnaryExpression) s); else if (s is IncrementDecrementExpression) retstr += GenerateIncrementDecrementExpression((IncrementDecrementExpression) s); else if (s is TypecastExpression) retstr += GenerateTypecastExpression((TypecastExpression) s); else if (s is FunctionCall) retstr += GenerateFunctionCall((FunctionCall) s); else if (s is VectorConstant) retstr += GenerateVectorConstant((VectorConstant) s); else if (s is RotationConstant) retstr += GenerateRotationConstant((RotationConstant) s); else if (s is ListConstant) retstr += GenerateListConstant((ListConstant) s); else if (s is Constant) retstr += GenerateConstant((Constant) s); else if (s is IdentDotExpression) retstr += Generate(CheckName(((IdentDotExpression) s).Name) + "." + ((IdentDotExpression) s).Member, s); else if (s is IdentExpression) retstr += Generate(CheckName(((IdentExpression) s).Name), s); else if (s is IDENT) retstr += Generate(CheckName(((TOKEN) s).yytext), s); else { foreach (SYMBOL kid in s.kids) retstr += GenerateNode(kid); } return retstr; } /// <summary> /// Generates the code for a GlobalFunctionDefinition node. /// </summary> /// <param name="gf">The GlobalFunctionDefinition node.</param> /// <returns>String containing C# code for GlobalFunctionDefinition gf.</returns> private string GenerateGlobalFunctionDefinition(GlobalFunctionDefinition gf) { string retstr = String.Empty; // we need to separate the argument declaration list from other kids List<SYMBOL> argumentDeclarationListKids = new List<SYMBOL>(); List<SYMBOL> remainingKids = new List<SYMBOL>(); foreach (SYMBOL kid in gf.kids) if (kid is ArgumentDeclarationList) argumentDeclarationListKids.Add(kid); else remainingKids.Add(kid); retstr += GenerateIndented(String.Format("{0} {1}(", gf.ReturnType, CheckName(gf.Name)), gf); // print the state arguments, if any foreach (SYMBOL kid in argumentDeclarationListKids) retstr += GenerateArgumentDeclarationList((ArgumentDeclarationList) kid); retstr += GenerateLine(")"); foreach (SYMBOL kid in remainingKids) retstr += GenerateNode(kid); return retstr; } /// <summary> /// Generates the code for a GlobalVariableDeclaration node. /// </summary> /// <param name="gv">The GlobalVariableDeclaration node.</param> /// <returns>String containing C# code for GlobalVariableDeclaration gv.</returns> private string GenerateGlobalVariableDeclaration(GlobalVariableDeclaration gv) { string retstr = String.Empty; foreach (SYMBOL s in gv.kids) { retstr += Indent(); retstr += GenerateNode(s); retstr += GenerateLine(";"); } return retstr; } /// <summary> /// Generates the code for a State node. /// </summary> /// <param name="s">The State node.</param> /// <returns>String containing C# code for State s.</returns> private string GenerateState(State s) { string retstr = String.Empty; foreach (SYMBOL kid in s.kids) if (kid is StateEvent) retstr += GenerateStateEvent((StateEvent) kid, s.Name); return retstr; } /// <summary> /// Generates the code for a StateEvent node. /// </summary> /// <param name="se">The StateEvent node.</param> /// <param name="parentStateName">The name of the parent state.</param> /// <returns>String containing C# code for StateEvent se.</returns> private string GenerateStateEvent(StateEvent se, string parentStateName) { string retstr = String.Empty; // we need to separate the argument declaration list from other kids List<SYMBOL> argumentDeclarationListKids = new List<SYMBOL>(); List<SYMBOL> remainingKids = new List<SYMBOL>(); foreach (SYMBOL kid in se.kids) if (kid is ArgumentDeclarationList) argumentDeclarationListKids.Add(kid); else remainingKids.Add(kid); // "state" (function) declaration retstr += GenerateIndented(String.Format("public void {0}_event_{1}(", parentStateName, se.Name), se); // print the state arguments, if any foreach (SYMBOL kid in argumentDeclarationListKids) retstr += GenerateArgumentDeclarationList((ArgumentDeclarationList) kid); retstr += GenerateLine(")"); foreach (SYMBOL kid in remainingKids) retstr += GenerateNode(kid); return retstr; } /// <summary> /// Generates the code for an ArgumentDeclarationList node. /// </summary> /// <param name="adl">The ArgumentDeclarationList node.</param> /// <returns>String containing C# code for ArgumentDeclarationList adl.</returns> private string GenerateArgumentDeclarationList(ArgumentDeclarationList adl) { string retstr = String.Empty; int comma = adl.kids.Count - 1; // tells us whether to print a comma foreach (Declaration d in adl.kids) { retstr += Generate(String.Format("{0} {1}", d.Datatype, CheckName(d.Id)), d); if (0 < comma--) retstr += Generate(", "); } return retstr; } /// <summary> /// Generates the code for an ArgumentList node. /// </summary> /// <param name="al">The ArgumentList node.</param> /// <returns>String containing C# code for ArgumentList al.</returns> private string GenerateArgumentList(ArgumentList al) { string retstr = String.Empty; int comma = al.kids.Count - 1; // tells us whether to print a comma foreach (SYMBOL s in al.kids) { retstr += GenerateNode(s); if (0 < comma--) retstr += Generate(", "); } return retstr; } /// <summary> /// Generates the code for a CompoundStatement node. /// </summary> /// <param name="cs">The CompoundStatement node.</param> /// <returns>String containing C# code for CompoundStatement cs.</returns> private string GenerateCompoundStatement(CompoundStatement cs) { string retstr = String.Empty; // opening brace retstr += GenerateIndentedLine("{"); m_braceCount++; foreach (SYMBOL kid in cs.kids) retstr += GenerateNode(kid); // closing brace m_braceCount--; retstr += GenerateIndentedLine("}"); return retstr; } /// <summary> /// Generates the code for a Declaration node. /// </summary> /// <param name="d">The Declaration node.</param> /// <returns>String containing C# code for Declaration d.</returns> private string GenerateDeclaration(Declaration d) { return Generate(String.Format("{0} {1}", d.Datatype, CheckName(d.Id)), d); } /// <summary> /// Generates the code for a Statement node. /// </summary> /// <param name="s">The Statement node.</param> /// <returns>String containing C# code for Statement s.</returns> private string GenerateStatement(Statement s) { string retstr = String.Empty; bool printSemicolon = true; retstr += Indent(); if (0 < s.kids.Count) { // Jump label prints its own colon, we don't need a semicolon. printSemicolon = !(s.kids.Top is JumpLabel); // If we encounter a lone Ident, we skip it, since that's a C# // (MONO) error. if (!(s.kids.Top is IdentExpression && 1 == s.kids.Count)) foreach (SYMBOL kid in s.kids) retstr += GenerateNode(kid); } if (printSemicolon) retstr += GenerateLine(";"); return retstr; } /// <summary> /// Generates the code for an Assignment node. /// </summary> /// <param name="a">The Assignment node.</param> /// <returns>String containing C# code for Assignment a.</returns> private string GenerateAssignment(Assignment a) { string retstr = String.Empty; List<string> identifiers = new List<string>(); checkForMultipleAssignments(identifiers, a); retstr += GenerateNode((SYMBOL) a.kids.Pop()); retstr += Generate(String.Format(" {0} ", a.AssignmentType), a); foreach (SYMBOL kid in a.kids) retstr += GenerateNode(kid); return retstr; } // This code checks for LSL of the following forms, and generates a // warning if it finds them. // // list l = [ "foo" ]; // l = (l=[]) + l + ["bar"]; // (produces l=["foo","bar"] in SL but l=["bar"] in OS) // // integer i; // integer j; // i = (j = 3) + (j = 4) + (j = 5); // (produces j=3 in SL but j=5 in OS) // // Without this check, that code passes compilation, but does not do what // the end user expects, because LSL in SL evaluates right to left instead // of left to right. // // The theory here is that producing an error and alerting the end user that // something needs to change is better than silently generating incorrect code. private void checkForMultipleAssignments(List<string> identifiers, SYMBOL s) { if (s is Assignment) { Assignment a = (Assignment)s; string newident = null; if (a.kids[0] is Declaration) { newident = ((Declaration)a.kids[0]).Id; } else if (a.kids[0] is IDENT) { newident = ((IDENT)a.kids[0]).yytext; } else if (a.kids[0] is IdentDotExpression) { newident = ((IdentDotExpression)a.kids[0]).Name; // +"." + ((IdentDotExpression)a.kids[0]).Member; } else { AddWarning(String.Format("Multiple assignments checker internal error '{0}' at line {1} column {2}.", a.kids[0].GetType(), ((SYMBOL)a.kids[0]).Line - 1, ((SYMBOL)a.kids[0]).Position)); } if (identifiers.Contains(newident)) { AddWarning(String.Format("Multiple assignments to '{0}' at line {1} column {2}; results may differ between LSL and OSSL.", newident, ((SYMBOL)a.kids[0]).Line - 1, ((SYMBOL)a.kids[0]).Position)); } identifiers.Add(newident); } int index; for (index = 0; index < s.kids.Count; index++) { checkForMultipleAssignments(identifiers, (SYMBOL) s.kids[index]); } } /// <summary> /// Generates the code for a ReturnStatement node. /// </summary> /// <param name="rs">The ReturnStatement node.</param> /// <returns>String containing C# code for ReturnStatement rs.</returns> private string GenerateReturnStatement(ReturnStatement rs) { string retstr = String.Empty; retstr += Generate("return ", rs); foreach (SYMBOL kid in rs.kids) retstr += GenerateNode(kid); return retstr; } /// <summary> /// Generates the code for a JumpLabel node. /// </summary> /// <param name="jl">The JumpLabel node.</param> /// <returns>String containing C# code for JumpLabel jl.</returns> private string GenerateJumpLabel(JumpLabel jl) { return Generate(String.Format("{0}:", CheckName(jl.LabelName)), jl) + " NoOp();\n"; } /// <summary> /// Generates the code for a JumpStatement node. /// </summary> /// <param name="js">The JumpStatement node.</param> /// <returns>String containing C# code for JumpStatement js.</returns> private string GenerateJumpStatement(JumpStatement js) { return Generate(String.Format("goto {0}", CheckName(js.TargetName)), js); } /// <summary> /// Generates the code for an IfStatement node. /// </summary> /// <param name="ifs">The IfStatement node.</param> /// <returns>String containing C# code for IfStatement ifs.</returns> private string GenerateIfStatement(IfStatement ifs) { string retstr = String.Empty; retstr += GenerateIndented("if (", ifs); retstr += GenerateNode((SYMBOL) ifs.kids.Pop()); retstr += GenerateLine(")"); // CompoundStatement handles indentation itself but we need to do it // otherwise. bool indentHere = ifs.kids.Top is Statement; if (indentHere) m_braceCount++; retstr += GenerateNode((SYMBOL) ifs.kids.Pop()); if (indentHere) m_braceCount--; if (0 < ifs.kids.Count) // do it again for an else { retstr += GenerateIndentedLine("else", ifs); indentHere = ifs.kids.Top is Statement; if (indentHere) m_braceCount++; retstr += GenerateNode((SYMBOL) ifs.kids.Pop()); if (indentHere) m_braceCount--; } return retstr; } /// <summary> /// Generates the code for a StateChange node. /// </summary> /// <param name="sc">The StateChange node.</param> /// <returns>String containing C# code for StateChange sc.</returns> private string GenerateStateChange(StateChange sc) { return Generate(String.Format("state(\"{0}\")", sc.NewState), sc); } /// <summary> /// Generates the code for a WhileStatement node. /// </summary> /// <param name="ws">The WhileStatement node.</param> /// <returns>String containing C# code for WhileStatement ws.</returns> private string GenerateWhileStatement(WhileStatement ws) { string retstr = String.Empty; retstr += GenerateIndented("while (", ws); retstr += GenerateNode((SYMBOL) ws.kids.Pop()); retstr += GenerateLine(")"); // CompoundStatement handles indentation itself but we need to do it // otherwise. bool indentHere = ws.kids.Top is Statement; if (indentHere) m_braceCount++; retstr += GenerateNode((SYMBOL) ws.kids.Pop()); if (indentHere) m_braceCount--; return retstr; } /// <summary> /// Generates the code for a DoWhileStatement node. /// </summary> /// <param name="dws">The DoWhileStatement node.</param> /// <returns>String containing C# code for DoWhileStatement dws.</returns> private string GenerateDoWhileStatement(DoWhileStatement dws) { string retstr = String.Empty; retstr += GenerateIndentedLine("do", dws); // CompoundStatement handles indentation itself but we need to do it // otherwise. bool indentHere = dws.kids.Top is Statement; if (indentHere) m_braceCount++; retstr += GenerateNode((SYMBOL) dws.kids.Pop()); if (indentHere) m_braceCount--; retstr += GenerateIndented("while (", dws); retstr += GenerateNode((SYMBOL) dws.kids.Pop()); retstr += GenerateLine(");"); return retstr; } /// <summary> /// Generates the code for a ForLoop node. /// </summary> /// <param name="fl">The ForLoop node.</param> /// <returns>String containing C# code for ForLoop fl.</returns> private string GenerateForLoop(ForLoop fl) { string retstr = String.Empty; retstr += GenerateIndented("for (", fl); // It's possible that we don't have an assignment, in which case // the child will be null and we only print the semicolon. // for (x = 0; x < 10; x++) // ^^^^^ ForLoopStatement s = (ForLoopStatement) fl.kids.Pop(); if (null != s) { retstr += GenerateForLoopStatement(s); } retstr += Generate("; "); // for (x = 0; x < 10; x++) // ^^^^^^ retstr += GenerateNode((SYMBOL) fl.kids.Pop()); retstr += Generate("; "); // for (x = 0; x < 10; x++) // ^^^ retstr += GenerateForLoopStatement((ForLoopStatement) fl.kids.Pop()); retstr += GenerateLine(")"); // CompoundStatement handles indentation itself but we need to do it // otherwise. bool indentHere = fl.kids.Top is Statement; if (indentHere) m_braceCount++; retstr += GenerateNode((SYMBOL) fl.kids.Pop()); if (indentHere) m_braceCount--; return retstr; } /// <summary> /// Generates the code for a ForLoopStatement node. /// </summary> /// <param name="fls">The ForLoopStatement node.</param> /// <returns>String containing C# code for ForLoopStatement fls.</returns> private string GenerateForLoopStatement(ForLoopStatement fls) { string retstr = String.Empty; int comma = fls.kids.Count - 1; // tells us whether to print a comma // It's possible that all we have is an empty Ident, for example: // // for (x; x < 10; x++) { ... } // // Which is illegal in C# (MONO). We'll skip it. if (fls.kids.Top is IdentExpression && 1 == fls.kids.Count) return retstr; foreach (SYMBOL s in fls.kids) { retstr += GenerateNode(s); if (0 < comma--) retstr += Generate(", "); } return retstr; } /// <summary> /// Generates the code for a BinaryExpression node. /// </summary> /// <param name="be">The BinaryExpression node.</param> /// <returns>String containing C# code for BinaryExpression be.</returns> private string GenerateBinaryExpression(BinaryExpression be) { string retstr = String.Empty; if (be.ExpressionSymbol.Equals("&&") || be.ExpressionSymbol.Equals("||")) { // special case handling for logical and/or, see Mantis 3174 retstr += "((bool)("; retstr += GenerateNode((SYMBOL)be.kids.Pop()); retstr += "))"; retstr += Generate(String.Format(" {0} ", be.ExpressionSymbol.Substring(0,1)), be); retstr += "((bool)("; foreach (SYMBOL kid in be.kids) retstr += GenerateNode(kid); retstr += "))"; } else { retstr += GenerateNode((SYMBOL)be.kids.Pop()); retstr += Generate(String.Format(" {0} ", be.ExpressionSymbol), be); foreach (SYMBOL kid in be.kids) retstr += GenerateNode(kid); } return retstr; } /// <summary> /// Generates the code for a UnaryExpression node. /// </summary> /// <param name="ue">The UnaryExpression node.</param> /// <returns>String containing C# code for UnaryExpression ue.</returns> private string GenerateUnaryExpression(UnaryExpression ue) { string retstr = String.Empty; retstr += Generate(ue.UnarySymbol, ue); retstr += GenerateNode((SYMBOL) ue.kids.Pop()); return retstr; } /// <summary> /// Generates the code for a ParenthesisExpression node. /// </summary> /// <param name="pe">The ParenthesisExpression node.</param> /// <returns>String containing C# code for ParenthesisExpression pe.</returns> private string GenerateParenthesisExpression(ParenthesisExpression pe) { string retstr = String.Empty; retstr += Generate("("); foreach (SYMBOL kid in pe.kids) retstr += GenerateNode(kid); retstr += Generate(")"); return retstr; } /// <summary> /// Generates the code for a IncrementDecrementExpression node. /// </summary> /// <param name="ide">The IncrementDecrementExpression node.</param> /// <returns>String containing C# code for IncrementDecrementExpression ide.</returns> private string GenerateIncrementDecrementExpression(IncrementDecrementExpression ide) { string retstr = String.Empty; if (0 < ide.kids.Count) { IdentDotExpression dot = (IdentDotExpression) ide.kids.Top; retstr += Generate(String.Format("{0}", ide.PostOperation ? CheckName(dot.Name) + "." + dot.Member + ide.Operation : ide.Operation + CheckName(dot.Name) + "." + dot.Member), ide); } else retstr += Generate(String.Format("{0}", ide.PostOperation ? CheckName(ide.Name) + ide.Operation : ide.Operation + CheckName(ide.Name)), ide); return retstr; } /// <summary> /// Generates the code for a TypecastExpression node. /// </summary> /// <param name="te">The TypecastExpression node.</param> /// <returns>String containing C# code for TypecastExpression te.</returns> private string GenerateTypecastExpression(TypecastExpression te) { string retstr = String.Empty; // we wrap all typecasted statements in parentheses retstr += Generate(String.Format("({0}) (", te.TypecastType), te); retstr += GenerateNode((SYMBOL) te.kids.Pop()); retstr += Generate(")"); return retstr; } /// <summary> /// Generates the code for a FunctionCall node. /// </summary> /// <param name="fc">The FunctionCall node.</param> /// <returns>String containing C# code for FunctionCall fc.</returns> private string GenerateFunctionCall(FunctionCall fc) { string retstr = String.Empty; retstr += Generate(String.Format("{0}(", CheckName(fc.Id)), fc); foreach (SYMBOL kid in fc.kids) retstr += GenerateNode(kid); retstr += Generate(")"); return retstr; } /// <summary> /// Generates the code for a Constant node. /// </summary> /// <param name="c">The Constant node.</param> /// <returns>String containing C# code for Constant c.</returns> private string GenerateConstant(Constant c) { string retstr = String.Empty; // Supprt LSL's weird acceptance of floats with no trailing digits // after the period. Turn float x = 10.; into float x = 10.0; if ("LSL_Types.LSLFloat" == c.Type) { int dotIndex = c.Value.IndexOf('.') + 1; if (0 < dotIndex && (dotIndex == c.Value.Length || !Char.IsDigit(c.Value[dotIndex]))) c.Value = c.Value.Insert(dotIndex, "0"); c.Value = "new LSL_Types.LSLFloat("+c.Value+")"; } else if ("LSL_Types.LSLInteger" == c.Type) { c.Value = "new LSL_Types.LSLInteger("+c.Value+")"; } else if ("LSL_Types.LSLString" == c.Type) { c.Value = "new LSL_Types.LSLString(\""+c.Value+"\")"; } retstr += Generate(c.Value, c); return retstr; } /// <summary> /// Generates the code for a VectorConstant node. /// </summary> /// <param name="vc">The VectorConstant node.</param> /// <returns>String containing C# code for VectorConstant vc.</returns> private string GenerateVectorConstant(VectorConstant vc) { string retstr = String.Empty; retstr += Generate(String.Format("new {0}(", vc.Type), vc); retstr += GenerateNode((SYMBOL) vc.kids.Pop()); retstr += Generate(", "); retstr += GenerateNode((SYMBOL) vc.kids.Pop()); retstr += Generate(", "); retstr += GenerateNode((SYMBOL) vc.kids.Pop()); retstr += Generate(")"); return retstr; } /// <summary> /// Generates the code for a RotationConstant node. /// </summary> /// <param name="rc">The RotationConstant node.</param> /// <returns>String containing C# code for RotationConstant rc.</returns> private string GenerateRotationConstant(RotationConstant rc) { string retstr = String.Empty; retstr += Generate(String.Format("new {0}(", rc.Type), rc); retstr += GenerateNode((SYMBOL) rc.kids.Pop()); retstr += Generate(", "); retstr += GenerateNode((SYMBOL) rc.kids.Pop()); retstr += Generate(", "); retstr += GenerateNode((SYMBOL) rc.kids.Pop()); retstr += Generate(", "); retstr += GenerateNode((SYMBOL) rc.kids.Pop()); retstr += Generate(")"); return retstr; } /// <summary> /// Generates the code for a ListConstant node. /// </summary> /// <param name="lc">The ListConstant node.</param> /// <returns>String containing C# code for ListConstant lc.</returns> private string GenerateListConstant(ListConstant lc) { string retstr = String.Empty; retstr += Generate(String.Format("new {0}(", lc.Type), lc); foreach (SYMBOL kid in lc.kids) retstr += GenerateNode(kid); retstr += Generate(")"); return retstr; } /// <summary> /// Prints a newline. /// </summary> /// <returns>A newline.</returns> private string GenerateLine() { return GenerateLine(""); } /// <summary> /// Prints text, followed by a newline. /// </summary> /// <param name="s">String of text to print.</param> /// <returns>String s followed by newline.</returns> private string GenerateLine(string s) { return GenerateLine(s, null); } /// <summary> /// Prints text, followed by a newline. /// </summary> /// <param name="s">String of text to print.</param> /// <param name="sym">Symbol being generated to extract original line /// number and column from.</param> /// <returns>String s followed by newline.</returns> private string GenerateLine(string s, SYMBOL sym) { string retstr = Generate(s, sym) + "\n"; m_CSharpLine++; m_CSharpCol = 1; return retstr; } /// <summary> /// Prints text. /// </summary> /// <param name="s">String of text to print.</param> /// <returns>String s.</returns> private string Generate(string s) { return Generate(s, null); } /// <summary> /// Prints text. /// </summary> /// <param name="s">String of text to print.</param> /// <param name="sym">Symbol being generated to extract original line /// number and column from.</param> /// <returns>String s.</returns> private string Generate(string s, SYMBOL sym) { if (null != sym) m_positionMap.Add(new KeyValuePair<int, int>(m_CSharpLine, m_CSharpCol), new KeyValuePair<int, int>(sym.Line, sym.Position)); m_CSharpCol += s.Length; return s; } /// <summary> /// Prints text correctly indented, followed by a newline. /// </summary> /// <param name="s">String of text to print.</param> /// <returns>Properly indented string s followed by newline.</returns> private string GenerateIndentedLine(string s) { return GenerateIndentedLine(s, null); } /// <summary> /// Prints text correctly indented, followed by a newline. /// </summary> /// <param name="s">String of text to print.</param> /// <param name="sym">Symbol being generated to extract original line /// number and column from.</param> /// <returns>Properly indented string s followed by newline.</returns> private string GenerateIndentedLine(string s, SYMBOL sym) { string retstr = GenerateIndented(s, sym) + "\n"; m_CSharpLine++; m_CSharpCol = 1; return retstr; } /// <summary> /// Prints text correctly indented. /// </summary> /// <param name="s">String of text to print.</param> /// <returns>Properly indented string s.</returns> //private string GenerateIndented(string s) //{ // return GenerateIndented(s, null); //} // THIS FUNCTION IS COMMENTED OUT TO SUPPRESS WARNINGS /// <summary> /// Prints text correctly indented. /// </summary> /// <param name="s">String of text to print.</param> /// <param name="sym">Symbol being generated to extract original line /// number and column from.</param> /// <returns>Properly indented string s.</returns> private string GenerateIndented(string s, SYMBOL sym) { string retstr = Indent() + s; if (null != sym) m_positionMap.Add(new KeyValuePair<int, int>(m_CSharpLine, m_CSharpCol), new KeyValuePair<int, int>(sym.Line, sym.Position)); m_CSharpCol += s.Length; return retstr; } /// <summary> /// Prints correct indentation. /// </summary> /// <returns>Indentation based on brace count.</returns> private string Indent() { string retstr = String.Empty; for (int i = 0; i < m_braceCount; i++) for (int j = 0; j < m_indentWidth; j++) { retstr += " "; m_CSharpCol++; } return retstr; } /// <summary> /// Returns the passed name with an underscore prepended if that name is a reserved word in C# /// and not resevered in LSL otherwise it just returns the passed name. /// /// This makes no attempt to cache the results to minimise future lookups. For a non trivial /// scripts the number of unique identifiers could easily grow to the size of the reserved word /// list so maintaining a list or dictionary and doing the lookup there firstwould probably not /// give any real speed advantage. /// /// I believe there is a class Microsoft.CSharp.CSharpCodeProvider that has a function /// CreateValidIdentifier(str) that will return either the value of str if it is not a C# /// key word or "_"+str if it is. But availability under Mono? /// </summary> private string CheckName(string s) { if (CSReservedWords.IsReservedWord(s)) return "@" + s; else return s; } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Statistics.Algo File: IOrderStatisticParameter.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Statistics { using System; using Ecng.Common; using Ecng.Serialization; using StockSharp.BusinessEntities; using StockSharp.Localization; /// <summary> /// The interface, describing statistic parameter, calculated based on orders. /// </summary> public interface IOrderStatisticParameter { /// <summary> /// To add to the parameter an information on new order. /// </summary> /// <param name="order">New order.</param> void New(Order order); /// <summary> /// To add to the parameter an information on changed order. /// </summary> /// <param name="order">The changed order.</param> void Changed(Order order); /// <summary> /// To add to the parameter an information on error of order registration. /// </summary> /// <param name="fail">Error registering order.</param> void RegisterFailed(OrderFail fail); /// <summary> /// To add to the parameter an information on error of order cancelling. /// </summary> /// <param name="fail">Error cancelling order.</param> void CancelFailed(OrderFail fail); } /// <summary> /// The base statistic parameter, calculated based on orders. /// </summary> /// <typeparam name="TValue">The type of the parameter value.</typeparam> public abstract class BaseOrderStatisticParameter<TValue> : BaseStatisticParameter<TValue>, IOrderStatisticParameter where TValue : IComparable<TValue> { /// <summary> /// Initialize <see cref="BaseOrderStatisticParameter{T}"/>. /// </summary> protected BaseOrderStatisticParameter() { } /// <summary> /// To add to the parameter an information on new order. /// </summary> /// <param name="order">New order.</param> public virtual void New(Order order) { } /// <summary> /// To add to the parameter an information on changed order. /// </summary> /// <param name="order">The changed order.</param> public virtual void Changed(Order order) { } /// <summary> /// To add to the parameter an information on error of order registration. /// </summary> /// <param name="fail">Error registering order.</param> public virtual void RegisterFailed(OrderFail fail) { } /// <summary> /// To add to the parameter an information on error of order cancelling. /// </summary> /// <param name="fail">Error cancelling order.</param> public virtual void CancelFailed(OrderFail fail) { } } /// <summary> /// The maximal value of the order registration delay. /// </summary> [DisplayNameLoc(LocalizedStrings.Str947Key)] [DescriptionLoc(LocalizedStrings.Str948Key)] [CategoryLoc(LocalizedStrings.OrdersKey)] public class MaxLatencyRegistrationParameter : BaseOrderStatisticParameter<TimeSpan> { /// <summary> /// To add to the parameter an information on new order. /// </summary> /// <param name="order">New order.</param> public override void New(Order order) { if (order.LatencyRegistration != null) Value = Value.Max(order.LatencyRegistration.Value); } } /// <summary> /// The maximal value of the order cancelling delay. /// </summary> [DisplayNameLoc(LocalizedStrings.Str950Key)] [DescriptionLoc(LocalizedStrings.Str951Key)] [CategoryLoc(LocalizedStrings.OrdersKey)] public class MaxLatencyCancellationParameter : BaseOrderStatisticParameter<TimeSpan> { /// <summary> /// To add to the parameter an information on changed order. /// </summary> /// <param name="order">The changed order.</param> public override void Changed(Order order) { if (order.LatencyCancellation != null) Value = Value.Max(order.LatencyCancellation.Value); } } /// <summary> /// The minimal value of order registration delay. /// </summary> [DisplayNameLoc(LocalizedStrings.Str952Key)] [DescriptionLoc(LocalizedStrings.Str953Key)] [CategoryLoc(LocalizedStrings.OrdersKey)] public class MinLatencyRegistrationParameter : BaseOrderStatisticParameter<TimeSpan> { private bool _initialized; /// <summary> /// To add to the parameter an information on new order. /// </summary> /// <param name="order">New order.</param> public override void New(Order order) { if (order.LatencyRegistration == null) return; if (!_initialized) { Value = order.LatencyRegistration.Value; _initialized = true; } else Value = Value.Min(order.LatencyRegistration.Value); } /// <summary> /// To load the state of statistic parameter. /// </summary> /// <param name="storage">Storage.</param> public override void Load(SettingsStorage storage) { _initialized = storage.GetValue<bool>("Initialized"); base.Load(storage); } /// <summary> /// To save the state of statistic parameter. /// </summary> /// <param name="storage">Storage.</param> public override void Save(SettingsStorage storage) { storage.SetValue("Initialized", _initialized); base.Save(storage); } } /// <summary> /// The minimal value of order cancelling delay. /// </summary> [DisplayNameLoc(LocalizedStrings.Str954Key)] [DescriptionLoc(LocalizedStrings.Str955Key)] [CategoryLoc(LocalizedStrings.OrdersKey)] public class MinLatencyCancellationParameter : BaseOrderStatisticParameter<TimeSpan> { private bool _initialized; /// <summary> /// To add to the parameter an information on changed order. /// </summary> /// <param name="order">The changed order.</param> public override void Changed(Order order) { if (order.LatencyCancellation == null) return; if (!_initialized) { Value = order.LatencyCancellation.Value; _initialized = true; } else Value = Value.Min(order.LatencyCancellation.Value); } /// <summary> /// To load the state of statistic parameter. /// </summary> /// <param name="storage">Storage.</param> public override void Load(SettingsStorage storage) { _initialized = storage.GetValue<bool>("Initialized"); base.Load(storage); } /// <summary> /// To save the state of statistic parameter. /// </summary> /// <param name="storage">Storage.</param> public override void Save(SettingsStorage storage) { storage.SetValue("Initialized", _initialized); base.Save(storage); } } /// <summary> /// Total number of orders. /// </summary> [DisplayNameLoc(LocalizedStrings.Str956Key)] [DescriptionLoc(LocalizedStrings.Str957Key)] [CategoryLoc(LocalizedStrings.OrdersKey)] public class OrderCountParameter : BaseOrderStatisticParameter<int> { /// <summary> /// To add to the parameter an information on new order. /// </summary> /// <param name="order">New order.</param> public override void New(Order order) { Value++; } } }
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <[email protected]>, 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. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using System.Threading; using NLog.Common; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class RoundRobinGroupTargetTests : NLogTestBase { [Fact] public void RoundRobinGroupTargetSyncTest1() { var myTarget1 = new MyTarget(); var myTarget2 = new MyTarget(); var myTarget3 = new MyTarget(); var wrapper = new RoundRobinGroupTarget() { Targets = { myTarget1, myTarget2, myTarget3 }, }; myTarget1.Initialize(null); myTarget2.Initialize(null); myTarget3.Initialize(null); wrapper.Initialize(null); List<Exception> exceptions = new List<Exception>(); // no exceptions for (int i = 0; i < 10; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } Assert.Equal(10, exceptions.Count); foreach (var e in exceptions) { Assert.Null(e); } Assert.Equal(4, myTarget1.WriteCount); Assert.Equal(3, myTarget2.WriteCount); Assert.Equal(3, myTarget3.WriteCount); Exception flushException = null; var flushHit = new ManualResetEvent(false); wrapper.Flush(ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); if (flushException != null) { Assert.True(false, flushException.ToString()); } Assert.Equal(1, myTarget1.FlushCount); Assert.Equal(1, myTarget2.FlushCount); Assert.Equal(1, myTarget3.FlushCount); } [Fact] public void RoundRobinGroupTargetSyncTest2() { var wrapper = new RoundRobinGroupTarget() { // empty target list }; wrapper.Initialize(null); List<Exception> exceptions = new List<Exception>(); // no exceptions for (int i = 0; i < 10; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } Assert.Equal(10, exceptions.Count); foreach (var e in exceptions) { Assert.Null(e); } Exception flushException = null; var flushHit = new ManualResetEvent(false); wrapper.Flush(ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); if (flushException != null) { Assert.True(false, flushException.ToString()); } } public class MyAsyncTarget : Target { public int FlushCount { get; private set; } public int WriteCount { get; private set; } public MyAsyncTarget() : base() { } public MyAsyncTarget(string name) : this() { Name = name; } protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException(); } protected override void Write(AsyncLogEventInfo logEvent) { Assert.True(FlushCount <= WriteCount); WriteCount++; ThreadPool.QueueUserWorkItem( s => { if (ThrowExceptions) { logEvent.Continuation(new InvalidOperationException("Some problem!")); logEvent.Continuation(new InvalidOperationException("Some problem!")); } else { logEvent.Continuation(null); logEvent.Continuation(null); } }); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { FlushCount++; ThreadPool.QueueUserWorkItem( s => asyncContinuation(null)); } public bool ThrowExceptions { get; set; } } class MyTarget : Target { public int FlushCount { get; set; } public int WriteCount { get; set; } public int FailCounter { get; set; } public MyTarget() : base() { } public MyTarget(string name) : this() { Name = name; } protected override void Write(LogEventInfo logEvent) { Assert.True(FlushCount <= WriteCount); WriteCount++; if (FailCounter > 0) { FailCounter--; throw new InvalidOperationException("Some failure."); } } protected override void FlushAsync(AsyncContinuation asyncContinuation) { FlushCount++; asyncContinuation(null); } } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Windows.Automation; using System.Windows.Input; using System.Windows.Interop; using EnvDTE; using Microsoft.PythonTools; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.InteractiveWindow.Shell; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Options; using Microsoft.PythonTools.Parsing; using Microsoft.PythonTools.Project; using Microsoft.PythonTools.Repl; using Microsoft.VisualStudio; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudioTools; using Microsoft.Win32; using TestUtilities.Python; using Process = System.Diagnostics.Process; namespace TestUtilities.UI.Python { class PythonVisualStudioApp : VisualStudioApp { private bool _deletePerformanceSessions; private PythonPerfExplorer _perfTreeView; private PythonPerfToolBar _perfToolBar; public readonly PythonToolsService PythonToolsService; public PythonVisualStudioApp(DTE dte = null) : base(dte) { var shell = (IVsShell)ServiceProvider.GetService(typeof(SVsShell)); var pkg = new Guid("6dbd7c1e-1f1b-496d-ac7c-c55dae66c783"); IVsPackage pPkg; ErrorHandler.ThrowOnFailure(shell.LoadPackage(ref pkg, out pPkg)); System.Threading.Thread.Sleep(1000); PythonToolsService = ServiceProvider.GetPythonToolsService_NotThreadSafe(); Assert.IsNotNull(PythonToolsService, "Failed to get PythonToolsService"); // Disable AutoListIdentifiers for tests var ao = PythonToolsService.AdvancedOptions; Assert.IsNotNull(ao, "Failed to get AdvancedOptions"); var oldALI = ao.AutoListIdentifiers; ao.AutoListIdentifiers = false; var orwoodProp = Dte.Properties["Environment", "ProjectsAndSolution"].Item("OnRunWhenOutOfDate"); Assert.IsNotNull(orwoodProp, "Failed to get OnRunWhenOutOfDate property"); var oldOrwood = orwoodProp.Value; orwoodProp.Value = 1; OnDispose(() => { ao.AutoListIdentifiers = oldALI; orwoodProp.Value = oldOrwood; }); } protected override void Dispose(bool disposing) { if (!IsDisposed) { try { ServiceProvider.GetUIThread().Invoke(() => { var iwp = ComponentModel.GetService<InteractiveWindowProvider>(); if (iwp != null) { foreach (var w in iwp.AllOpenWindows) { w.InteractiveWindow.Close(); } } }); } catch (Exception ex) { Console.WriteLine("Error while closing all interactive windows"); Console.WriteLine(ex); } if (_deletePerformanceSessions) { try { dynamic profiling = Dte.GetObject("PythonProfiling"); for (dynamic session = profiling.GetSession(1); session != null; session = profiling.GetSession(1)) { profiling.RemoveSession(session, true); } } catch (Exception ex) { Console.WriteLine("Error while cleaning up profiling sessions"); Console.WriteLine(ex); } } } base.Dispose(disposing); } // Constants for passing to CreateProject private const string _templateLanguageName = "Python"; public static string TemplateLanguageName { get { return _templateLanguageName; } } public const string PythonApplicationTemplate = "ConsoleAppProject"; public const string EmptyWebProjectTemplate = "WebProjectEmpty"; public const string BottleWebProjectTemplate = "WebProjectBottle"; public const string FlaskWebProjectTemplate = "WebProjectFlask"; public const string DjangoWebProjectTemplate = "DjangoProject"; public const string WorkerRoleProjectTemplate = "WorkerRoleProject"; public const string EmptyFileTemplate = "EmptyPyFile"; public const string WebRoleSupportTemplate = "AzureCSWebRole"; public const string WorkerRoleSupportTemplate = "AzureCSWorkerRole"; /// <summary> /// Opens and activates the solution explorer window. /// </summary> public void OpenPythonPerformance() { try { _deletePerformanceSessions = true; Dte.ExecuteCommand("Python.PerformanceExplorer"); } catch { // If the package is not loaded yet then the command may not // work. Force load the package by opening the Launch dialog. using (var dialog = new PythonPerfTarget(OpenDialogWithDteExecuteCommand("Python.LaunchProfiling"))) { } Dte.ExecuteCommand("Python.PerformanceExplorer"); } } /// <summary> /// Opens and activates the solution explorer window. /// </summary> public PythonPerfTarget LaunchPythonProfiling() { _deletePerformanceSessions = true; return new PythonPerfTarget(OpenDialogWithDteExecuteCommand("Python.LaunchProfiling")); } /// <summary> /// Provides access to the Python profiling tree view. /// </summary> public PythonPerfExplorer PythonPerformanceExplorerTreeView { get { if (_perfTreeView == null) { var element = Element.FindFirst(TreeScope.Descendants, new AndCondition( new PropertyCondition( AutomationElement.ClassNameProperty, "SysTreeView32" ), new PropertyCondition( AutomationElement.NameProperty, "Python Performance" ) ) ); _perfTreeView = new PythonPerfExplorer(element); } return _perfTreeView; } } /// <summary> /// Provides access to the Python profiling tool bar /// </summary> public PythonPerfToolBar PythonPerformanceExplorerToolBar { get { if (_perfToolBar == null) { var element = Element.FindFirst(TreeScope.Descendants, new AndCondition( new PropertyCondition( AutomationElement.ClassNameProperty, "ToolBar" ), new PropertyCondition( AutomationElement.NameProperty, "Python Performance" ) ) ); _perfToolBar = new PythonPerfToolBar(element); } return _perfToolBar; } } public ReplWindowProxy ExecuteInInteractive(Project project, PythonReplWindowProxySettings settings = null) { OpenSolutionExplorer().SelectProject(project); ExecuteCommand("Python.ExecuteInInteractive"); return GetInteractiveWindow(project); } public void SendToInteractive() { ExecuteCommand("Python.SendSelectionToInteractive"); } public ReplWindowProxy WaitForInteractiveWindow(string title, PythonReplWindowProxySettings settings = null) { var iwp = GetService<IComponentModel>(typeof(SComponentModel))?.GetService<InteractiveWindowProvider>(); IVsInteractiveWindow window = null; for (int retries = 20; retries > 0 && window == null; --retries) { System.Threading.Thread.Sleep(100); window = iwp?.AllOpenWindows.FirstOrDefault(w => ((ToolWindowPane)w).Caption == title); } if (window == null) { Trace.TraceWarning( "Failed to find {0} in {1}", title, string.Join(", ", iwp?.AllOpenWindows.Select(w => ((ToolWindowPane)w).Caption) ?? Enumerable.Empty<string>()) ); return null; } return new ReplWindowProxy(this, window.InteractiveWindow, (ToolWindowPane)window, settings ?? new PythonReplWindowProxySettings()); } public ReplWindowProxy GetInteractiveWindow(Project project, PythonReplWindowProxySettings settings = null) { return GetInteractiveWindow(project.Name + " Interactive", settings); } public ReplWindowProxy GetInteractiveWindow(string title, PythonReplWindowProxySettings settings = null) { var iwp = GetService<IComponentModel>(typeof(SComponentModel))?.GetService<InteractiveWindowProvider>(); var window = iwp?.AllOpenWindows.FirstOrDefault(w => ((ToolWindowPane)w).Caption == title); if (window == null) { Trace.TraceWarning( "Failed to find {0} in {1}", title, string.Join(", ", iwp?.AllOpenWindows.Select(w => ((ToolWindowPane)w).Caption) ?? Enumerable.Empty<string>()) ); return null; } return new ReplWindowProxy(this, window.InteractiveWindow, (ToolWindowPane)window, settings ?? new PythonReplWindowProxySettings()); } internal Document WaitForDocument(string docName) { for (int i = 0; i < 100; i++) { try { return Dte.Documents.Item(docName); } catch { System.Threading.Thread.Sleep(100); } } throw new InvalidOperationException("Document not opened: " + docName); } /// <summary> /// Selects the given interpreter as the default. /// </summary> /// <remarks> /// This method should always be called as a using block. /// </remarks> public DefaultInterpreterSetter SelectDefaultInterpreter(PythonVersion python) { return new DefaultInterpreterSetter( InterpreterService.FindInterpreter(python.Id), ServiceProvider ); } public DefaultInterpreterSetter SelectDefaultInterpreter(PythonVersion interp, string installPackages) { interp.AssertInstalled(); if (interp.IsIronPython && !string.IsNullOrEmpty(installPackages)) { Assert.Inconclusive("Package installation not supported on IronPython"); } var interpreterService = InterpreterService; var factory = interpreterService.FindInterpreter(interp.Id); var defaultInterpreterSetter = new DefaultInterpreterSetter(factory); try { if (!string.IsNullOrEmpty(installPackages)) { factory.InstallPip(); foreach (var package in installPackages.Split(' ', ',', ';').Select(s => s.Trim()).Where(s => !string.IsNullOrEmpty(s))) { factory.PipInstall("-U " + package); } } Assert.AreEqual(factory.Configuration.Id, OptionsService.DefaultInterpreterId); var result = defaultInterpreterSetter; defaultInterpreterSetter = null; return result; } finally { if (defaultInterpreterSetter != null) { defaultInterpreterSetter.Dispose(); } } } public IInterpreterRegistryService InterpreterService { get { var model = GetService<IComponentModel>(typeof(SComponentModel)); var service = model.GetService<IInterpreterRegistryService>(); Assert.IsNotNull(service, "Unable to get IInterpreterRegistryService"); return service; } } public IInterpreterOptionsService OptionsService { get { var model = GetService<IComponentModel>(typeof(SComponentModel)); var service = model.GetService<IInterpreterOptionsService>(); Assert.IsNotNull(service, "Unable to get InterpreterOptionsService"); return service; } } public TreeNode CreateVirtualEnvironment(EnvDTE.Project project, out string envName) { string dummy; return CreateVirtualEnvironment(project, out envName, out dummy); } public TreeNode CreateVirtualEnvironment(EnvDTE.Project project, out string envName, out string envPath) { var environmentsNode = OpenSolutionExplorer().FindChildOfProject(project, Strings.Environments); environmentsNode.Select(); using (var pss = new ProcessScope("python")) { using (var createVenv = AutomationDialog.FromDte(this, "Python.AddVirtualEnvironment")) { envPath = new TextBox(createVenv.FindByAutomationId("VirtualEnvPath")).GetValue(); var baseInterp = new ComboBox(createVenv.FindByAutomationId("BaseInterpreter")).GetSelectedItemName(); envName = "{0} ({1})".FormatUI(envPath, baseInterp); Console.WriteLine("Expecting environment named: {0}", envName); // Force a wait for the view to be updated. var wnd = (DialogWindowVersioningWorkaround)HwndSource.FromHwnd( new IntPtr(createVenv.Element.Current.NativeWindowHandle) ).RootVisual; wnd.Dispatcher.Invoke(() => { var view = (AddVirtualEnvironmentView)wnd.DataContext; return view.UpdateInterpreter(view.BaseInterpreter); }).Wait(); createVenv.ClickButtonByAutomationId("Create"); createVenv.ClickButtonAndClose("Close", nameIsAutomationId: true); } var nowRunning = pss.WaitForNewProcess(TimeSpan.FromMinutes(1)); if (nowRunning == null || !nowRunning.Any()) { Assert.Fail("Failed to see python process start to create virtualenv"); } foreach (var p in nowRunning) { if (p.HasExited) { continue; } try { p.WaitForExit(30000); } catch (Win32Exception ex) { Console.WriteLine("Error waiting for process ID {0}\n{1}", p.Id, ex); } } } try { return OpenSolutionExplorer().WaitForChildOfProject(project, Strings.Environments, envName); } finally { var text = GetOutputWindowText("General"); if (!string.IsNullOrEmpty(text)) { Console.WriteLine("** Output Window text"); Console.WriteLine(text); Console.WriteLine("***"); Console.WriteLine(); } } } public TreeNode AddExistingVirtualEnvironment(EnvDTE.Project project, string envPath, out string envName) { var environmentsNode = OpenSolutionExplorer().FindChildOfProject(project, Strings.Environments); environmentsNode.Select(); using (var createVenv = AutomationDialog.FromDte(this, "Python.AddVirtualEnvironment")) { new TextBox(createVenv.FindByAutomationId("VirtualEnvPath")).SetValue(envPath); var baseInterp = new ComboBox(createVenv.FindByAutomationId("BaseInterpreter")).GetSelectedItemName(); envName = string.Format("{0} ({1})", Path.GetFileName(envPath), baseInterp); Console.WriteLine("Expecting environment named: {0}", envName); createVenv.ClickButtonAndClose("Add", nameIsAutomationId: true); } return OpenSolutionExplorer().WaitForChildOfProject(project, Strings.Environments, envName); } public IPythonOptions Options { get { return (IPythonOptions)Dte.GetObject("VsPython"); } } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace Revit.SDK.Samples.BeamAndSlabNewParameter.CS { /// <summary> /// User Interface. /// </summary> public class BeamAndSlabParametersForm : System.Windows.Forms.Form { private System.Windows.Forms.Button addParameterButton; private System.Windows.Forms.Button displayValueButton; private System.Windows.Forms.Button exitButton; private System.Windows.Forms.ListBox attributeValueListBox; private System.Windows.Forms.Label attributeValueLabel; private Button findButton; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; /// <summary> /// constructor /// </summary> /// <param name="dataBuffer"></param> public BeamAndSlabParametersForm(Command dataBuffer) { InitializeComponent(); m_dataBuffer = dataBuffer; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.addParameterButton = new System.Windows.Forms.Button(); this.displayValueButton = new System.Windows.Forms.Button(); this.exitButton = new System.Windows.Forms.Button(); this.attributeValueListBox = new System.Windows.Forms.ListBox(); this.attributeValueLabel = new System.Windows.Forms.Label(); this.findButton = new System.Windows.Forms.Button(); this.SuspendLayout(); // // addParameterButton // this.addParameterButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.addParameterButton.Location = new System.Drawing.Point(311, 65); this.addParameterButton.Name = "addParameterButton"; this.addParameterButton.Size = new System.Drawing.Size(105, 26); this.addParameterButton.TabIndex = 1; this.addParameterButton.Text = "&Add"; this.addParameterButton.TextAlign = System.Drawing.ContentAlignment.TopCenter; this.addParameterButton.Click += new System.EventHandler(this.addParameterButton_Click); // // displayValueButton // this.displayValueButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.displayValueButton.Location = new System.Drawing.Point(311, 111); this.displayValueButton.Name = "displayValueButton"; this.displayValueButton.Size = new System.Drawing.Size(105, 26); this.displayValueButton.TabIndex = 2; this.displayValueButton.Text = "&Display Value"; this.displayValueButton.Click += new System.EventHandler(this.displayValueButton_Click); // // exitButton // this.exitButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.exitButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.exitButton.Location = new System.Drawing.Point(311, 203); this.exitButton.Name = "exitButton"; this.exitButton.Size = new System.Drawing.Size(105, 26); this.exitButton.TabIndex = 4; this.exitButton.Text = "&Exit"; this.exitButton.Click += new System.EventHandler(this.exitButton_Click); // // attributeValueListBox // this.attributeValueListBox.ItemHeight = 16; this.attributeValueListBox.Location = new System.Drawing.Point(19, 46); this.attributeValueListBox.Name = "attributeValueListBox"; this.attributeValueListBox.Size = new System.Drawing.Size(269, 228); this.attributeValueListBox.TabIndex = 18; this.attributeValueListBox.TabStop = false; // // attributeValueLabel // this.attributeValueLabel.Location = new System.Drawing.Point(19, 9); this.attributeValueLabel.Name = "attributeValueLabel"; this.attributeValueLabel.Size = new System.Drawing.Size(279, 37); this.attributeValueLabel.TabIndex = 19; this.attributeValueLabel.Text = "Display the value of the Unique ID if present for all the selected elements"; // // findButton // this.findButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.findButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.findButton.Location = new System.Drawing.Point(311, 157); this.findButton.Name = "findButton"; this.findButton.Size = new System.Drawing.Size(105, 26); this.findButton.TabIndex = 3; this.findButton.Text = "&Find"; this.findButton.Click += new System.EventHandler(this.findButton_Click); // // BeamAndSlabParametersForm // this.CancelButton = this.exitButton; this.ClientSize = new System.Drawing.Size(438, 292); this.Controls.Add(this.attributeValueLabel); this.Controls.Add(this.attributeValueListBox); this.Controls.Add(this.addParameterButton); this.Controls.Add(this.findButton); this.Controls.Add(this.displayValueButton); this.Controls.Add(this.exitButton); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "BeamAndSlabParametersForm"; this.ShowInTaskbar = false; this.Text = "Beam and Slab New Parameters"; this.ResumeLayout(false); } #endregion // an instance of Command class Command m_dataBuffer = null; /// <summary> /// Call SetNewParameterToBeamsAndSlabs function /// which is belongs to BeamAndSlabParameters class /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void addParameterButton_Click(object sender, System.EventArgs e) { bool successAddParameter = m_dataBuffer.SetNewParameterToBeamsAndSlabs(); if (successAddParameter) { this.DialogResult = DialogResult.OK; m_dataBuffer.SetValueToUniqueIDParameter(); MessageBox.Show("Done"); } else { this.DialogResult = DialogResult.None; m_dataBuffer.SetValueToUniqueIDParameter(); MessageBox.Show("Unique ID parameter exist"); } } /// <summary> /// Call SetValueToUniqueIDParameter function /// which is belongs to BeamAndSlabNewParameters class /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void findButton_Click(object sender, System.EventArgs e) { if (null != attributeValueListBox.SelectedItem) { m_dataBuffer.FindElement(attributeValueListBox.SelectedItem.ToString()); } } /// <summary> /// Call SendValueToListBox function which is belongs to BeamAndSlabNewParameters class /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void displayValueButton_Click(object sender, System.EventArgs e) { attributeValueListBox.DataSource = m_dataBuffer.SendValueToListBox(); //If we displayed nothing, give possible reasons if (0 == attributeValueListBox.Items.Count) { string message = ""; message = "There was an error executing the command.\r\n"; message = message + "Possible reasons for this are:\r\n\r\n"; message = message + "1. No parameter was added.\r\n"; message = message + "2. No beam or slab was selected.\r\n"; message = message + "3. The value was blank.\r\n"; MessageBox.Show(message); } } /// <summary> /// Close this form /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void exitButton_Click(object sender, System.EventArgs e) { this.Close(); } } }
// 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 MS.Utility; using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Windows; using System.Diagnostics; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace MS.Internal.Ink { /// <summary> /// A stream-style reader for retrieving packed bits from a byte array /// </summary> /// <remarks>This bits should packed into the leftmost position in each byte. /// For compatibility purposes with the v1 ISF encoder and decoder, the order of the /// packing must not be changed. This code is a from-scratch rewrite of the BitStream /// natice C++ class in the v1 Ink code, but still maintaining the same packing /// behavior.</remarks> internal class BitStreamReader { /// <summary> /// Create a new BitStreamReader to unpack the bits in a buffer of bytes /// </summary> /// <param name="buffer">Buffer of bytes</param> internal BitStreamReader(byte[] buffer) { Debug.Assert(buffer != null); _byteArray = buffer; _bufferLengthInBits = (uint)buffer.Length * (uint)Native.BitsPerByte; } /// <summary> /// Create a new BitStreamReader to unpack the bits in a buffer of bytes /// </summary> /// <param name="buffer">Buffer of bytes</param> /// <param name="startIndex">The index to start reading at</param> internal BitStreamReader(byte[] buffer, int startIndex) { Debug.Assert(buffer != null); if (startIndex < 0 || startIndex >= buffer.Length) { throw new ArgumentOutOfRangeException("startIndex"); } _byteArray = buffer; _byteArrayIndex = startIndex; _bufferLengthInBits = (uint)(buffer.Length - startIndex) * (uint)Native.BitsPerByte; } /// <summary> /// Create a new BitStreamReader to unpack the bits in a buffer of bytes /// and enforce a maximum buffer read length /// </summary> /// <param name="buffer">Buffer of bytes</param> /// <param name="bufferLengthInBits">Maximum number of bytes to read from the buffer</param> internal BitStreamReader(byte[] buffer, uint bufferLengthInBits) : this(buffer) { if (bufferLengthInBits > (buffer.Length * Native.BitsPerByte)) { throw new ArgumentOutOfRangeException("bufferLengthInBits", SR.Get(SRID.InvalidBufferLength)); } _bufferLengthInBits = bufferLengthInBits; } /// <summary> /// Read a specified number of bits from the stream into a long /// </summary> internal long ReadUInt64(int countOfBits) { // we only support 1-64 bits currently, not multiple bytes, and not 0 bits if (countOfBits > Native.BitsPerLong || countOfBits <= 0) { throw new ArgumentOutOfRangeException("countOfBits", countOfBits, SR.Get(SRID.CountOfBitsOutOfRange)); } long retVal = 0; while (countOfBits > 0) { int countToRead = (int)Native.BitsPerByte; if (countOfBits < 8) { countToRead = countOfBits; } //make room retVal <<= countToRead; byte b = ReadByte(countToRead); retVal |= (long)b; countOfBits -= countToRead; } return retVal; } /// <summary> /// Read a single UInt16 from the byte[] /// </summary> /// <param name="countOfBits"></param> /// <returns></returns> internal ushort ReadUInt16(int countOfBits) { // we only support 1-16 bits currently, not multiple bytes, and not 0 bits if (countOfBits > Native.BitsPerShort || countOfBits <= 0) { throw new ArgumentOutOfRangeException("countOfBits", countOfBits, SR.Get(SRID.CountOfBitsOutOfRange)); } ushort retVal = 0; while (countOfBits > 0) { int countToRead = (int)Native.BitsPerByte; if (countOfBits < 8) { countToRead = countOfBits; } //make room retVal <<= countToRead; byte b = ReadByte(countToRead); retVal |= (ushort)b; countOfBits -= countToRead; } return retVal; } /// <summary> /// Read a specified number of bits from the stream in reverse byte order /// </summary> internal uint ReadUInt16Reverse(int countOfBits) { // we only support 1-8 bits currently, not multiple bytes, and not 0 bits if (countOfBits > Native.BitsPerShort|| countOfBits <= 0) { throw new ArgumentOutOfRangeException("countOfBits", countOfBits, SR.Get(SRID.CountOfBitsOutOfRange)); } ushort retVal = 0; int fullBytesRead = 0; while (countOfBits > 0) { int countToRead = (int)Native.BitsPerByte; if (countOfBits < 8) { countToRead = countOfBits; } //make room ushort b = (ushort)ReadByte(countToRead); b <<= (fullBytesRead * Native.BitsPerByte); retVal |= b; fullBytesRead++; countOfBits -= countToRead; } return retVal; } /// <summary> /// Read a specified number of bits from the stream into a single byte /// </summary> internal uint ReadUInt32(int countOfBits) { // we only support 1-8 bits currently, not multiple bytes, and not 0 bits if (countOfBits > Native.BitsPerInt || countOfBits <= 0) { throw new ArgumentOutOfRangeException("countOfBits", countOfBits, SR.Get(SRID.CountOfBitsOutOfRange)); } uint retVal = 0; while (countOfBits > 0) { int countToRead = (int)Native.BitsPerByte; if (countOfBits < 8) { countToRead = countOfBits; } //make room retVal <<= countToRead; byte b = ReadByte(countToRead); retVal |= (uint)b; countOfBits -= countToRead; } return retVal; } /// <summary> /// Read a specified number of bits from the stream in reverse byte order /// </summary> internal uint ReadUInt32Reverse(int countOfBits) { // we only support 1-8 bits currently, not multiple bytes, and not 0 bits if (countOfBits > Native.BitsPerInt || countOfBits <= 0) { throw new ArgumentOutOfRangeException("countOfBits", countOfBits, SR.Get(SRID.CountOfBitsOutOfRange)); } uint retVal = 0; int fullBytesRead = 0; while (countOfBits > 0) { int countToRead = (int)Native.BitsPerByte; if (countOfBits < 8) { countToRead = countOfBits; } //make room uint b = (uint)ReadByte(countToRead); b <<= (fullBytesRead * Native.BitsPerByte); retVal |= b; fullBytesRead++; countOfBits -= countToRead; } return retVal; } /// <summary> /// Reads a single bit from the buffer /// </summary> /// <returns></returns> internal bool ReadBit() { byte b = ReadByte(1); return ((b & 1) == 1); } /// <summary> /// Read a specified number of bits from the stream into a single byte /// </summary> /// <param name="countOfBits">The number of bits to unpack</param> /// <returns>A single byte that contains up to 8 packed bits</returns> /// <remarks>For example, if 2 bits are read from the stream, then a full byte /// will be created with the least significant bits set to the 2 unpacked bits /// from the stream</remarks> internal byte ReadByte(int countOfBits) { // if the end of the stream has been reached, then throw an exception if (EndOfStream) { throw new System.IO.EndOfStreamException(SR.Get(SRID.EndOfStreamReached)); } // we only support 1-8 bits currently, not multiple bytes, and not 0 bits if (countOfBits > Native.BitsPerByte || countOfBits <= 0) { throw new ArgumentOutOfRangeException("countOfBits", countOfBits, SR.Get(SRID.CountOfBitsOutOfRange)); } if (countOfBits > _bufferLengthInBits) { throw new ArgumentOutOfRangeException("countOfBits", countOfBits, SR.Get(SRID.CountOfBitsGreatThanRemainingBits)); } _bufferLengthInBits -= (uint)countOfBits; // initialize return byte to 0 before reading from the cache byte returnByte = 0; // if the partial bit cache contains more bits than requested, then read the // cache only if (_cbitsInPartialByte >= countOfBits) { // retrieve the requested count of most significant bits from the cache // and store them in the least significant positions in the return byte int rightShiftPartialByteBy = Native.BitsPerByte - countOfBits; returnByte = (byte)(_partialByte >> rightShiftPartialByteBy); // reposition any unused portion of the cache in the most significant part of the bit cache unchecked // disable overflow checking since we are intentionally throwing away // the significant bits { _partialByte <<= countOfBits; } // update the bit count in the cache _cbitsInPartialByte -= countOfBits; } // otherwise, we need to retrieve more full bytes from the stream else { // retrieve the next full byte from the stream byte nextByte = _byteArray[_byteArrayIndex]; _byteArrayIndex++; //right shift partial byte to get it ready to or with the partial next byte int rightShiftPartialByteBy = Native.BitsPerByte - countOfBits; returnByte = (byte)(_partialByte >> rightShiftPartialByteBy); // now copy the remaining chunk of the newly retrieved full byte int rightShiftNextByteBy = Math.Abs((countOfBits - _cbitsInPartialByte) - Native.BitsPerByte); returnByte |= (byte)(nextByte >> rightShiftNextByteBy); // update the partial bit cache with the remainder of the newly retrieved full byte unchecked // disable overflow checking since we are intentionally throwing away // the significant bits { _partialByte = (byte)(nextByte << (countOfBits - _cbitsInPartialByte)); } _cbitsInPartialByte = Native.BitsPerByte - (countOfBits - _cbitsInPartialByte); } return returnByte; } /// <summary> /// Since the return value of Read cannot distinguish between valid and invalid /// data (e.g. 8 bits set), the EndOfStream property detects when there is no more /// data to read. /// </summary> /// <value>True if stream end has been reached</value> internal bool EndOfStream { get { return 0 == _bufferLengthInBits; } } /// <summary> /// The current read index in the array /// </summary> internal int CurrentIndex { get { //_byteArrayIndex is always advanced to the next index // so we always decrement before returning return _byteArrayIndex - 1; } } // Privates // reference to the source byte buffer to read from private byte[] _byteArray = null; // maximum length of buffer to read in bits private uint _bufferLengthInBits = 0; // the index in the source buffer for the next byte to be read private int _byteArrayIndex = 0; // since the bits from multiple inputs can be packed into a single byte // (e.g. 2 bits per input fits 4 per byte), we use this field as a cache // of the remaining partial bits. private byte _partialByte = 0; // the number of bits (partial byte) left to read in the overlapped byte field private int _cbitsInPartialByte = 0; } /// <summary> /// A stream-like writer for packing bits into a byte buffer /// </summary> /// <remarks>This class is to be used with the BitStreamReader for reading /// and writing bytes. Note that the bytes should be read in the same order /// and lengths as they were written to retrieve the same values. /// See remarks in BitStreamReader regarding compatibility with the native C++ /// BitStream class.</remarks> internal class BitStreamWriter { /// <summary> /// Create a new bit writer that writes to the target buffer /// </summary> /// <param name="bufferToWriteTo"></param> internal BitStreamWriter(List<byte> bufferToWriteTo) { if (bufferToWriteTo == null) { throw new ArgumentNullException("bufferToWriteTo"); } _targetBuffer = bufferToWriteTo; } /// <summary> /// Writes the count of bits from the int to the left packed buffer /// </summary> /// <param name="bits"></param> /// <param name="countOfBits"></param> internal void Write(uint bits, int countOfBits) { // validate that a subset of the bits in a single byte are being written if (countOfBits <= 0 || countOfBits > Native.BitsPerInt) throw new ArgumentOutOfRangeException("countOfBits", countOfBits, SR.Get(SRID.CountOfBitsOutOfRange)); // calculate the number of full bytes // Example: 10 bits would require 1 full byte int fullBytes = countOfBits / Native.BitsPerByte; // calculate the number of bits that spill beyond the full byte boundary // Example: 10 buttons would require 2 extra bits (8 fit in a full byte) int bitsToWrite = countOfBits % Native.BitsPerByte; for (; fullBytes >= 0; fullBytes--) { byte byteOfData = (byte)(bits >> (fullBytes * Native.BitsPerByte)); // // write 8 or less bytes to the bitwriter // checking for 0 handles the case where we're writing 8, 16 or 24 bytes // and bitsToWrite is initialize to zero // if (bitsToWrite > 0) { Write(byteOfData, bitsToWrite); } if (fullBytes > 0) { bitsToWrite = Native.BitsPerByte; } } } /// <summary> /// Writes the count of bits from the int to the buffer in reverse order /// </summary> /// <param name="bits"></param> /// <param name="countOfBits"></param> internal void WriteReverse(uint bits, int countOfBits) { // validate that a subset of the bits in a single byte are being written if (countOfBits <= 0 || countOfBits > Native.BitsPerInt) throw new ArgumentOutOfRangeException("countOfBits", countOfBits, SR.Get(SRID.CountOfBitsOutOfRange)); // calculate the number of full bytes // Example: 10 bits would require 1 full byte int fullBytes = countOfBits / Native.BitsPerByte; // calculate the number of bits that spill beyond the full byte boundary // Example: 10 buttons would require 2 extra bits (8 fit in a full byte) int bitsToWrite = countOfBits % Native.BitsPerByte; if (bitsToWrite > 0) { fullBytes++; } for (int x = 0; x < fullBytes; x++) { byte byteOfData = (byte)(bits >> (x * Native.BitsPerByte)); Write(byteOfData, Native.BitsPerByte); } } /// <summary> /// Write a specific number of bits from byte input into the stream /// </summary> /// <param name="bits">The byte to read the bits from</param> /// <param name="countOfBits">The number of bits to read</param> internal void Write(byte bits, int countOfBits) { // validate that a subset of the bits in a single byte are being written if (countOfBits <= 0 || countOfBits > Native.BitsPerByte) throw new ArgumentOutOfRangeException("countOfBits", countOfBits, SR.Get(SRID.CountOfBitsOutOfRange)); byte buffer; // if there is remaining bits in the last byte in the stream // then use those first if (_remaining > 0) { // retrieve the last byte from the stream, update it, and then replace it buffer = _targetBuffer[_targetBuffer.Count - 1]; // if the remaining bits aren't enough then just copy the significant bits // of the input into the remainder if (countOfBits > _remaining) { buffer |= (byte)((bits & (0xFF >> (Native.BitsPerByte - countOfBits))) >> (countOfBits - _remaining)); } // otherwise, copy the entire set of input bits into the remainder else { buffer |= (byte)((bits & (0xFF >> (Native.BitsPerByte - countOfBits))) << (_remaining - countOfBits)); } _targetBuffer[_targetBuffer.Count - 1] = buffer; } // if the remainder wasn't large enough to hold the entire input set if (countOfBits > _remaining) { // then copy the uncontained portion of the input set into a temporary byte _remaining = Native.BitsPerByte - (countOfBits - _remaining); unchecked // disable overflow checking since we are intentionally throwing away // the significant bits { buffer = (byte)(bits << _remaining); } // and add it to the target buffer _targetBuffer.Add(buffer); } else { // otherwise, simply update the amount of remaining bits we have to spare _remaining -= countOfBits; } } // the buffer that the bits are written into private List<byte> _targetBuffer = null; // number of free bits remaining in the last byte added to the target buffer private int _remaining = 0; } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Data; using System.Reflection; using log4net; #if CSharpSqlite using Community.CsharpSqlite.Sqlite; #else using Mono.Data.Sqlite; #endif using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Data.SQLite { public class SQLiteUserProfilesData: IProfilesData { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private SqliteConnection m_connection; private string m_connectionString; private Dictionary<string, FieldInfo> m_FieldMap = new Dictionary<string, FieldInfo>(); protected virtual Assembly Assembly { get { return GetType().Assembly; } } public SQLiteUserProfilesData() { } public SQLiteUserProfilesData(string connectionString) { Initialise(connectionString); } public void Initialise(string connectionString) { if (Util.IsWindows()) Util.LoadArchSpecificWindowsDll("sqlite3.dll"); m_connectionString = connectionString; m_log.Info("[PROFILES_DATA]: Sqlite - connecting: "+m_connectionString); m_connection = new SqliteConnection(m_connectionString); m_connection.Open(); Migration m = new Migration(m_connection, Assembly, "UserProfiles"); m.Update(); } private string[] FieldList { get { return new List<string>(m_FieldMap.Keys).ToArray(); } } #region IProfilesData implementation public OSDArray GetClassifiedRecords(UUID creatorId) { OSDArray data = new OSDArray(); string query = "SELECT classifieduuid, name FROM classifieds WHERE creatoruuid = :Id"; IDataReader reader = null; using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":Id", creatorId); reader = cmd.ExecuteReader(); } while (reader.Read()) { OSDMap n = new OSDMap(); UUID Id = UUID.Zero; string Name = null; try { UUID.TryParse(Convert.ToString( reader["classifieduuid"]), out Id); Name = Convert.ToString(reader["name"]); } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": UserAccount exception {0}", e.Message); } n.Add("classifieduuid", OSD.FromUUID(Id)); n.Add("name", OSD.FromString(Name)); data.Add(n); } reader.Close(); return data; } public bool UpdateClassifiedRecord(UserClassifiedAdd ad, ref string result) { string query = string.Empty; query += "INSERT OR REPLACE INTO classifieds ("; query += "`classifieduuid`,"; query += "`creatoruuid`,"; query += "`creationdate`,"; query += "`expirationdate`,"; query += "`category`,"; query += "`name`,"; query += "`description`,"; query += "`parceluuid`,"; query += "`parentestate`,"; query += "`snapshotuuid`,"; query += "`simname`,"; query += "`posglobal`,"; query += "`parcelname`,"; query += "`classifiedflags`,"; query += "`priceforlisting`) "; query += "VALUES ("; query += ":ClassifiedId,"; query += ":CreatorId,"; query += ":CreatedDate,"; query += ":ExpirationDate,"; query += ":Category,"; query += ":Name,"; query += ":Description,"; query += ":ParcelId,"; query += ":ParentEstate,"; query += ":SnapshotId,"; query += ":SimName,"; query += ":GlobalPos,"; query += ":ParcelName,"; query += ":Flags,"; query += ":ListingPrice ) "; if(string.IsNullOrEmpty(ad.ParcelName)) ad.ParcelName = "Unknown"; if(ad.ParcelId == null) ad.ParcelId = UUID.Zero; if(string.IsNullOrEmpty(ad.Description)) ad.Description = "No Description"; DateTime epoch = new DateTime(1970, 1, 1); DateTime now = DateTime.Now; TimeSpan epochnow = now - epoch; TimeSpan duration; DateTime expiration; TimeSpan epochexp; if(ad.Flags == 2) { duration = new TimeSpan(7,0,0,0); expiration = now.Add(duration); epochexp = expiration - epoch; } else { duration = new TimeSpan(365,0,0,0); expiration = now.Add(duration); epochexp = expiration - epoch; } ad.CreationDate = (int)epochnow.TotalSeconds; ad.ExpirationDate = (int)epochexp.TotalSeconds; try { using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":ClassifiedId", ad.ClassifiedId.ToString()); cmd.Parameters.AddWithValue(":CreatorId", ad.CreatorId.ToString()); cmd.Parameters.AddWithValue(":CreatedDate", ad.CreationDate.ToString()); cmd.Parameters.AddWithValue(":ExpirationDate", ad.ExpirationDate.ToString()); cmd.Parameters.AddWithValue(":Category", ad.Category.ToString()); cmd.Parameters.AddWithValue(":Name", ad.Name.ToString()); cmd.Parameters.AddWithValue(":Description", ad.Description.ToString()); cmd.Parameters.AddWithValue(":ParcelId", ad.ParcelId.ToString()); cmd.Parameters.AddWithValue(":ParentEstate", ad.ParentEstate.ToString()); cmd.Parameters.AddWithValue(":SnapshotId", ad.SnapshotId.ToString ()); cmd.Parameters.AddWithValue(":SimName", ad.SimName.ToString()); cmd.Parameters.AddWithValue(":GlobalPos", ad.GlobalPos.ToString()); cmd.Parameters.AddWithValue(":ParcelName", ad.ParcelName.ToString()); cmd.Parameters.AddWithValue(":Flags", ad.Flags.ToString()); cmd.Parameters.AddWithValue(":ListingPrice", ad.Price.ToString ()); cmd.ExecuteNonQuery(); } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": ClassifiedesUpdate exception {0}", e.Message); result = e.Message; return false; } return true; } public bool DeleteClassifiedRecord(UUID recordId) { string query = string.Empty; query += "DELETE FROM classifieds WHERE "; query += "classifieduuid = :ClasifiedId"; try { using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":ClassifiedId", recordId.ToString()); cmd.ExecuteNonQuery(); } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": DeleteClassifiedRecord exception {0}", e.Message); return false; } return true; } public bool GetClassifiedInfo(ref UserClassifiedAdd ad, ref string result) { IDataReader reader = null; string query = string.Empty; query += "SELECT * FROM classifieds WHERE "; query += "classifieduuid = :AdId"; try { using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":AdId", ad.ClassifiedId.ToString()); using (reader = cmd.ExecuteReader()) { if(reader.Read ()) { ad.CreatorId = new UUID(reader["creatoruuid"].ToString()); ad.ParcelId = new UUID(reader["parceluuid"].ToString ()); ad.SnapshotId = new UUID(reader["snapshotuuid"].ToString ()); ad.CreationDate = Convert.ToInt32(reader["creationdate"]); ad.ExpirationDate = Convert.ToInt32(reader["expirationdate"]); ad.ParentEstate = Convert.ToInt32(reader["parentestate"]); ad.Flags = (byte) Convert.ToUInt32(reader["classifiedflags"]); ad.Category = Convert.ToInt32(reader["category"]); ad.Price = Convert.ToInt16(reader["priceforlisting"]); ad.Name = reader["name"].ToString(); ad.Description = reader["description"].ToString(); ad.SimName = reader["simname"].ToString(); ad.GlobalPos = reader["posglobal"].ToString(); ad.ParcelName = reader["parcelname"].ToString(); } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": GetPickInfo exception {0}", e.Message); } return true; } public OSDArray GetAvatarPicks(UUID avatarId) { IDataReader reader = null; string query = string.Empty; query += "SELECT `pickuuid`,`name` FROM userpicks WHERE "; query += "creatoruuid = :Id"; OSDArray data = new OSDArray(); try { using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":Id", avatarId.ToString()); using (reader = cmd.ExecuteReader()) { while (reader.Read()) { OSDMap record = new OSDMap(); record.Add("pickuuid",OSD.FromString((string)reader["pickuuid"])); record.Add("name",OSD.FromString((string)reader["name"])); data.Add(record); } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": GetAvatarPicks exception {0}", e.Message); } return data; } public UserProfilePick GetPickInfo(UUID avatarId, UUID pickId) { IDataReader reader = null; string query = string.Empty; UserProfilePick pick = new UserProfilePick(); query += "SELECT * FROM userpicks WHERE "; query += "creatoruuid = :CreatorId AND "; query += "pickuuid = :PickId"; try { using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":CreatorId", avatarId.ToString()); cmd.Parameters.AddWithValue(":PickId", pickId.ToString()); using (reader = cmd.ExecuteReader()) { while (reader.Read()) { string description = (string)reader["description"]; if (string.IsNullOrEmpty(description)) description = "No description given."; UUID.TryParse((string)reader["pickuuid"], out pick.PickId); UUID.TryParse((string)reader["creatoruuid"], out pick.CreatorId); UUID.TryParse((string)reader["parceluuid"], out pick.ParcelId); UUID.TryParse((string)reader["snapshotuuid"], out pick.SnapshotId); pick.GlobalPos = (string)reader["posglobal"]; bool.TryParse((string)reader["toppick"].ToString(), out pick.TopPick); bool.TryParse((string)reader["enabled"].ToString(), out pick.Enabled); pick.Name = (string)reader["name"]; pick.Desc = description; pick.User = (string)reader["user"]; pick.OriginalName = (string)reader["originalname"]; pick.SimName = (string)reader["simname"]; pick.SortOrder = (int)reader["sortorder"]; } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": GetPickInfo exception {0}", e.Message); } return pick; } public bool UpdatePicksRecord(UserProfilePick pick) { string query = string.Empty; query += "INSERT OR REPLACE INTO userpicks ("; query += "pickuuid, "; query += "creatoruuid, "; query += "toppick, "; query += "parceluuid, "; query += "name, "; query += "description, "; query += "snapshotuuid, "; query += "user, "; query += "originalname, "; query += "simname, "; query += "posglobal, "; query += "sortorder, "; query += "enabled ) "; query += "VALUES ("; query += ":PickId,"; query += ":CreatorId,"; query += ":TopPick,"; query += ":ParcelId,"; query += ":Name,"; query += ":Desc,"; query += ":SnapshotId,"; query += ":User,"; query += ":Original,"; query += ":SimName,"; query += ":GlobalPos,"; query += ":SortOrder,"; query += ":Enabled) "; try { using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { int top_pick; int.TryParse(pick.TopPick.ToString(), out top_pick); int enabled; int.TryParse(pick.Enabled.ToString(), out enabled); cmd.CommandText = query; cmd.Parameters.AddWithValue(":PickId", pick.PickId.ToString()); cmd.Parameters.AddWithValue(":CreatorId", pick.CreatorId.ToString()); cmd.Parameters.AddWithValue(":TopPick", top_pick); cmd.Parameters.AddWithValue(":ParcelId", pick.ParcelId.ToString()); cmd.Parameters.AddWithValue(":Name", pick.Name.ToString()); cmd.Parameters.AddWithValue(":Desc", pick.Desc.ToString()); cmd.Parameters.AddWithValue(":SnapshotId", pick.SnapshotId.ToString()); cmd.Parameters.AddWithValue(":User", pick.User.ToString()); cmd.Parameters.AddWithValue(":Original", pick.OriginalName.ToString()); cmd.Parameters.AddWithValue(":SimName",pick.SimName.ToString()); cmd.Parameters.AddWithValue(":GlobalPos", pick.GlobalPos); cmd.Parameters.AddWithValue(":SortOrder", pick.SortOrder.ToString ()); cmd.Parameters.AddWithValue(":Enabled", enabled); cmd.ExecuteNonQuery(); } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": UpdateAvatarNotes exception {0}", e.Message); return false; } return true; } public bool DeletePicksRecord(UUID pickId) { string query = string.Empty; query += "DELETE FROM userpicks WHERE "; query += "pickuuid = :PickId"; try { using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":PickId", pickId.ToString()); cmd.ExecuteNonQuery(); } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": DeleteUserPickRecord exception {0}", e.Message); return false; } return true; } public bool GetAvatarNotes(ref UserProfileNotes notes) { IDataReader reader = null; string query = string.Empty; query += "SELECT `notes` FROM usernotes WHERE "; query += "useruuid = :Id AND "; query += "targetuuid = :TargetId"; OSDArray data = new OSDArray(); try { using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":Id", notes.UserId.ToString()); cmd.Parameters.AddWithValue(":TargetId", notes.TargetId.ToString()); using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { while (reader.Read()) { notes.Notes = OSD.FromString((string)reader["notes"]); } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": GetAvatarNotes exception {0}", e.Message); } return true; } public bool UpdateAvatarNotes(ref UserProfileNotes note, ref string result) { string query = string.Empty; bool remove; if(string.IsNullOrEmpty(note.Notes)) { remove = true; query += "DELETE FROM usernotes WHERE "; query += "useruuid=:UserId AND "; query += "targetuuid=:TargetId"; } else { remove = false; query += "INSERT OR REPLACE INTO usernotes VALUES ( "; query += ":UserId,"; query += ":TargetId,"; query += ":Notes )"; } try { using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; if(!remove) cmd.Parameters.AddWithValue(":Notes", note.Notes); cmd.Parameters.AddWithValue(":TargetId", note.TargetId.ToString ()); cmd.Parameters.AddWithValue(":UserId", note.UserId.ToString()); cmd.ExecuteNonQuery(); } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": UpdateAvatarNotes exception {0}", e.Message); return false; } return true; } public bool GetAvatarProperties(ref UserProfileProperties props, ref string result) { IDataReader reader = null; string query = string.Empty; query += "SELECT * FROM userprofile WHERE "; query += "useruuid = :Id"; using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":Id", props.UserId.ToString()); try { reader = cmd.ExecuteReader(); } catch(Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": GetAvatarProperties exception {0}", e.Message); result = e.Message; return false; } if(reader != null && reader.Read()) { props.WebUrl = (string)reader["profileURL"]; UUID.TryParse((string)reader["profileImage"], out props.ImageId); props.AboutText = (string)reader["profileAboutText"]; UUID.TryParse((string)reader["profileFirstImage"], out props.FirstLifeImageId); props.FirstLifeText = (string)reader["profileFirstText"]; UUID.TryParse((string)reader["profilePartner"], out props.PartnerId); props.WantToMask = (int)reader["profileWantToMask"]; props.WantToText = (string)reader["profileWantToText"]; props.SkillsMask = (int)reader["profileSkillsMask"]; props.SkillsText = (string)reader["profileSkillsText"]; props.Language = (string)reader["profileLanguages"]; } else { props.WebUrl = string.Empty; props.ImageId = UUID.Zero; props.AboutText = string.Empty; props.FirstLifeImageId = UUID.Zero; props.FirstLifeText = string.Empty; props.PartnerId = UUID.Zero; props.WantToMask = 0; props.WantToText = string.Empty; props.SkillsMask = 0; props.SkillsText = string.Empty; props.Language = string.Empty; props.PublishProfile = false; props.PublishMature = false; query = "INSERT INTO userprofile ("; query += "useruuid, "; query += "profilePartner, "; query += "profileAllowPublish, "; query += "profileMaturePublish, "; query += "profileURL, "; query += "profileWantToMask, "; query += "profileWantToText, "; query += "profileSkillsMask, "; query += "profileSkillsText, "; query += "profileLanguages, "; query += "profileImage, "; query += "profileAboutText, "; query += "profileFirstImage, "; query += "profileFirstText) VALUES ("; query += ":userId, "; query += ":profilePartner, "; query += ":profileAllowPublish, "; query += ":profileMaturePublish, "; query += ":profileURL, "; query += ":profileWantToMask, "; query += ":profileWantToText, "; query += ":profileSkillsMask, "; query += ":profileSkillsText, "; query += ":profileLanguages, "; query += ":profileImage, "; query += ":profileAboutText, "; query += ":profileFirstImage, "; query += ":profileFirstText)"; using (SqliteCommand put = (SqliteCommand)m_connection.CreateCommand()) { put.CommandText = query; put.Parameters.AddWithValue(":userId", props.UserId.ToString()); put.Parameters.AddWithValue(":profilePartner", props.PartnerId.ToString()); put.Parameters.AddWithValue(":profileAllowPublish", props.PublishProfile); put.Parameters.AddWithValue(":profileMaturePublish", props.PublishMature); put.Parameters.AddWithValue(":profileURL", props.WebUrl); put.Parameters.AddWithValue(":profileWantToMask", props.WantToMask); put.Parameters.AddWithValue(":profileWantToText", props.WantToText); put.Parameters.AddWithValue(":profileSkillsMask", props.SkillsMask); put.Parameters.AddWithValue(":profileSkillsText", props.SkillsText); put.Parameters.AddWithValue(":profileLanguages", props.Language); put.Parameters.AddWithValue(":profileImage", props.ImageId.ToString()); put.Parameters.AddWithValue(":profileAboutText", props.AboutText); put.Parameters.AddWithValue(":profileFirstImage", props.FirstLifeImageId.ToString()); put.Parameters.AddWithValue(":profileFirstText", props.FirstLifeText); put.ExecuteNonQuery(); } } } return true; } public bool UpdateAvatarProperties(ref UserProfileProperties props, ref string result) { string query = string.Empty; query += "UPDATE userprofile SET "; query += "profileURL=:profileURL, "; query += "profileImage=:image, "; query += "profileAboutText=:abouttext,"; query += "profileFirstImage=:firstlifeimage,"; query += "profileFirstText=:firstlifetext "; query += "WHERE useruuid=:uuid"; try { using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":profileURL", props.WebUrl); cmd.Parameters.AddWithValue(":image", props.ImageId.ToString()); cmd.Parameters.AddWithValue(":abouttext", props.AboutText); cmd.Parameters.AddWithValue(":firstlifeimage", props.FirstLifeImageId.ToString()); cmd.Parameters.AddWithValue(":firstlifetext", props.FirstLifeText); cmd.Parameters.AddWithValue(":uuid", props.UserId.ToString()); cmd.ExecuteNonQuery(); } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": AgentPropertiesUpdate exception {0}", e.Message); return false; } return true; } public bool UpdateAvatarInterests(UserProfileProperties up, ref string result) { string query = string.Empty; query += "UPDATE userprofile SET "; query += "profileWantToMask=:WantMask, "; query += "profileWantToText=:WantText,"; query += "profileSkillsMask=:SkillsMask,"; query += "profileSkillsText=:SkillsText, "; query += "profileLanguages=:Languages "; query += "WHERE useruuid=:uuid"; try { using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":WantMask", up.WantToMask); cmd.Parameters.AddWithValue(":WantText", up.WantToText); cmd.Parameters.AddWithValue(":SkillsMask", up.SkillsMask); cmd.Parameters.AddWithValue(":SkillsText", up.SkillsText); cmd.Parameters.AddWithValue(":Languages", up.Language); cmd.Parameters.AddWithValue(":uuid", up.UserId.ToString()); cmd.ExecuteNonQuery(); } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": AgentInterestsUpdate exception {0}", e.Message); result = e.Message; return false; } return true; } public bool UpdateUserPreferences(ref UserPreferences pref, ref string result) { string query = string.Empty; query += "UPDATE usersettings SET "; query += "imviaemail=:ImViaEmail, "; query += "visible=:Visible "; query += "WHERE useruuid=:uuid"; try { using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":ImViaEmail", pref.IMViaEmail); cmd.Parameters.AddWithValue(":Visible", pref.Visible); cmd.Parameters.AddWithValue(":uuid", pref.UserId.ToString()); cmd.ExecuteNonQuery(); } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": AgentInterestsUpdate exception {0}", e.Message); result = e.Message; return false; } return true; } public bool GetUserPreferences(ref UserPreferences pref, ref string result) { IDataReader reader = null; string query = string.Empty; query += "SELECT imviaemail,visible,email FROM "; query += "usersettings WHERE "; query += "useruuid = :Id"; OSDArray data = new OSDArray(); try { using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue("?Id", pref.UserId.ToString()); using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.Read()) { bool.TryParse((string)reader["imviaemail"], out pref.IMViaEmail); bool.TryParse((string)reader["visible"], out pref.Visible); pref.EMail = (string)reader["email"]; } else { query = "INSERT INTO usersettings VALUES "; query += "(:Id,'false','false', :Email)"; using (SqliteCommand put = (SqliteCommand)m_connection.CreateCommand()) { put.Parameters.AddWithValue(":Id", pref.UserId.ToString()); put.Parameters.AddWithValue(":Email", pref.EMail); put.ExecuteNonQuery(); } } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": Get preferences exception {0}", e.Message); result = e.Message; return false; } return true; } public bool GetUserAppData(ref UserAppData props, ref string result) { IDataReader reader = null; string query = string.Empty; query += "SELECT * FROM `userdata` WHERE "; query += "UserId = :Id AND "; query += "TagId = :TagId"; try { using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":Id", props.UserId.ToString()); cmd.Parameters.AddWithValue (":TagId", props.TagId.ToString()); using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.Read()) { props.DataKey = (string)reader["DataKey"]; props.DataVal = (string)reader["DataVal"]; } else { query += "INSERT INTO userdata VALUES ( "; query += ":UserId,"; query += ":TagId,"; query += ":DataKey,"; query += ":DataVal) "; using (SqliteCommand put = (SqliteCommand)m_connection.CreateCommand()) { put.Parameters.AddWithValue(":Id", props.UserId.ToString()); put.Parameters.AddWithValue(":TagId", props.TagId.ToString()); put.Parameters.AddWithValue(":DataKey", props.DataKey.ToString()); put.Parameters.AddWithValue(":DataVal", props.DataVal.ToString()); put.ExecuteNonQuery(); } } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": Requst application data exception {0}", e.Message); result = e.Message; return false; } return true; } public bool SetUserAppData(UserAppData props, ref string result) { string query = string.Empty; query += "UPDATE userdata SET "; query += "TagId = :TagId, "; query += "DataKey = :DataKey, "; query += "DataVal = :DataVal WHERE "; query += "UserId = :UserId AND "; query += "TagId = :TagId"; try { using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":UserId", props.UserId.ToString()); cmd.Parameters.AddWithValue(":TagId", props.TagId.ToString ()); cmd.Parameters.AddWithValue(":DataKey", props.DataKey.ToString ()); cmd.Parameters.AddWithValue(":DataVal", props.DataKey.ToString ()); cmd.ExecuteNonQuery(); } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": SetUserData exception {0}", e.Message); return false; } return true; } public OSDArray GetUserImageAssets(UUID avatarId) { IDataReader reader = null; OSDArray data = new OSDArray(); string query = "SELECT `snapshotuuid` FROM {0} WHERE `creatoruuid` = :Id"; // Get classified image assets try { using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":Id", avatarId.ToString()); using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { while(reader.Read()) { data.Add(new OSDString((string)reader["snapshotuuid"].ToString())); } } } using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":Id", avatarId.ToString()); using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.Read()) { data.Add(new OSDString((string)reader["snapshotuuid"].ToString ())); } } } query = "SELECT `profileImage`, `profileFirstImage` FROM `userprofile` WHERE `useruuid` = :Id"; using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":Id", avatarId.ToString()); using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.Read()) { data.Add(new OSDString((string)reader["profileImage"].ToString ())); data.Add(new OSDString((string)reader["profileFirstImage"].ToString ())); } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": GetAvatarNotes exception {0}", e.Message); } return data; } #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.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; namespace MS.Internal.Xml.XPath { internal sealed class SortQuery : Query { private List<SortKey> results; private XPathSortComparer comparer; private Query qyInput; public SortQuery(Query qyInput) { Debug.Assert(qyInput != null, "Sort Query needs an input query tree to work on"); this.results = new List<SortKey>(); this.comparer = new XPathSortComparer(); this.qyInput = qyInput; count = 0; } private SortQuery(SortQuery other) : base(other) { this.results = new List<SortKey>(other.results); this.comparer = other.comparer.Clone(); this.qyInput = Clone(other.qyInput); count = 0; } public override void Reset() { count = 0; } public override void SetXsltContext(XsltContext xsltContext) { qyInput.SetXsltContext(xsltContext); if ( qyInput.StaticType != XPathResultType.NodeSet && qyInput.StaticType != XPathResultType.Any ) { throw XPathException.Create(SR.Xp_NodeSetExpected); } } private void BuildResultsList() { Int32 numSorts = this.comparer.NumSorts; Debug.Assert(numSorts > 0, "Why was the sort query created?"); XPathNavigator eNext; while ((eNext = qyInput.Advance()) != null) { SortKey key = new SortKey(numSorts, /*originalPosition:*/this.results.Count, eNext.Clone()); for (Int32 j = 0; j < numSorts; j++) { key[j] = this.comparer.Expression(j).Evaluate(qyInput); } results.Add(key); } results.Sort(this.comparer); } public override object Evaluate(XPathNodeIterator context) { qyInput.Evaluate(context); this.results.Clear(); BuildResultsList(); count = 0; return this; } public override XPathNavigator Advance() { Debug.Assert(0 <= count && count <= results.Count); if (count < this.results.Count) { return this.results[count++].Node; } return null; } public override XPathNavigator Current { get { Debug.Assert(0 <= count && count <= results.Count); if (count == 0) { return null; } return results[count - 1].Node; } } internal void AddSort(Query evalQuery, IComparer comparer) { this.comparer.AddSort(evalQuery, comparer); } public override XPathNodeIterator Clone() { return new SortQuery(this); } public override XPathResultType StaticType { get { return XPathResultType.NodeSet; } } public override int CurrentPosition { get { return count; } } public override int Count { get { return results.Count; } } public override QueryProps Properties { get { return QueryProps.Cached | QueryProps.Position | QueryProps.Count; } } public override void PrintQuery(XmlWriter w) { w.WriteStartElement(this.GetType().Name); qyInput.PrintQuery(w); w.WriteElementString("XPathSortComparer", "... PrintTree() not implemented ..."); w.WriteEndElement(); } } // class SortQuery internal sealed class SortKey { private Int32 numKeys; private object[] keys; private int originalPosition; private XPathNavigator node; public SortKey(int numKeys, int originalPosition, XPathNavigator node) { this.numKeys = numKeys; this.keys = new object[numKeys]; this.originalPosition = originalPosition; this.node = node; } public object this[int index] { get { return this.keys[index]; } set { this.keys[index] = value; } } public int NumKeys { get { return this.numKeys; } } public int OriginalPosition { get { return this.originalPosition; } } public XPathNavigator Node { get { return this.node; } } } // class SortKey internal sealed class XPathSortComparer : IComparer<SortKey> { private const int minSize = 3; private Query[] expressions; private IComparer[] comparers; private int numSorts; public XPathSortComparer(int size) { if (size <= 0) size = minSize; this.expressions = new Query[size]; this.comparers = new IComparer[size]; } public XPathSortComparer() : this(minSize) { } public void AddSort(Query evalQuery, IComparer comparer) { Debug.Assert(this.expressions.Length == this.comparers.Length); Debug.Assert(0 < this.expressions.Length); Debug.Assert(0 <= numSorts && numSorts <= this.expressions.Length); // Adjust array sizes if needed. if (numSorts == this.expressions.Length) { Query[] newExpressions = new Query[numSorts * 2]; IComparer[] newComparers = new IComparer[numSorts * 2]; for (int i = 0; i < numSorts; i++) { newExpressions[i] = this.expressions[i]; newComparers[i] = this.comparers[i]; } this.expressions = newExpressions; this.comparers = newComparers; } Debug.Assert(numSorts < this.expressions.Length); // Fixup expression to handle node-set return type: if (evalQuery.StaticType == XPathResultType.NodeSet || evalQuery.StaticType == XPathResultType.Any) { evalQuery = new StringFunctions(Function.FunctionType.FuncString, new Query[] { evalQuery }); } this.expressions[numSorts] = evalQuery; this.comparers[numSorts] = comparer; numSorts++; } public int NumSorts { get { return numSorts; } } public Query Expression(int i) { return this.expressions[i]; } int IComparer<SortKey>.Compare(SortKey x, SortKey y) { Debug.Assert(x != null && y != null, "Oops!! what happened?"); int result = 0; for (int i = 0; i < x.NumKeys; i++) { result = this.comparers[i].Compare(x[i], y[i]); if (result != 0) { return result; } } // if after all comparisons, the two sort keys are still equal, preserve the doc order return x.OriginalPosition - y.OriginalPosition; } internal XPathSortComparer Clone() { XPathSortComparer clone = new XPathSortComparer(this.numSorts); for (int i = 0; i < this.numSorts; i++) { clone.comparers[i] = this.comparers[i]; clone.expressions[i] = (Query)this.expressions[i].Clone(); // Expressions should be cloned because Query should be cloned } clone.numSorts = this.numSorts; return clone; } } // class XPathSortComparer } // namespace
using System; using System.Collections; using System.Collections.Generic; using System.IO; using PlayFab.Json; using PlayFab.SharedModels; using UnityEngine; #if !UNITY_WSA && !UNITY_WP8 using Ionic.Zlib; #endif namespace PlayFab.Internal { public class PlayFabWww : IPlayFabHttp { private int _pendingWwwMessages = 0; public bool SessionStarted { get; set; } public string AuthKey { get; set; } public void InitializeHttp() { } public void Update() { } public void OnDestroy() { } public void MakeApiCall(CallRequestContainer reqContainer) { //Set headers var headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }; if (reqContainer.AuthKey == AuthType.DevSecretKey) { #if ENABLE_PLAYFABSERVER_API || ENABLE_PLAYFABADMIN_API headers.Add("X-SecretKey", PlayFabSettings.DeveloperSecretKey); #endif } else if (reqContainer.AuthKey == AuthType.LoginSession) { headers.Add("X-Authorization", AuthKey); } headers.Add("X-ReportErrorAsSuccess", "true"); headers.Add("X-PlayFabSDK", PlayFabSettings.VersionString); #if !UNITY_WSA && !UNITY_WP8 && !UNITY_WEBGL if (PlayFabSettings.CompressApiData) { headers.Add("Content-Encoding", "GZIP"); headers.Add("Accept-Encoding", "GZIP"); using (var stream = new MemoryStream()) { using (GZipStream zipstream = new GZipStream(stream, CompressionMode.Compress, CompressionLevel.BestCompression)) { zipstream.Write(reqContainer.Payload, 0, reqContainer.Payload.Length); } reqContainer.Payload = stream.ToArray(); } } #endif //Debug.LogFormat("Posting {0} to Url: {1}", req.Trim(), url); var www = new WWW(reqContainer.FullUrl, reqContainer.Payload, headers); #if PLAYFAB_REQUEST_TIMING var stopwatch = System.Diagnostics.Stopwatch.StartNew(); #endif // Start the www corouting to Post, and get a response or error which is then passed to the callbacks. Action<string> wwwSuccessCallback = (response) => { try { #if PLAYFAB_REQUEST_TIMING var startTime = DateTime.UtcNow; #endif var httpResult = JsonWrapper.DeserializeObject<HttpResponseObject>(response, PlayFabUtil.ApiSerializerStrategy); if (httpResult.code == 200) { // We have a good response from the server reqContainer.JsonResponse = JsonWrapper.SerializeObject(httpResult.data, PlayFabUtil.ApiSerializerStrategy); reqContainer.DeserializeResultJson(); reqContainer.ApiResult.Request = reqContainer.ApiRequest; reqContainer.ApiResult.CustomData = reqContainer.CustomData; #if !DISABLE_PLAYFABCLIENT_API ClientModels.UserSettings userSettings = null; var res = reqContainer.ApiResult as ClientModels.LoginResult; var regRes = reqContainer.ApiResult as ClientModels.RegisterPlayFabUserResult; if (res != null) { userSettings = res.SettingsForUser; AuthKey = res.SessionTicket; } else if (regRes != null) { userSettings = regRes.SettingsForUser; AuthKey = regRes.SessionTicket; } if (userSettings != null && AuthKey != null && userSettings.NeedsAttribution) { PlayFabIdfa.OnPlayFabLogin(); } #endif try { PlayFabHttp.SendEvent(reqContainer.ApiEndpoint, reqContainer.ApiRequest, reqContainer.ApiResult, ApiProcessingEventType.Post); } catch (Exception e) { Debug.LogException(e); } #if PLAYFAB_REQUEST_TIMING stopwatch.Stop(); var timing = new PlayFabHttp.RequestTiming { StartTimeUtc = startTime, ApiEndpoint = reqContainer.ApiEndpoint, WorkerRequestMs = (int)stopwatch.ElapsedMilliseconds, MainThreadRequestMs = (int)stopwatch.ElapsedMilliseconds }; PlayFabHttp.SendRequestTiming(timing); #endif try { reqContainer.InvokeSuccessCallback(); } catch (Exception e) { Debug.LogException(e); } } else { if (reqContainer.ErrorCallback != null) { reqContainer.Error = PlayFabHttp.GeneratePlayFabError(response, reqContainer.CustomData); PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error); reqContainer.ErrorCallback(reqContainer.Error); } } } catch (Exception e) { Debug.LogException(e); } }; Action<string> wwwErrorCallback = (errorCb) => { reqContainer.JsonResponse = errorCb; if (reqContainer.ErrorCallback != null) { reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.JsonResponse, reqContainer.CustomData); PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error); reqContainer.ErrorCallback(reqContainer.Error); } }; PlayFabHttp.instance.StartCoroutine(Post(www, wwwSuccessCallback, wwwErrorCallback)); } private IEnumerator Post(WWW www, Action<string> wwwSuccessCallback, Action<string> wwwErrorCallback) { yield return www; if (!string.IsNullOrEmpty(www.error)) { wwwErrorCallback(www.error); } else { try { #if !UNITY_WSA && !UNITY_WP8 && !UNITY_WEBGL string encoding; if (www.responseHeaders.TryGetValue("Content-Encoding", out encoding) && encoding.ToLower() == "gzip") { var stream = new MemoryStream(www.bytes); using (var gZipStream = new GZipStream(stream, CompressionMode.Decompress, false)) { var buffer = new byte[4096]; using (var output = new MemoryStream()) { int read; while ((read = gZipStream.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, read); } output.Seek(0, SeekOrigin.Begin); var streamReader = new System.IO.StreamReader(output); var jsonResponse = streamReader.ReadToEnd(); //Debug.Log(jsonResponse); wwwSuccessCallback(jsonResponse); } } } else #endif { wwwSuccessCallback(www.text); } } catch (Exception e) { wwwErrorCallback("Unhandled error in PlayFabWWW: " + e); } } } public int GetPendingMessages() { return _pendingWwwMessages; } } }
using MatterHackers.Agg.Transform; using MatterHackers.Agg.VertexSource; using MatterHackers.VectorMath; //---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // // C# port by: Lars Brubaker // [email protected] // Copyright (C) 2007-2011 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; namespace MatterHackers.Agg.Font { public partial class TypeFace { private class Glyph { public int horiz_adv_x; public int unicode; public string glyphName; public IVertexSource glyphData = new VertexStorage(); } private class Panos_1 { // these are defined in the order in which they are present in the panos-1 attribute. private enum Family { Any, No_Fit, Latin_Text_and_Display, Latin_Script, Latin_Decorative, Latin_Pictorial }; private enum Serif_Style { Any, No_Fit, Cove, Obtuse_Cove, Square_Cove, Obtuse_Square_Cove, Square, Thin, Bone, Exaggerated, Triangle, Normal_Sans, Obtuse_Sans, Perp_Sans, Flared, Rounded }; private enum Weight { Any, No_Fit, Very_Light_100, Light_200, Thin_300, Book_400_same_as_CSS1_normal, Medium_500, Demi_600, Bold_700_same_as_CSS1_bold, Heavy_800, Black_900, Extra_Black_Nord_900_force_mapping_to_CSS1_100_900_scale }; private enum Proportion { Any, No_Fit, Old_Style, Modern, Even_Width, Expanded, Condensed, Very_Expanded, Very_Condensed, Monospaced }; private enum Contrast { Any, No_Fit, None, Very_Low, Low, Medium_Low, Medium, Medium_High, High, Very_High }; private enum Stroke_Variation { Any, No_Fit, No_Variation, Gradual_Diagonal, Gradual_Transitional, Gradual_Vertical, Gradual_Horizontal, Rapid_Vertical, Rapid_Horizontal, Instant_Horizontal, Instant_Vertical }; private enum Arm_Style { Any, No_Fit, Straight_Arms_Horizontal, Straight_Arms_Wedge, Straight_Arms_Vertical, Straight_Arms_Single_Serif, Straight_Arms_Double_Serif, Non_Straight_Arms_Horizontal, Non_Straight_Arms_Wedge, Non_Straight_Arms_Vertical_90, Non_Straight_Arms_Single_Serif, Non_Straight_Arms_Double_Serif }; private enum Letterform { Any, No_Fit, Normal_Contact, Normal_Weighted, Normal_Boxed, Normal_Flattened, Normal_Rounded, Normal_Off_Center, Normal_Square, Oblique_Contact, Oblique_Weighted, Oblique_Boxed, Oblique_Flattened, Oblique_Rounded, Oblique_Off_Center, Oblique_Square }; private enum Midline { Any, No_Fit, Standard_Trimmed, Standard_Pointed, Standard_Serifed, High_Trimmed, High_Pointed, High_Serifed, Constant_Trimmed, Constant_Pointed, Constant_Serifed, Low_Trimmed, Low_Pointed, Low_Serifed }; private enum XHeight { Any, No_Fit, Constant_Small, Constant_Standard, Constant_Large, Ducking_Small, Ducking_Standard, Ducking_Large }; private Family family; private Serif_Style serifStyle; private Weight weight; private Proportion proportion; private Contrast contrast; private Stroke_Variation strokeVariation; private Arm_Style armStyle; private Letterform letterform; private Midline midline; private XHeight xHeight; public Panos_1(String SVGPanos1String) { int tempInt; String[] valuesString = SVGPanos1String.Split(' '); if (int.TryParse(valuesString[0], out tempInt)) family = (Family)tempInt; if (int.TryParse(valuesString[1], out tempInt)) serifStyle = (Serif_Style)tempInt; if (int.TryParse(valuesString[2], out tempInt)) weight = (Weight)tempInt; if (int.TryParse(valuesString[3], out tempInt)) proportion = (Proportion)tempInt; if (int.TryParse(valuesString[4], out tempInt)) contrast = (Contrast)tempInt; if (int.TryParse(valuesString[5], out tempInt)) strokeVariation = (Stroke_Variation)tempInt; if (int.TryParse(valuesString[6], out tempInt)) armStyle = (Arm_Style)tempInt; if (int.TryParse(valuesString[7], out tempInt)) letterform = (Letterform)tempInt; if (int.TryParse(valuesString[8], out tempInt)) midline = (Midline)tempInt; if (int.TryParse(valuesString[0], out tempInt)) xHeight = (XHeight)tempInt; } } Typography.OpenFont.Typeface _ofTypeface; private String fontId; private int horiz_adv_x; private String fontFamily; private int font_weight; private String font_stretch; private int unitsPerEm; private Panos_1 panose_1; private int ascent; public int Ascent { get { return ascent; } } private int descent; public int Descent { get { return descent; } } private int x_height; public int X_height { get { return x_height; } } private int cap_height; public int Cap_height { get { return cap_height; } } private RectangleInt boundingBox; public RectangleInt BoundingBox { get { return boundingBox; } } private int underline_thickness; public int Underline_thickness { get { return underline_thickness; } } private int underline_position; public int Underline_position { get { return underline_position; } } private String unicode_range; private Glyph missingGlyph; private Dictionary<int, Glyph> glyphs = new Dictionary<int, Glyph>(); // a glyph is indexed by the string it represents, usually one character, but sometimes multiple private Dictionary<Char, Dictionary<Char, int>> HKerns = new Dictionary<char, Dictionary<char, int>>(); public int UnitsPerEm { get { return unitsPerEm; } } private static String GetSubString(String source, String start, String end) { int startIndex = 0; return GetSubString(source, start, end, ref startIndex); } private static String GetSubString(String source, String start, String end, ref int startIndex) { int startPos = source.IndexOf(start, startIndex); if (startPos >= 0) { int endPos = source.IndexOf(end, startPos + start.Length); int length = endPos - (startPos + start.Length); startIndex = endPos + end.Length; // advance our start position to the last position used return source.Substring(startPos + start.Length, length); } return null; } private static String GetStringValue(String source, String name) { String element = GetSubString(source, name + "=\"", "\""); return element; } private static bool GetIntValue(String source, String name, out int outValue, ref int startIndex) { String element = GetSubString(source, name + "=\"", "\"", ref startIndex); if (int.TryParse(element, NumberStyles.Number, null, out outValue)) { return true; } return false; } private static bool GetIntValue(String source, String name, out int outValue) { int startIndex = 0; return GetIntValue(source, name, out outValue, ref startIndex); } public static TypeFace LoadFrom(string content) { TypeFace fontUnderConstruction = new TypeFace(); fontUnderConstruction.ReadSVG(content); return fontUnderConstruction; } public void LoadTTF(string filename) { using (var fs = new FileStream(filename, FileMode.Open)) { LoadTTF(fs); } } public bool LoadTTF(Stream stream) { var reader = new Typography.OpenFont.OpenFontReader(); _ofTypeface = reader.Read(stream); if (_ofTypeface != null) { this.ascent = _ofTypeface.Ascender; this.descent = _ofTypeface.Descender; this.unitsPerEm = _ofTypeface.UnitsPerEm; return true; } return false; } public static TypeFace LoadSVG(String filename) { TypeFace fontUnderConstruction = new TypeFace(); string svgContent = ""; using (FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (StreamReader reader = new StreamReader(fileStream)) { svgContent = reader.ReadToEnd(); } } fontUnderConstruction.ReadSVG(svgContent); return fontUnderConstruction; } private Glyph CreateGlyphFromSVGGlyphData(String SVGGlyphData) { Glyph newGlyph = new Glyph(); if (!GetIntValue(SVGGlyphData, "horiz-adv-x", out newGlyph.horiz_adv_x)) { newGlyph.horiz_adv_x = horiz_adv_x; } newGlyph.glyphName = GetStringValue(SVGGlyphData, "glyph-name"); String unicodeString = GetStringValue(SVGGlyphData, "unicode"); if (unicodeString != null) { if (unicodeString.Length == 1) { newGlyph.unicode = (int)unicodeString[0]; } else { if (unicodeString.Split(';').Length > 1 && unicodeString.Split(';')[1].Length > 0) { throw new NotImplementedException("We do not currently support glyphs longer than one character. You need to write the search so that it will find them if you want to support this"); } if (int.TryParse(unicodeString, NumberStyles.Number, null, out newGlyph.unicode) == false) { // see if it is a unicode String hexNumber = GetSubString(unicodeString, "&#x", ";"); int.TryParse(hexNumber, NumberStyles.HexNumber, null, out newGlyph.unicode); } } } String dString = GetStringValue(SVGGlyphData, "d"); if (dString == null || dString.Length == 0) { return newGlyph; } if (newGlyph.glyphData is VertexStorage storage) { storage.ParseSvgDString(dString); } return newGlyph; } public void ReadSVG(String svgContent) { int startIndex = 0; String fontElementString = GetSubString(svgContent, "<font", ">", ref startIndex); fontId = GetStringValue(fontElementString, "id"); GetIntValue(fontElementString, "horiz-adv-x", out horiz_adv_x); String fontFaceString = GetSubString(svgContent, "<font-face", "/>", ref startIndex); fontFamily = GetStringValue(fontFaceString, "font-family"); GetIntValue(fontFaceString, "font-weight", out font_weight); font_stretch = GetStringValue(fontFaceString, "font-stretch"); GetIntValue(fontFaceString, "units-per-em", out unitsPerEm); panose_1 = new Panos_1(GetStringValue(fontFaceString, "panose-1")); GetIntValue(fontFaceString, "ascent", out ascent); GetIntValue(fontFaceString, "descent", out descent); GetIntValue(fontFaceString, "x-height", out x_height); GetIntValue(fontFaceString, "cap-height", out cap_height); String bboxString = GetStringValue(fontFaceString, "bbox"); String[] valuesString = bboxString.Split(' '); int.TryParse(valuesString[0], out boundingBox.Left); int.TryParse(valuesString[1], out boundingBox.Bottom); int.TryParse(valuesString[2], out boundingBox.Right); int.TryParse(valuesString[3], out boundingBox.Top); GetIntValue(fontFaceString, "underline-thickness", out underline_thickness); GetIntValue(fontFaceString, "underline-position", out underline_position); unicode_range = GetStringValue(fontFaceString, "unicode-range"); String missingGlyphString = GetSubString(svgContent, "<missing-glyph", "/>", ref startIndex); missingGlyph = CreateGlyphFromSVGGlyphData(missingGlyphString); String nextGlyphString = GetSubString(svgContent, "<glyph", "/>", ref startIndex); while (nextGlyphString != null) { // get the data and put it in the glyph dictionary Glyph newGlyph = CreateGlyphFromSVGGlyphData(nextGlyphString); if (newGlyph.unicode > 0) { glyphs.Add(newGlyph.unicode, newGlyph); } nextGlyphString = GetSubString(svgContent, "<glyph", "/>", ref startIndex); } } internal IVertexSource GetGlyphForCharacter(char character) { if (_ofTypeface != null) { // TODO: MAKE SURE THIS IS OFF!!!!!!! It is un-needed and only for debugging //glyphs.Clear(); } // TODO: check for multi character glyphs (we don't currently support them in the reader). Glyph glyph = null; if (!glyphs.TryGetValue(character, out glyph)) { // if we have a loaded ttf try to create the glyph data if (_ofTypeface != null) { var storage = new VertexStorage(); var translator = new VertexSourceGlyphTranslator(storage); var glyphIndex = _ofTypeface.LookupIndex(character); var ttfGlyph = _ofTypeface.GetGlyphByIndex(glyphIndex); // Typography.OpenFont.IGlyphReaderExtensions.Read(translator,ttfGlyph.GlyphPoints, ttfGlyph.EndPoints); // glyph = new Glyph(); glyph.unicode = character; glyph.horiz_adv_x = _ofTypeface.GetHAdvanceWidthFromGlyphIndex(glyphIndex); glyphs.Add(character, glyph); // Wrap glyph data with ClosedLoopGlyphData to ensure all loops are correctly closed glyph.glyphData = new ClosedLoopGlyphData(storage); } } return glyph?.glyphData; } /// <summary> /// Ensure all MoveTo operations are preceded by ClosePolygon commands /// </summary> private class ClosedLoopGlyphData : IVertexSource { private VertexStorage storage; public ClosedLoopGlyphData(VertexStorage source) { storage = new VertexStorage(); var vertexData = source.Vertices().Where(v => v.command != ShapePath.FlagsAndCommand.FlagNone).ToArray(); VertexData previous = default(VertexData); for(var i = 0; i < vertexData.Length; i++) { var current = vertexData[i]; // All MoveTo operations should be preceded by ClosePolygon if (i > 0 && current.IsMoveTo && ShapePath.is_vertex(previous.command)) { storage.ClosePolygon(); } // Add original VertexData storage.Add(current.position.X, current.position.Y, current.command); // Hold prior item previous = current; } // Ensure closed storage.ClosePolygon(); } public void rewind(int pathId = 0) { storage.rewind(pathId); } public ShapePath.FlagsAndCommand vertex(out double x, out double y) { return storage.vertex(out x, out y); } public IEnumerable<VertexData> Vertices() { return storage.Vertices(); } } internal int GetAdvanceForCharacter(char character, char nextCharacterToKernWith) { // TODO: check for kerning and adjust Glyph glyph; if (glyphs.TryGetValue(character, out glyph)) { return glyph.horiz_adv_x; } return 0; } internal int GetAdvanceForCharacter(char character) { Glyph glyph; if (glyphs.TryGetValue(character, out glyph)) { return glyph.horiz_adv_x; } return 0; } public void ShowDebugInfo(Graphics2D graphics2D) { StyledTypeFace typeFaceNameStyle = new StyledTypeFace(this, 30); TypeFacePrinter fontNamePrinter = new TypeFacePrinter(this.fontFamily + " - 30 point", typeFaceNameStyle); RectangleDouble bounds = typeFaceNameStyle.BoundingBoxInPixels; double origX = 10 - bounds.Left; double x = origX; double y = 10 - typeFaceNameStyle.DescentInPixels; int width = 50; Color boundingBoxColor = new Color(0, 0, 0); Color originColor = new Color(0, 0, 0); Color ascentColor = new Color(255, 0, 0); Color descentColor = new Color(255, 0, 0); Color xHeightColor = new Color(12, 25, 200); Color capHeightColor = new Color(12, 25, 200); Color underlineColor = new Color(0, 150, 55); // the origin graphics2D.Line(x, y, x + width, y, originColor); graphics2D.Rectangle(x + bounds.Left, y + bounds.Bottom, x + bounds.Right, y + bounds.Top, boundingBoxColor); x += typeFaceNameStyle.BoundingBoxInPixels.Width * 1.5; width = width * 3; double temp = typeFaceNameStyle.AscentInPixels; graphics2D.Line(x, y + temp, x + width, y + temp, ascentColor); temp = typeFaceNameStyle.DescentInPixels; graphics2D.Line(x, y + temp, x + width, y + temp, descentColor); temp = typeFaceNameStyle.XHeightInPixels; graphics2D.Line(x, y + temp, x + width, y + temp, xHeightColor); temp = typeFaceNameStyle.CapHeightInPixels; graphics2D.Line(x, y + temp, x + width, y + temp, capHeightColor); temp = typeFaceNameStyle.UnderlinePositionInPixels; graphics2D.Line(x, y + temp, x + width, y + temp, underlineColor); Affine textTransform; textTransform = Affine.NewIdentity(); textTransform *= Affine.NewTranslation(10, origX); VertexSourceApplyTransform transformedText = new VertexSourceApplyTransform(textTransform); fontNamePrinter.Render(graphics2D, Color.Black, transformedText); graphics2D.Render(transformedText, Color.Black); // render the legend StyledTypeFace legendFont = new StyledTypeFace(this, 12); Vector2 textPos = new Vector2(x + width / 2, y + typeFaceNameStyle.EmSizeInPixels * 1.5); graphics2D.Render(new TypeFacePrinter("Descent"), textPos, descentColor); textPos.Y += legendFont.EmSizeInPixels; graphics2D.Render(new TypeFacePrinter("Underline"), textPos, underlineColor); textPos.Y += legendFont.EmSizeInPixels; graphics2D.Render(new TypeFacePrinter("X Height"), textPos, xHeightColor); textPos.Y += legendFont.EmSizeInPixels; graphics2D.Render(new TypeFacePrinter("CapHeight"), textPos, capHeightColor); textPos.Y += legendFont.EmSizeInPixels; graphics2D.Render(new TypeFacePrinter("Ascent"), textPos, ascentColor); textPos.Y += legendFont.EmSizeInPixels; graphics2D.Render(new TypeFacePrinter("Origin"), textPos, originColor); textPos.Y += legendFont.EmSizeInPixels; graphics2D.Render(new TypeFacePrinter("Bounding Box"), textPos, boundingBoxColor); } } }
using UnityEngine; using System.Collections; namespace TMPro.Examples { public class TextMeshProFloatingText : MonoBehaviour { public Font TheFont; private GameObject m_floatingText; private TextMeshPro m_textMeshPro; private TextContainer m_textContainer; private TextMesh m_textMesh; private Transform m_transform; private Transform m_floatingText_Transform; private Transform m_cameraTransform; Vector3 lastPOS = Vector3.zero; Quaternion lastRotation = Quaternion.identity; public int SpawnType; //private int m_frame = 0; void Awake() { m_transform = transform; m_floatingText = new GameObject(m_transform.name + " floating text"); m_floatingText_Transform = m_floatingText.transform; m_floatingText_Transform.position = m_transform.position + new Vector3(0, 15f, 0); m_cameraTransform = Camera.main.transform; //m_parentScript = GetComponent<TextMeshSpawner>(); //Debug.Log(m_parentScript.NumberOfNPC); } void Start() { if (SpawnType == 0) { //Debug.Log("Spawning TextMesh Pro Objects."); // TextMesh Pro Implementation m_textMeshPro = m_floatingText.AddComponent<TextMeshPro>(); m_textContainer = m_floatingText.GetComponent<TextContainer>(); m_textContainer.isAutoFitting = false; //m_textMeshPro.fontAsset = Resources.Load("Fonts & Materials/JOKERMAN SDF", typeof(TextMeshProFont)) as TextMeshProFont; // User should only provide a string to the resource. //m_textMeshPro.fontSharedMaterial = Resources.Load("Fonts & Materials/ARIAL SDF 1", typeof(Material)) as Material; //m_textContainer.anchorPosition = TextContainerAnchors.Bottom; m_textMeshPro.alignment = TextAlignmentOptions.Center; m_textMeshPro.color = new Color32((byte)Random.Range(0, 255), (byte)Random.Range(0, 255), (byte)Random.Range(0, 255), 255); m_textMeshPro.fontSize = 24; //m_textMeshPro.enableExtraPadding = true; //m_textMeshPro.enableShadows = false; m_textMeshPro.text = string.Empty; StartCoroutine(DisplayTextMeshProFloatingText()); } else if (SpawnType == 1) { //Debug.Log("Spawning TextMesh Objects."); m_textMesh = m_floatingText.AddComponent<TextMesh>(); m_textMesh.font = Resources.Load("Fonts/ARIAL", typeof(Font)) as Font; m_textMesh.GetComponent<Renderer>().sharedMaterial = m_textMesh.font.material; m_textMesh.color = new Color32((byte)Random.Range(0, 255), (byte)Random.Range(0, 255), (byte)Random.Range(0, 255), 255); m_textMesh.anchor = TextAnchor.LowerCenter; m_textMesh.fontSize = 24; StartCoroutine(DisplayTextMeshFloatingText()); } else if (SpawnType == 2) { } } //void Update() //{ // if (SpawnType == 0) // { // m_textMeshPro.SetText("{0}", m_frame); // } // else // { // m_textMesh.text = m_frame.ToString(); // } // m_frame = (m_frame + 1) % 1000; //} public IEnumerator DisplayTextMeshProFloatingText() { float CountDuration = 2.0f; // How long is the countdown alive. float starting_Count = Random.Range(5f, 20f); // At what number is the counter starting at. float current_Count = starting_Count; Vector3 start_pos = m_floatingText_Transform.position; Color32 start_color = m_textMeshPro.color; float alpha = 255; //int int_counter = 0; float fadeDuration = 3 / starting_Count * CountDuration; while (current_Count > 0) { current_Count -= (Time.deltaTime / CountDuration) * starting_Count; if (current_Count <= 3) { //Debug.Log("Fading Counter ... " + current_Count.ToString("f2")); alpha = Mathf.Clamp(alpha - (Time.deltaTime / fadeDuration) * 255, 0, 255); } //int_counter = (int)current_Count; m_textMeshPro.SetText("{0}", (int)current_Count); m_textMeshPro.color = new Color32(start_color.r, start_color.g, start_color.b, (byte)alpha); // Move the floating text upward each update m_floatingText_Transform.position += new Vector3(0, starting_Count * Time.deltaTime, 0); // Align floating text perpendicular to Camera. if (!lastPOS.Compare(m_cameraTransform.position, 1000) || !lastRotation.Compare(m_cameraTransform.rotation, 1000)) { lastPOS = m_cameraTransform.position; lastRotation = m_cameraTransform.rotation; m_floatingText_Transform.rotation = lastRotation; Vector3 dir = m_transform.position - lastPOS; m_transform.forward = new Vector3(dir.x, 0, dir.z); } yield return new WaitForEndOfFrame(); } //Debug.Log("Done Counting down."); yield return new WaitForSeconds(Random.Range(0.1f, 1.0f)); m_floatingText_Transform.position = start_pos; StartCoroutine(DisplayTextMeshProFloatingText()); } public IEnumerator DisplayTextMeshFloatingText() { float CountDuration = 2.0f; // How long is the countdown alive. float starting_Count = Random.Range(5f, 20f); // At what number is the counter starting at. float current_Count = starting_Count; Vector3 start_pos = m_floatingText_Transform.position; Color32 start_color = m_textMesh.color; float alpha = 255; int int_counter = 0; float fadeDuration = 3 / starting_Count * CountDuration; while (current_Count > 0) { current_Count -= (Time.deltaTime / CountDuration) * starting_Count; if (current_Count <= 3) { //Debug.Log("Fading Counter ... " + current_Count.ToString("f2")); alpha = Mathf.Clamp(alpha - (Time.deltaTime / fadeDuration) * 255, 0, 255); } int_counter = (int)current_Count; m_textMesh.text = int_counter.ToString(); //Debug.Log("Current Count:" + current_Count.ToString("f2")); m_textMesh.color = new Color32(start_color.r, start_color.g, start_color.b, (byte)alpha); // Move the floating text upward each update m_floatingText_Transform.position += new Vector3(0, starting_Count * Time.deltaTime, 0); // Align floating text perpendicular to Camera. if (!lastPOS.Compare(m_cameraTransform.position, 1000) || !lastRotation.Compare(m_cameraTransform.rotation, 1000)) { lastPOS = m_cameraTransform.position; lastRotation = m_cameraTransform.rotation; m_floatingText_Transform.rotation = lastRotation; Vector3 dir = m_transform.position - lastPOS; m_transform.forward = new Vector3(dir.x, 0, dir.z); } yield return new WaitForEndOfFrame(); } //Debug.Log("Done Counting down."); yield return new WaitForSeconds(Random.Range(0.1f, 1.0f)); m_floatingText_Transform.position = start_pos; StartCoroutine(DisplayTextMeshFloatingText()); } } }
using PhotoNet.Common; using RawNet.Decoder.HuffmanCompressor; using RawNet.Jpeg; using System.Collections.Generic; using System.Diagnostics; namespace RawNet.Decoder.Decompressor { internal abstract class JPEGDecompressor { public ImageBinaryReader input; public BitPump bits; public RawImage raw; public SOFInfo frame = new SOFInfo(); public List<uint> slicesW = new List<uint>(1); public int predictor; public int Pt; public uint offX = 0, offY = 0; // Offset into image where decoding should start public uint skipX = 0, skipY = 0; // Tile is larger than output, skip these border pixels public HuffmanTable[] huff; public bool UseBigTable { get; set; } // Use only for large images public bool DNGCompatible { get; set; } // DNG v1.0.x compatibility public CosineTable dct = new CosineTable(); public virtual void DecodeScan() { throw new RawDecoderException("No scan decoder found"); } /* * Huffman table generation: * HuffDecode, * createHuffmanTable * and used data structures are originally grabbed from the IJG software, * and adapted by Hubert Figuiere. * * Copyright (C) 1991, 1992, Thomas G. Lane. * Part of the Independent JPEG Group's software. * See the file Copyright for more details. * * Copyright (c) 1993 Brian C. Smith, The Regents of the University * of California * All rights reserved. * * Copyright (c) 1994 Kongji Huang and Brian C. Smith. * Cornell University * All rights reserved. * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose, without fee, and without written agreement is * hereby granted, provided that the above copyright notice and the following * two paragraphs appear in all copies of this software. * * IN NO EVENT SHALL CORNELL UNIVERSITY BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF CORNELL * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * CORNELL UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND CORNELL UNIVERSITY HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ public JPEGDecompressor(ImageBinaryReader file, RawImage img, bool DNGCompatible, bool UseBigTable) { raw = img; input = file; this.DNGCompatible = DNGCompatible; this.UseBigTable = UseBigTable; huff = new HuffmanTable[4]; } public SOFInfo GetSOF(uint offset, uint size) { // JPEG is big endian if (Common.GetHostEndianness() == Endianness.Big) input = new ImageBinaryReader(input.BaseStream, offset); else input = new ImageBinaryReaderBigEndian(input.BaseStream, offset); if (GetNextMarker(false) != JpegMarker.SOI) throw new RawDecoderException("Image did not start with SOI. Probably not an LJPEG"); while (true) { JpegMarker m = GetNextMarker(true); if (m == JpegMarker.Sof3) { SOFInfo sof = new SOFInfo(); ParseSOF(sof); return sof; } if (m == JpegMarker.EOI) { throw new RawDecoderException("Could not locate Start of Frame."); } } } public void StartDecoder(uint offset, uint size) { if (!input.IsValid(offset, size)) throw new RawDecoderException("Start offset plus size is longer than file. Truncated file."); if ((int)offX >= raw.fullSize.dim.width) throw new RawDecoderException("X offset outside of image"); if ((int)offY >= raw.fullSize.dim.height) throw new RawDecoderException("Y offset outside of image"); // JPEG is big endian if (Common.GetHostEndianness() == Endianness.Big) input = new ImageBinaryReader(input.BaseStream, offset); else input = new ImageBinaryReaderBigEndian(input.BaseStream, offset); if (GetNextMarker(false) != JpegMarker.SOI) throw new RawDecoderException("Image did not start with SOI. Probably not an LJPEG"); bool moreImage = true; while (moreImage) { JpegMarker m = GetNextMarker(true); switch (m) { case JpegMarker.DQT: throw new RawDecoderException("Not a valid RAW file."); case JpegMarker.DHT: // _RPT0(0,"Found DHT marker\n"); ParseDHT(); break; case JpegMarker.SOS: // _RPT0(0,"Found SOS marker\n"); ParseSOS(); break; case JpegMarker.Sof3: // _RPT0(0,"Found SOF 3 marker:\n"); ParseSOF(frame); break; case JpegMarker.EOI: // _RPT0(0,"Found EOI marker\n"); moreImage = false; break; case JpegMarker.DRI: // _RPT0(0,"Found DRI marker\n"); case JpegMarker.App0: // _RPT0(0,"Found APP0 marker\n"); default: // _RPT1(0, "Found marker:0x%x. Skipping\n", m); // Just let it skip to next marker break; } } } public void ParseSOF(SOFInfo sof) { uint headerLength = input.ReadUInt16(); sof.precision = input.ReadByte(); sof.height = input.ReadUInt16(); sof.width = input.ReadUInt16(); sof.numComponents = input.ReadByte(); if (sof.precision > 16) throw new RawDecoderException("More than 16 bits per channel is not supported."); if (sof.numComponents > 4 || sof.numComponents < 1) throw new RawDecoderException("Only from 1 to 4 components are supported."); if (headerLength != 8 + sof.numComponents * 3) throw new RawDecoderException("Header size mismatch."); for (int i = 0; i < sof.numComponents; i++) { sof.ComponentInfo[i].componentId = input.ReadByte(); uint subs = input.ReadByte(); frame.ComponentInfo[i].superV = subs & 0xf; frame.ComponentInfo[i].superH = subs >> 4; uint Tq = input.ReadByte(); if (Tq != 0) throw new RawDecoderException("Quantized components not supported."); } sof.Initialized = true; } public void ParseSOS() { if (!frame.Initialized) throw new RawDecoderException("Frame not yet initialized (SOF Marker not parsed)"); input.ReadInt16(); uint soscps = input.ReadByte(); if (frame.numComponents != soscps) throw new RawDecoderException("Component number mismatch."); for (int i = 0; i < frame.numComponents; i++) { uint cs = input.ReadByte(); uint count = 0; // Find the correct component while (frame.ComponentInfo[count].componentId != cs) { if (count >= frame.numComponents) throw new RawDecoderException("Invalid Component Selector"); count++; } uint b1 = input.ReadByte(); uint td = b1 >> 4; if (td > 3) throw new RawDecoderException("Invalid Huffman table selection"); if (!huff[td].Initialized) throw new RawDecoderException("Invalid Huffman table selection, not defined."); if (count > 3) throw new RawDecoderException("Component count out of range"); frame.ComponentInfo[count].dcTblNo = td; } predictor = input.ReadByte(); if (predictor > 7) throw new RawDecoderException("Invalid predictor mode."); input.ReadBytes(1); // Se + Ah Not used in LJPEG int b = input.ReadByte(); Pt = b & 0xf; // Point Transform bits = new BitPumpJPEG(input); for (int i = 0; i < huff.Length; i++) { huff[i].bitPump = bits; huff[i].precision = frame.precision; } DecodeScan(); input.Position = bits.Offset; } public void ParseDHT() { uint headerLength = (uint)input.ReadInt16() - 2; // Subtract myself while (headerLength != 0) { uint b = input.ReadByte(); uint Tc = (b >> 4); if (Tc != 0) throw new RawDecoderException("Unsupported Table class."); uint Th = b & 0xf; if (Th > 3) throw new RawDecoderException("Invalid huffman table destination id."); uint acc = 0; HuffmanTable table = huff[Th]; if (table.Initialized) throw new RawDecoderException("Duplicate table definition"); for (int i = 0; i < 16; i++) { table.bits[i + 1] = input.ReadByte(); acc += table.bits[i + 1]; } table.bits[0] = 0; if (acc > 256) throw new RawDecoderException("Invalid DHT table."); if (headerLength < 1 + 16 + acc) throw new RawDecoderException("Invalid DHT table length."); for (int i = 0; i < acc; i++) { table.huffval[i] = input.ReadByte(); } table.Create(frame.precision); headerLength -= 1 + 16 + acc; } } public JpegMarker GetNextMarker(bool allowskip) { if (!allowskip) { byte idL = input.ReadByte(); if (idL != 0xff) throw new RawDecoderException("Expected marker not found. Probably corrupt file."); JpegMarker markL = (JpegMarker)input.ReadByte(); if (JpegMarker.Fill == markL || JpegMarker.Stuff == markL) throw new RawDecoderException("Expected marker, but found stuffed 00 or ff."); return markL; } input.SkipToMarker(); var id = input.ReadByte(); Debug.Assert(0xff == id); JpegMarker mark = (JpegMarker)input.ReadByte(); return mark; } } }
using NUnit.Framework; using static NSelene.Selene; namespace NSelene.Tests.Integration.SharedDriver.SeleneSpec { using System; using System.Linq; using System.Reflection; using Harness; using OpenQA.Selenium; [TestFixture] public class SeleneBrowser_Should_Specs : BaseTest { // TODO: imrove coverage and consider breaking down into separate test classes [Test] public void SeleneWaitTo_HaveJsReturned_WaitsForPresenceInDom_OfInitiialyAbsent() { Configuration.Timeout = 0.6; Configuration.PollDuringWaits = 0.1; Given.OpenedEmptyPage(); var beforeCall = DateTime.Now; Given.OpenedPageWithBodyTimedOut( @" <p style='display:none'>a</p> <p style='display:none'>b</p> ", 300 ); Selene.WaitTo(Have.JSReturnedTrue( @" var expectedCount = arguments[0] return document.getElementsByTagName('p').length == expectedCount " , 2 )); var afterCall = DateTime.Now; Assert.Greater(afterCall, beforeCall.AddSeconds(0.3)); Assert.Less(afterCall, beforeCall.AddSeconds(0.6)); } [Test] public void SeleneWaitTo_HaveNoJsReturned_WaitsForAbsenceInDom_OfInitiialyPresent() { Configuration.Timeout = 0.6; Configuration.PollDuringWaits = 0.1; Given.OpenedPageWithBody( @" <p style='display:none'>a</p> <p style='display:none'>b</p> " ); var beforeCall = DateTime.Now; Given.WithBodyTimedOut( @" ", 300 ); SS("p").Should(Have.No.Count(2)); Selene.WaitTo(Have.No.JSReturnedTrue( @" var expectedCount = arguments[0] return document.getElementsByTagName('p').length == expectedCount " , 2 )); var afterCall = DateTime.Now; Assert.Greater(afterCall, beforeCall.AddSeconds(0.3)); Assert.Less(afterCall, beforeCall.AddSeconds(0.6)); Assert.AreEqual( 0, Configuration.Driver .FindElements(By.TagName("p")).Count ); } [Test] public void SeleneWaitTo_HaveJsReturned_IsRenderedInError_OnAbsentElementTimeoutFailure() { Configuration.Timeout = 0.25; Configuration.PollDuringWaits = 0.1; Given.OpenedEmptyPage(); var beforeCall = DateTime.Now; try { Selene.WaitTo(Have.JSReturnedTrue( @" var expectedCount = arguments[0] return document.getElementsByTagName('p').length == expectedCount " , 2 )); } catch (WebDriverTimeoutException error) { var afterCall = DateTime.Now; Assert.Greater(afterCall, beforeCall.AddSeconds(0.25)); var accuracyDelta = 0.2; Assert.Less(afterCall, beforeCall.AddSeconds(0.25 + 0.1 + accuracyDelta)); // TODO: shoud we check timing here too? var lines = error.Message.Split("\n").Select( item => item.Trim() ).ToList(); Assert.Contains("Timed out after 0.25 seconds", lines); Assert.Contains("while waiting entity with locator: OpenQA.Selenium.Chrome.ChromeDriver", lines); Assert.Contains("for condition: JSReturnedTrue", lines); } // catch (TimeoutException error) // { // var afterCall = DateTime.Now; // Assert.Greater(afterCall, beforeCall.AddSeconds(0.25)); // var accuracyDelta = 0.2; // Assert.Less(afterCall, beforeCall.AddSeconds(0.25 + 0.1 + accuracyDelta)); // // TODO: shoud we check timing here too? // var lines = error.Message.Split("\n").Select( // item => item.Trim() // ).ToList(); // Assert.Contains("Timed out after 0.25s, while waiting for:", lines); // Assert.Contains("Browser.All(p).count = 2", lines); // Assert.Contains("Reason:", lines); // Assert.Contains("actual: count = 0", lines); // } } [Test] public void SeleneWaitTo_HaveNoJsReturned_IsRenderedInError_OnInDomElementsTimeoutFailure() { Configuration.Timeout = 0.25; Configuration.PollDuringWaits = 0.1; Given.OpenedPageWithBody( @" <p style='display:none'>a</p> <p style='display:none'>b</p> " ); var beforeCall = DateTime.Now; try { Selene.WaitTo(Have.No.JSReturnedTrue( @" var expectedCount = arguments[0] return document.getElementsByTagName('p').length == expectedCount " , 2 )); } catch (WebDriverTimeoutException error) { var afterCall = DateTime.Now; Assert.Greater(afterCall, beforeCall.AddSeconds(0.25)); var accuracyDelta = 0.2; Assert.Less(afterCall, beforeCall.AddSeconds(0.25 + 0.1 + accuracyDelta)); // TODO: shoud we check timing here too? var lines = error.Message.Split("\n").Select( item => item.Trim() ).ToList(); Assert.Contains("Timed out after 0.25 seconds", lines); Assert.Contains("while waiting entity with locator: OpenQA.Selenium.Chrome.ChromeDriver", lines); Assert.Contains("for condition: Not.JSReturnedTrue", lines); } // catch (TimeoutException error) // { // var afterCall = DateTime.Now; // Assert.Greater(afterCall, beforeCall.AddSeconds(0.25)); // var accuracyDelta = 0.2; // Assert.Less(afterCall, beforeCall.AddSeconds(0.25 + 0.1 + accuracyDelta)); // // TODO: shoud we check timing here too? // var lines = error.Message.Split("\n").Select( // item => item.Trim() // ).ToList(); // Assert.Contains("Timed out after 0.25s, while waiting for:", lines); // Assert.Contains("Browser.All(p).not count = 2", lines); // Assert.Contains("Reason:", lines); // Assert.Contains("actual: count = 2", lines); // } } // [Test] // public void SeleneWaitTo_HaveNoJsReturned_WaitsForAsked_OfInitialyOtherResult() // NOT RELEVANT // { // } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Azure.Core.TestFramework; using Azure.Search.Documents.Indexes; using Azure.Search.Documents.Indexes.Models; using Azure.Search.Documents.Tests.Utilities; using NUnit.Framework; namespace Azure.Search.Documents.Tests { public class SearchIndexerClientTests : SearchTestBase { public SearchIndexerClientTests(bool async, SearchClientOptions.ServiceVersion serviceVersion) : base(async, serviceVersion, null /* RecordedTestMode.Record /* to re-record */) { } [Test] public void Constructor() { var serviceName = "my-svc-name"; var endpoint = new Uri($"https://{serviceName}.search.windows.net"); var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake")); Assert.NotNull(service); Assert.AreEqual(endpoint, service.Endpoint); Assert.AreEqual(serviceName, service.ServiceName); Assert.Throws<ArgumentNullException>(() => new SearchIndexerClient(null, new AzureKeyCredential("fake"))); Assert.Throws<ArgumentNullException>(() => new SearchIndexerClient(endpoint, null)); Assert.Throws<ArgumentException>(() => new SearchIndexerClient(new Uri("http://bing.com"), null)); } [Test] public void DiagnosticsAreUnique() { // Make sure we're not repeating Header/Query names already defined // in the base ClientOptions SearchClientOptions options = new SearchClientOptions(); Assert.IsEmpty(GetDuplicates(options.Diagnostics.LoggedHeaderNames)); Assert.IsEmpty(GetDuplicates(options.Diagnostics.LoggedQueryParameters)); // CollectionAssert.Unique doesn't give you the duplicate values // which is less helpful than it could be static string GetDuplicates(IEnumerable<string> values) { List<string> duplicates = new List<string>(); HashSet<string> unique = new HashSet<string>(); foreach (string value in values) { if (!unique.Add(value)) { duplicates.Add(value); } } return string.Join(", ", duplicates); } } [Test] public async Task CreateAzureBlobIndexer() { await using SearchResources resources = await SearchResources.CreateWithBlobStorageAndIndexAsync(this, populate: true); SearchIndexerClient serviceClient = resources.GetIndexerClient(); // Create the Azure Blob data source and indexer. SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection( Recording.Random.GetName(), SearchIndexerDataSourceType.AzureBlob, resources.StorageAccountConnectionString, new SearchIndexerDataContainer(resources.BlobContainerName)); SearchIndexerDataSourceConnection actualSource = await serviceClient.CreateDataSourceConnectionAsync( dataSource); SearchIndexer indexer = new SearchIndexer( Recording.Random.GetName(), dataSource.Name, resources.IndexName); SearchIndexer actualIndexer = await serviceClient.CreateIndexerAsync( indexer); // Update the indexer. actualIndexer.Description = "Updated description"; await serviceClient.CreateOrUpdateIndexerAsync( actualIndexer, onlyIfUnchanged: true); await WaitForIndexingAsync(serviceClient, actualIndexer.Name); // Run the indexer. await serviceClient.RunIndexerAsync( indexer.Name); await WaitForIndexingAsync(serviceClient, actualIndexer.Name); // Query the index. SearchClient client = resources.GetSearchClient(); long count = await client.GetDocumentCountAsync(); // This should be equal, but sometimes reports double despite logs showing no shared resources. Assert.That(count, Is.GreaterThanOrEqualTo(SearchResources.TestDocuments.Length)); } [Test] [SyncOnly] public void CreateDataSourceConnectionParameterValidation() { var endpoint = new Uri($"https://my-svc-name.search.windows.net"); var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake")); ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.CreateDataSourceConnection(null)); Assert.AreEqual("dataSourceConnection", ex.ParamName); ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.CreateDataSourceConnectionAsync(null)); Assert.AreEqual("dataSourceConnection", ex.ParamName); } [Test] [SyncOnly] public void CreateOrUpdateDataSourceConnectionParameterValidation() { var endpoint = new Uri($"https://my-svc-name.search.windows.net"); var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake")); ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.CreateOrUpdateDataSourceConnection(null)); Assert.AreEqual("dataSourceConnection", ex.ParamName); ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.CreateOrUpdateDataSourceConnectionAsync(null)); Assert.AreEqual("dataSourceConnection", ex.ParamName); } [Test] [SyncOnly] public void GetDataSourceConnectionParameterValidation() { var endpoint = new Uri($"https://my-svc-name.search.windows.net"); var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake")); ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.GetDataSourceConnection(null)); Assert.AreEqual("dataSourceConnectionName", ex.ParamName); ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.GetDataSourceConnectionAsync(null)); Assert.AreEqual("dataSourceConnectionName", ex.ParamName); } [Test] [SyncOnly] public void DeleteDataSourceConnectionParameterValidation() { var endpoint = new Uri($"https://my-svc-name.search.windows.net"); var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake")); ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.DeleteDataSourceConnection((string)null)); Assert.AreEqual("dataSourceConnectionName", ex.ParamName); ex = Assert.Throws<ArgumentNullException>(() => service.DeleteDataSourceConnection((SearchIndexerDataSourceConnection)null)); Assert.AreEqual("dataSourceConnection", ex.ParamName); ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.DeleteDataSourceConnectionAsync((string)null)); Assert.AreEqual("dataSourceConnectionName", ex.ParamName); ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.DeleteDataSourceConnectionAsync((SearchIndexerDataSourceConnection)null)); Assert.AreEqual("dataSourceConnection", ex.ParamName); } [Test] public async Task CrudDataSourceConnection() { await using SearchResources resources = await SearchResources.CreateWithBlobStorageAndIndexAsync(this); SearchIndexerClient client = resources.GetIndexerClient(); string connectionName = Recording.Random.GetName(); SearchIndexerDataSourceConnection connection = new SearchIndexerDataSourceConnection( connectionName, SearchIndexerDataSourceType.AzureBlob, resources.StorageAccountConnectionString, new SearchIndexerDataContainer(resources.BlobContainerName)); // Create the connection. SearchIndexerDataSourceConnection createdConnection = await client.CreateDataSourceConnectionAsync(connection); try { Assert.That(createdConnection, Is.EqualTo(connection).Using(SearchIndexerDataSourceConnectionComparer.Shared)); Assert.IsNull(createdConnection.ConnectionString); // Should not be returned since it contains sensitive information. // Update the connection. createdConnection.Description = "Updated description"; SearchIndexerDataSourceConnection updatedConnection = await client.CreateOrUpdateDataSourceConnectionAsync(createdConnection, onlyIfUnchanged: true); Assert.That(updatedConnection, Is.EqualTo(createdConnection).Using(SearchIndexerDataSourceConnectionComparer.Shared)); Assert.IsNull(updatedConnection.ConnectionString); // Should not be returned since it contains sensitive information. Assert.AreNotEqual(createdConnection.ETag, updatedConnection.ETag); // Get the connection. connection = await client.GetDataSourceConnectionAsync(connectionName); Assert.That(connection, Is.EqualTo(updatedConnection).Using(SearchIndexerDataSourceConnectionComparer.Shared)); Assert.IsNull(connection.ConnectionString); // Should not be returned since it contains sensitive information. Assert.AreEqual(updatedConnection.ETag, connection.ETag); // Delete the connection. await client.DeleteDataSourceConnectionAsync(connection, onlyIfUnchanged: true); Response<IReadOnlyList<string>> names = await client.GetDataSourceConnectionNamesAsync(); CollectionAssert.DoesNotContain(names.Value, connectionName); } catch { if (Recording.Mode != RecordedTestMode.Playback) { await client.DeleteDataSourceConnectionAsync(connectionName); } throw; } } [Test] [SyncOnly] public void CreateIndexParameterValidation() { var endpoint = new Uri($"https://my-svc-name.search.windows.net"); var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake")); ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.CreateIndexer(null)); Assert.AreEqual("indexer", ex.ParamName); ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.CreateIndexerAsync(null)); Assert.AreEqual("indexer", ex.ParamName); } [Test] [SyncOnly] public void CreateOrUpdateIndexerParameterValidation() { var endpoint = new Uri($"https://my-svc-name.search.windows.net"); var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake")); ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.CreateOrUpdateIndexer(null)); Assert.AreEqual("indexer", ex.ParamName); ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.CreateOrUpdateIndexerAsync(null)); Assert.AreEqual("indexer", ex.ParamName); } [Test] [SyncOnly] public void GetIndexerParameterValidation() { var endpoint = new Uri($"https://my-svc-name.search.windows.net"); var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake")); ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.GetIndexer(null)); Assert.AreEqual("indexerName", ex.ParamName); ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.GetIndexerAsync(null)); Assert.AreEqual("indexerName", ex.ParamName); } [Test] [SyncOnly] public void DeleteIndexerParameterValidation() { var endpoint = new Uri($"https://my-svc-name.search.windows.net"); var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake")); ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.DeleteIndexer((string)null)); Assert.AreEqual("indexerName", ex.ParamName); ex = Assert.Throws<ArgumentNullException>(() => service.DeleteIndexer((SearchIndexer)null)); Assert.AreEqual("indexer", ex.ParamName); ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.DeleteIndexerAsync((string)null)); Assert.AreEqual("indexerName", ex.ParamName); ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.DeleteIndexerAsync((SearchIndexer)null)); Assert.AreEqual("indexer", ex.ParamName); } [Test] [SyncOnly] public void ResetIndexerParameterValidation() { var endpoint = new Uri($"https://my-svc-name.search.windows.net"); var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake")); ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.ResetIndexer(null)); Assert.AreEqual("indexerName", ex.ParamName); ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.ResetIndexerAsync(null)); Assert.AreEqual("indexerName", ex.ParamName); } [Test] [SyncOnly] public void RunIndexerParameterValidation() { var endpoint = new Uri($"https://my-svc-name.search.windows.net"); var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake")); ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.RunIndexer(null)); Assert.AreEqual("indexerName", ex.ParamName); ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.RunIndexerAsync(null)); Assert.AreEqual("indexerName", ex.ParamName); } [Test] [SyncOnly] public void CreateSkillsetParameterValidation() { var endpoint = new Uri($"https://my-svc-name.search.windows.net"); var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake")); ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.CreateSkillset(null)); Assert.AreEqual("skillset", ex.ParamName); ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.CreateSkillsetAsync(null)); Assert.AreEqual("skillset", ex.ParamName); } [Test] [SyncOnly] public void CreateOrUpdateSkillsetParameterValidation() { var endpoint = new Uri($"https://my-svc-name.search.windows.net"); var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake")); ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.CreateOrUpdateSkillset(null)); Assert.AreEqual("skillset", ex.ParamName); ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.CreateOrUpdateSkillsetAsync(null)); Assert.AreEqual("skillset", ex.ParamName); } [Test] [SyncOnly] public void GetSkillsetParameterValidation() { var endpoint = new Uri($"https://my-svc-name.search.windows.net"); var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake")); ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.GetSkillset(null)); Assert.AreEqual("skillsetName", ex.ParamName); ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.GetSkillsetAsync(null)); Assert.AreEqual("skillsetName", ex.ParamName); } [Test] [SyncOnly] public void DeleteSkillsetParameterValidation() { var endpoint = new Uri($"https://my-svc-name.search.windows.net"); var service = new SearchIndexerClient(endpoint, new AzureKeyCredential("fake")); ArgumentException ex = Assert.Throws<ArgumentNullException>(() => service.DeleteSkillset((string)null)); Assert.AreEqual("skillsetName", ex.ParamName); ex = Assert.Throws<ArgumentNullException>(() => service.DeleteSkillset((SearchIndexerSkillset)null)); Assert.AreEqual("skillset", ex.ParamName); ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.DeleteSkillsetAsync((string)null)); Assert.AreEqual("skillsetName", ex.ParamName); ex = Assert.ThrowsAsync<ArgumentNullException>(() => service.DeleteSkillsetAsync((SearchIndexerSkillset)null)); Assert.AreEqual("skillset", ex.ParamName); } [Test] public async Task CrudSkillset() { await using SearchResources resources = await SearchResources.CreateWithBlobStorageAndIndexAsync(this); SearchIndexerClient client = resources.GetIndexerClient(new SearchClientOptions()); string skillsetName = Recording.Random.GetName(); // Skills based on https://github.com/Azure-Samples/azure-search-sample-data/blob/master/hotelreviews/HotelReviews_skillset.json. SearchIndexerSkill skill1 = new SplitSkill( new[] { new InputFieldMappingEntry("text") { Source = "/document/reviews_text" }, new InputFieldMappingEntry("languageCode") { Source = "/document/Language" }, }, new[] { new OutputFieldMappingEntry("textItems") { TargetName = "pages" }, }) { Context = "/document/reviews_text", DefaultLanguageCode = SplitSkillLanguage.En, TextSplitMode = TextSplitMode.Pages, MaximumPageLength = 5000, }; SearchIndexerSkill skill2 = new SentimentSkill( new[] { new InputFieldMappingEntry("text") { Source = "/documents/reviews_text/pages/*" }, new InputFieldMappingEntry("languageCode") { Source = "/document/Language" }, }, new[] { new OutputFieldMappingEntry("score") { TargetName = "Sentiment" }, }) { Context = "/document/reviews_text/pages/*", DefaultLanguageCode = SentimentSkillLanguage.En, }; SearchIndexerSkill skill3 = new LanguageDetectionSkill( new[] { new InputFieldMappingEntry("text") { Source = "/document/reviews_text" }, }, new[] { new OutputFieldMappingEntry("languageCode") { TargetName = "Language" }, }) { Context = "/document", }; SearchIndexerSkill skill4 = new KeyPhraseExtractionSkill( new[] { new InputFieldMappingEntry("text") { Source = "/documents/reviews_Text/pages/*" }, new InputFieldMappingEntry("languageCode") { Source = "/document/Language" }, }, new[] { new OutputFieldMappingEntry("keyPhrases") { TargetName = "Keyphrases" }, }) { Context = "/document/reviews_text/pages/*", DefaultLanguageCode = KeyPhraseExtractionSkillLanguage.En, }; SearchIndexerSkill skill5 = new ShaperSkill( new[] { new InputFieldMappingEntry("name") { Source = "/document/name" }, new InputFieldMappingEntry("reviews_date") { Source = "/document/reviews_date" }, new InputFieldMappingEntry("reviews_rating") { Source = "/documents/reviews_rating" }, new InputFieldMappingEntry("reviews_text") { Source = "/documents/reviews_text" }, new InputFieldMappingEntry("reviews_title") { Source = "/document/reviews_title" }, new InputFieldMappingEntry("AzureSearch_DocumentKey") { Source = "/document/AzureSearch_DocumentKey" }, new InputFieldMappingEntry("pages") { SourceContext = "/document/reviews_text/pages/*", Inputs = { new InputFieldMappingEntry("SentimentScore") { Source = "/document/reviews_text/pages/*/Sentiment" }, new InputFieldMappingEntry("LanguageCode") { Source = "/document/Language" }, new InputFieldMappingEntry("Page") { Source = "/document/reviews_text/pages/*" }, new InputFieldMappingEntry("keyphrase") { SourceContext = "/document/reviews_text/pages/*/Keyphrases/*", Inputs = { new InputFieldMappingEntry("Keyphrases") { Source = "/document/reviews_text/pages/*/Keyphrases/*" }, }, }, }, }, }, new[] { new OutputFieldMappingEntry("output") { TargetName = "tableprojection" }, }) { Context = "/document", }; SearchIndexerKnowledgeStoreTableProjectionSelector table1 = new("hotelReviewsDocument") { GeneratedKeyName = "Documentid", Source = "/document/tableprojection", SourceContext = null, }; SearchIndexerKnowledgeStoreTableProjectionSelector table2 = new("hotelReviewsPages") { GeneratedKeyName = "Pagesid", Source = "/document/tableprojection/pages/*", SourceContext = null, }; SearchIndexerKnowledgeStoreTableProjectionSelector table3 = new("hotelReviewsKeyPhrases") { GeneratedKeyName = "KeyPhrasesid", Source = "/document/tableprojection/pages/*/keyphrase/*", SourceContext = null, }; SearchIndexerKnowledgeStoreProjection projection1 = new(); projection1.Tables.Add(table1); projection1.Tables.Add(table2); projection1.Tables.Add(table3); SearchIndexerKnowledgeStoreTableProjectionSelector table4 = new("hotelReviewsInlineDocument") { GeneratedKeyName = "Documentid", Source = null, SourceContext = "/document", }; table4.Inputs.Add(new("name") { Source = "/document/name", SourceContext = null }); table4.Inputs.Add(new("reviews_date") { Source = "/document/reviews_date", SourceContext = null }); table4.Inputs.Add(new("reviews_rating") { Source = "/document/reviews_rating", SourceContext = null }); table4.Inputs.Add(new("reviews_text") { Source = "/document/reviews_text", SourceContext = null }); table4.Inputs.Add(new("reviews_title") { Source = "/document/reviews_title", SourceContext = null }); table4.Inputs.Add(new("AzureSearch_DocumentKey") { Source = "/document/AzureSearch_DocumentKey", SourceContext = null }); SearchIndexerKnowledgeStoreTableProjectionSelector table5 = new("hotelReviewsInlinePages") { GeneratedKeyName = "Pagesid", Source = null, SourceContext = "/document/reviews_text/pages/*", }; table5.Inputs.Add(new("SentimentScore") { Source = "/document/reviews_text/pages/*/Sentiment", SourceContext = null }); table5.Inputs.Add(new("LanguageCode") { Source = "/document/Language", SourceContext = null }); table5.Inputs.Add(new("Page") { Source = "/document/reviews_text/pages/*", SourceContext = null }); SearchIndexerKnowledgeStoreTableProjectionSelector table6 = new("hotelReviewsInlineKeyPhrases") { GeneratedKeyName = "kpidv2", Source = null, SourceContext = "/document/reviews_text/pages/*/Keyphrases/*", }; table6.Inputs.Add(new("Keyphrases") { Source = "/document/reviews_text/pages/*/Keyphrases/*", SourceContext = null }); SearchIndexerKnowledgeStoreProjection projection2 = new(); projection2.Tables.Add(table4); projection2.Tables.Add(table5); projection2.Tables.Add(table6); List<SearchIndexerKnowledgeStoreProjection> projections = new() { projection1, projection2 }; SearchIndexerSkillset skillset = new SearchIndexerSkillset(skillsetName, new[] { skill1, skill2, skill3, skill4, skill5 }) { CognitiveServicesAccount = new DefaultCognitiveServicesAccount(), KnowledgeStore = new SearchIndexerKnowledgeStore(resources.StorageAccountConnectionString, projections), }; // Create the skillset. SearchIndexerSkillset createdSkillset = await client.CreateSkillsetAsync(skillset); try { Assert.That(createdSkillset, Is.EqualTo(skillset).Using(SearchIndexerSkillsetComparer.Shared)); // Update the skillset. createdSkillset.Description = "Update description"; SearchIndexerSkillset updatedSkillset = await client.CreateOrUpdateSkillsetAsync(createdSkillset, onlyIfUnchanged: true); Assert.That(updatedSkillset, Is.EqualTo(createdSkillset).Using(SearchIndexerSkillsetComparer.Shared)); Assert.AreNotEqual(createdSkillset.ETag, updatedSkillset.ETag); // Get the skillset skillset = await client.GetSkillsetAsync(skillsetName); Assert.That(skillset, Is.EqualTo(updatedSkillset).Using(SearchIndexerSkillsetComparer.Shared)); Assert.AreEqual(updatedSkillset.ETag, skillset.ETag); // Check the projections in the knowledge store of the skillset. Assert.AreEqual(2, skillset.KnowledgeStore.Projections.Count); SearchIndexerKnowledgeStoreProjection p1 = skillset.KnowledgeStore.Projections[0]; Assert.AreEqual(3, p1.Tables.Count); Assert.AreEqual("hotelReviewsDocument", p1.Tables[0].TableName); Assert.AreEqual(0, p1.Tables[0].Inputs.Count); Assert.AreEqual("hotelReviewsPages", p1.Tables[1].TableName); Assert.AreEqual(0, p1.Tables[1].Inputs.Count); Assert.AreEqual("hotelReviewsKeyPhrases", p1.Tables[2].TableName); Assert.AreEqual(0, p1.Tables[2].Inputs.Count); Assert.AreEqual(0, p1.Objects.Count); Assert.AreEqual(0, p1.Files.Count); SearchIndexerKnowledgeStoreProjection p2 = skillset.KnowledgeStore.Projections[1]; Assert.AreEqual(3, p2.Tables.Count); Assert.AreEqual("hotelReviewsInlineDocument", p2.Tables[0].TableName); Assert.AreEqual(6, p2.Tables[0].Inputs.Count); Assert.AreEqual("hotelReviewsInlinePages", p2.Tables[1].TableName); Assert.AreEqual(3, p2.Tables[1].Inputs.Count); Assert.AreEqual("hotelReviewsInlineKeyPhrases", p2.Tables[2].TableName); Assert.AreEqual(1, p2.Tables[2].Inputs.Count); Assert.AreEqual(0, p2.Objects.Count); Assert.AreEqual(0, p2.Files.Count); // Delete the skillset. await client.DeleteSkillsetAsync(skillset, onlyIfUnchanged: true); Response<IReadOnlyList<string>> names = await client.GetSkillsetNamesAsync(); CollectionAssert.DoesNotContain(names.Value, skillsetName); } catch { if (Recording.Mode != RecordedTestMode.Playback) { await client.DeleteSkillsetAsync(skillsetName); } throw; } } [Test] public async Task RoundtripAllSkills() { // BUGBUG: https://github.com/Azure/azure-sdk-for-net/issues/15108 await using SearchResources resources = SearchResources.CreateWithNoIndexes(this); SearchIndexerClient client = resources.GetIndexerClient(new SearchClientOptions()); string skillsetName = Recording.Random.GetName(); // Enumerate all skills and create them with consistently fake input to test for nullability during deserialization. SearchIndexerSkill CreateSkill(Type t, string[] inputNames, string[] outputNames) { var inputs = inputNames.Select(input => new InputFieldMappingEntry(input) { Source = "/document/content" } ).ToList(); var outputs = outputNames.Select(output => new OutputFieldMappingEntry(output, targetName: Recording.Random.GetName())).ToList(); return t switch { Type _ when t == typeof(CustomEntityLookupSkill) => new CustomEntityLookupSkill(inputs, outputs) { EntitiesDefinitionUri = "https://microsoft.com" }, // TODO: Should TextSplitMode be added to constructor (required input)? Type _ when t == typeof(SplitSkill) => new SplitSkill(inputs, outputs) { TextSplitMode = TextSplitMode.Pages }, Type _ when t == typeof(TextTranslationSkill) => new TextTranslationSkill(inputs, outputs, TextTranslationSkillLanguage.En), Type _ when t == typeof(WebApiSkill) => new WebApiSkill(inputs, outputs, "https://microsoft.com"), _ => (SearchIndexerSkill)Activator.CreateInstance(t, new object[] { inputs, outputs }), }; } List<SearchIndexerSkill> skills = typeof(SearchIndexerSkill).Assembly.GetExportedTypes() .Where(t => t != typeof(SearchIndexerSkill) && typeof(SearchIndexerSkill).IsAssignableFrom(t)) .Select(t => t switch { Type _ when t == typeof(ConditionalSkill) => CreateSkill(t, new[] { "condition", "whenTrue", "whenFalse" }, new[] { "output" }), Type _ when t == typeof(CustomEntityLookupSkill) => CreateSkill(t, new[] { "text", "languageCode" }, new[] { "entities" }), Type _ when t == typeof(DocumentExtractionSkill) => CreateSkill(t, new[] { "file_data" }, new[] { "content", "normalized_images" }), Type _ when t == typeof(EntityRecognitionSkill) => CreateSkill(t, new[] { "languageCode", "text" }, new[] { "persons" }), Type _ when t == typeof(ImageAnalysisSkill) => CreateSkill(t, new[] { "image" }, new[] { "categories" }), Type _ when t == typeof(KeyPhraseExtractionSkill) => CreateSkill(t, new[] { "text", "languageCode" }, new[] { "keyPhrases" }), Type _ when t == typeof(LanguageDetectionSkill) => CreateSkill(t, new[] { "text" }, new[] { "languageCode", "languageName", "score" }), Type _ when t == typeof(MergeSkill) => CreateSkill(t, new[] { "text", "itemsToInsert", "offsets" }, new[] { "mergedText" }), Type _ when t == typeof(OcrSkill) => CreateSkill(t, new[] { "image" }, new[] { "text", "layoutText" }), Type _ when t == typeof(SentimentSkill) => CreateSkill(t, new[] { "text", "languageCode" }, new[] { "score" }), Type _ when t == typeof(ShaperSkill) => CreateSkill(t, new[] { "text" }, new[] { "output" }), Type _ when t == typeof(SplitSkill) => CreateSkill(t, new[] { "text", "languageCode" }, new[] { "textItems" }), Type _ when t == typeof(TextTranslationSkill) => CreateSkill(t, new[] { "text", "toLanguageCode", "fromLanguageCode" }, new[] { "translatedText", "translatedToLanguageCode", "translatedFromLanguageCode" }), Type _ when t == typeof(WebApiSkill) => CreateSkill(t, new[] { "input" }, new[] { "output" }), _ => throw new NotSupportedException(), }) .ToList(); SearchIndexerSkillset specifiedSkillset = new SearchIndexerSkillset(skillsetName, skills) { CognitiveServicesAccount = new DefaultCognitiveServicesAccount(), KnowledgeStore = new SearchIndexerKnowledgeStore(resources.StorageAccountConnectionString, new List<SearchIndexerKnowledgeStoreProjection>()), }; try { SearchIndexerSkillset createdSkillset = await client.CreateSkillsetAsync(specifiedSkillset); Assert.AreEqual(skillsetName, createdSkillset.Name); Assert.AreEqual(skills.Count, createdSkillset.Skills.Count); } catch { if (Recording.Mode != RecordedTestMode.Playback) { await client.DeleteSkillsetAsync(skillsetName); } throw; } } } }
// 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.Diagnostics; using System.Diagnostics.Contracts; using System.Text; using System.Threading; using System.Globalization; using System.Security; namespace System.Text { // SBCSCodePageEncoding internal class SBCSCodePageEncoding : BaseCodePageEncoding { // Pointers to our memory section parts [SecurityCritical] private unsafe char* _mapBytesToUnicode = null; // char 256 [SecurityCritical] private unsafe byte* _mapUnicodeToBytes = null; // byte 65536 private const char UNKNOWN_CHAR = (char)0xFFFD; // byteUnknown is used for default fallback only private byte _byteUnknown; private char _charUnknown; [System.Security.SecurityCritical] // auto-generated public SBCSCodePageEncoding(int codePage) : this(codePage, codePage) { } [System.Security.SecurityCritical] // auto-generated public SBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage) { } // Method assumes that memory pointer is aligned private static unsafe void ZeroMemAligned(byte* buffer, int count) { long* pLong = (long*)buffer; long* pLongEnd = (long*)(buffer + count - sizeof(long)); while (pLong < pLongEnd) { *pLong = 0; pLong++; } byte* pByte = (byte*)pLong; byte* pEnd = buffer + count; while (pByte < pEnd) { *pByte = 0; pByte++; } } // We have a managed code page entry, so load our tables // SBCS data section looks like: // // char[256] - what each byte maps to in unicode. No support for surrogates. 0 is undefined code point // (except 0 for byte 0 is expected to be a real 0) // // byte/char* - Data for best fit (unicode->bytes), again no best fit for Unicode // 1st WORD is Unicode // of 1st character position // Next bytes are best fit byte for that position. Position is incremented after each byte // byte < 0x20 means skip the next n positions. (Where n is the byte #) // byte == 1 means that next word is another unicode code point # // byte == 0 is unknown. (doesn't override initial WCHAR[256] table! [System.Security.SecurityCritical] // auto-generated protected override unsafe void LoadManagedCodePage() { fixed (byte* pBytes = m_codePageHeader) { CodePageHeader* pCodePage = (CodePageHeader*)pBytes; // Should be loading OUR code page Debug.Assert(pCodePage->CodePage == dataTableCodePage, "[SBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page"); // Make sure we're really a 1 byte code page if (pCodePage->ByteCount != 1) throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, CodePage)); // Remember our unknown bytes & chars _byteUnknown = (byte)pCodePage->ByteReplace; _charUnknown = pCodePage->UnicodeReplace; // Get our mapped section 65536 bytes for unicode->bytes, 256 * 2 bytes for bytes->unicode // Plus 4 byte to remember CP # when done loading it. (Don't want to get IA64 or anything out of alignment) const int UnicodeToBytesMappingSize = 65536; const int BytesToUnicodeMappingSize = 256 * 2; const int CodePageNumberSize = 4; int bytesToAllocate = UnicodeToBytesMappingSize + BytesToUnicodeMappingSize + CodePageNumberSize + iExtraBytes; byte* pNativeMemory = GetNativeMemory(bytesToAllocate); ZeroMemAligned(pNativeMemory, bytesToAllocate); char* mapBytesToUnicode = (char*)pNativeMemory; byte* mapUnicodeToBytes = (byte*)(pNativeMemory + 256 * 2); // Need to read our data file and fill in our section. // WARNING: Multiple code pieces could do this at once (so we don't have to lock machine-wide) // so be careful here. Only stick legal values in here, don't stick temporary values. // Read our data file and set mapBytesToUnicode and mapUnicodeToBytes appropriately // First table is just all 256 mappings byte[] buffer = new byte[256 * sizeof(char)]; lock (s_streamLock) { s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin); s_codePagesEncodingDataStream.Read(buffer, 0, buffer.Length); } fixed (byte* pBuffer = buffer) { char* pTemp = (char*)pBuffer; for (int b = 0; b < 256; b++) { // Don't want to force 0's to map Unicode wrong. 0 byte == 0 unicode already taken care of if (pTemp[b] != 0 || b == 0) { mapBytesToUnicode[b] = pTemp[b]; if (pTemp[b] != UNKNOWN_CHAR) mapUnicodeToBytes[pTemp[b]] = (byte)b; } else { mapBytesToUnicode[b] = UNKNOWN_CHAR; } } } _mapBytesToUnicode = mapBytesToUnicode; _mapUnicodeToBytes = mapUnicodeToBytes; } } // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } // Read in our best fit table [System.Security.SecurityCritical] // auto-generated protected unsafe override void ReadBestFitTable() { // Lock so we don't confuse ourselves. lock (InternalSyncObject) { // If we got a best fit array already, then don't do this if (arrayUnicodeBestFit == null) { // // Read in Best Fit table. // // First check the SBCS->Unicode best fit table, which starts right after the // 256 word data table. This table looks like word, word where 1st word is byte and 2nd // word is replacement for that word. It ends when byte == 0. byte[] buffer = new byte[m_dataSize - 512]; lock (s_streamLock) { s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset + 512, SeekOrigin.Begin); s_codePagesEncodingDataStream.Read(buffer, 0, buffer.Length); } fixed (byte* pBuffer = buffer) { byte* pData = pBuffer; // Need new best fit array char[] arrayTemp = new char[256]; for (int i = 0; i < 256; i++) arrayTemp[i] = _mapBytesToUnicode[i]; // See if our words are zero ushort byteTemp; while ((byteTemp = *((ushort*)pData)) != 0) { Debug.Assert(arrayTemp[byteTemp] == UNKNOWN_CHAR, String.Format(CultureInfo.InvariantCulture, "[SBCSCodePageEncoding::ReadBestFitTable] Expected unallocated byte (not 0x{2:X2}) for best fit byte at 0x{0:X2} for code page {1}", byteTemp, CodePage, (int)arrayTemp[byteTemp])); pData += 2; arrayTemp[byteTemp] = *((char*)pData); pData += 2; } // Remember our new array arrayBytesBestFit = arrayTemp; // It was on 0, it needs to be on next byte pData += 2; byte* pUnicodeToSBCS = pData; // Now count our characters from our Unicode->SBCS best fit table, // which is right after our 256 byte data table int iBestFitCount = 0; // Now do the UnicodeToBytes Best Fit mapping (this is the one we normally think of when we say "best fit") // pData should be pointing at the first data point for Bytes->Unicode table int unicodePosition = *((ushort*)pData); pData += 2; while (unicodePosition < 0x10000) { // Get the next byte byte input = *pData; pData++; // build our table: if (input == 1) { // Use next 2 bytes as our byte position unicodePosition = *((ushort*)pData); pData += 2; } else if (input < 0x20 && input > 0 && input != 0x1e) { // Advance input characters unicodePosition += input; } else { // Use this character if it isn't zero if (input > 0) iBestFitCount++; // skip this unicode position in any case unicodePosition++; } } // Make an array for our best fit data arrayTemp = new char[iBestFitCount * 2]; // Now actually read in the data // reset pData should be pointing at the first data point for Bytes->Unicode table pData = pUnicodeToSBCS; unicodePosition = *((ushort*)pData); pData += 2; iBestFitCount = 0; while (unicodePosition < 0x10000) { // Get the next byte byte input = *pData; pData++; // build our table: if (input == 1) { // Use next 2 bytes as our byte position unicodePosition = *((ushort*)pData); pData += 2; } else if (input < 0x20 && input > 0 && input != 0x1e) { // Advance input characters unicodePosition += input; } else { // Check for escape for glyph range if (input == 0x1e) { // Its an escape, so just read next byte directly input = *pData; pData++; } // 0 means just skip me if (input > 0) { // Use this character arrayTemp[iBestFitCount++] = (char)unicodePosition; // Have to map it to Unicode because best fit will need unicode value of best fit char. arrayTemp[iBestFitCount++] = _mapBytesToUnicode[input]; // This won't work if it won't round trip. Debug.Assert(arrayTemp[iBestFitCount - 1] != (char)0, String.Format(CultureInfo.InvariantCulture, "[SBCSCodePageEncoding.ReadBestFitTable] No valid Unicode value {0:X4} for round trip bytes {1:X4}, encoding {2}", (int)_mapBytesToUnicode[input], (int)input, CodePage)); } unicodePosition++; } } // Remember it arrayUnicodeBestFit = arrayTemp; } // Fixed() } } } // GetByteCount // Note: We start by assuming that the output will be the same as count. Having // an encoder or fallback may change that assumption [System.Security.SecurityCritical] // auto-generated public override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetByteCount]count is negative"); Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. Debug.Assert(EncoderFallback != null, "[SBCSCodePageEncoding.GetByteCount]Attempting to use null fallback"); CheckMemorySection(); // Need to test fallback EncoderReplacementFallback fallback = null; // Get any left over characters char charLeftOver = (char)0; if (encoder != null) { charLeftOver = encoder.charLeftOver; Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[SBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; // Verify that we have no fallbackbuffer, actually for SBCS this is always empty, so just assert Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetByteCount]Expected empty fallback buffer at start"); } else { // If we aren't using default fallback then we may have a complicated count. fallback = EncoderFallback as EncoderReplacementFallback; } if ((fallback != null && fallback.MaxCharCount == 1)/* || bIsBestFit*/) { // Replacement fallback encodes surrogate pairs as two ?? (or two whatever), so return size is always // same as input size. // Note that no existing SBCS code pages map code points to supplementary characters, so this is easy. // We could however have 1 extra byte if the last call had an encoder and a funky fallback and // if we don't use the funky fallback this time. // Do we have an extra char left over from last time? if (charLeftOver > 0) count++; return (count); } // It had a funky fallback, so it's more complicated // May need buffer later EncoderFallbackBuffer fallbackBuffer = null; // prepare our end int byteCount = 0; char* charEnd = chars + count; EncoderFallbackBufferHelper fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { // Since leftover char was a surrogate, it'll have to be fallen back. // Get fallback Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver"); fallbackBuffer = encoder.FallbackBuffer; fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(chars, charEnd, encoder, false); // This will fallback a pair if *chars is a low surrogate fallbackHelper.InternalFallback(charLeftOver, ref chars); } // Now we may have fallback char[] already from the encoder // Go ahead and do it, including the fallback. char ch; while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // get byte for this char byte bTemp = _mapUnicodeToBytes[ch]; // Check for fallback, this'll catch surrogate pairs too. if (bTemp == 0 && ch != (char)0) { if (fallbackBuffer == null) { // Create & init fallback buffer if (encoder == null) fallbackBuffer = EncoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); // chars has moved so we need to remember figure it out so Exception fallback // index will be correct fallbackHelper.InternalInitialize(charEnd - count, charEnd, encoder, false); } // Get Fallback fallbackHelper.InternalFallback(ch, ref chars); continue; } // We'll use this one byteCount++; } Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetByteCount]Expected Empty fallback buffer at end"); return (int)byteCount; } [System.Security.SecurityCritical] // auto-generated public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetBytes]bytes is null"); Debug.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetBytes]byteCount is negative"); Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetBytes]chars is null"); Debug.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. Debug.Assert(EncoderFallback != null, "[SBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback"); CheckMemorySection(); // Need to test fallback EncoderReplacementFallback fallback = null; // Get any left over characters char charLeftOver = (char)0; if (encoder != null) { charLeftOver = encoder.charLeftOver; Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[SBCSCodePageEncoding.GetBytes]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; // Verify that we have no fallbackbuffer, for SBCS its always empty, so just assert Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetBytes]Expected empty fallback buffer at start"); // if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer && // encoder.FallbackBuffer.Remaining > 0) // throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty", // EncodingName, encoder.Fallback.GetType())); } else { // If we aren't using default fallback then we may have a complicated count. fallback = EncoderFallback as EncoderReplacementFallback; } // prepare our end char* charEnd = chars + charCount; byte* byteStart = bytes; char* charStart = chars; // See if we do the fast default or slightly slower fallback if (fallback != null && fallback.MaxCharCount == 1) { // Make sure our fallback character is valid first byte bReplacement = _mapUnicodeToBytes[fallback.DefaultString[0]]; // Check for replacements in range, otherwise fall back to slow version. if (bReplacement != 0) { // We should have exactly as many output bytes as input bytes, unless there's a leftover // character, in which case we may need one more. // If we had a leftover character we will have to add a ? (This happens if they had a funky // fallback last time, but not this time. We can't spit any out though, // because with fallback encoder each surrogate is treated as a separate code point) if (charLeftOver > 0) { // Have to have room // Throw even if doing no throw version because this is just 1 char, // so buffer will never be big enough if (byteCount == 0) ThrowBytesOverflow(encoder, true); // This'll make sure we still have more room and also make sure our return value is correct. *(bytes++) = bReplacement; byteCount--; // We used one of the ones we were counting. } // This keeps us from overrunning our output buffer if (byteCount < charCount) { // Throw or make buffer smaller? ThrowBytesOverflow(encoder, byteCount < 1); // Just use what we can charEnd = chars + byteCount; } // Simple way while (chars < charEnd) { char ch2 = *chars; chars++; byte bTemp = _mapUnicodeToBytes[ch2]; // Check for fallback if (bTemp == 0 && ch2 != (char)0) *bytes = bReplacement; else *bytes = bTemp; bytes++; } // Clear encoder if (encoder != null) { encoder.charLeftOver = (char)0; encoder.m_charsUsed = (int)(chars - charStart); } return (int)(bytes - byteStart); } } // Slower version, have to do real fallback. // For fallback we may need a fallback buffer, we know we aren't default fallback EncoderFallbackBuffer fallbackBuffer = null; // prepare our end byte* byteEnd = bytes + byteCount; EncoderFallbackBufferHelper fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver"); fallbackBuffer = encoder.FallbackBuffer; fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(chars, charEnd, encoder, true); // This will fallback a pair if *chars is a low surrogate fallbackHelper.InternalFallback(charLeftOver, ref chars); if (fallbackBuffer.Remaining > byteEnd - bytes) { // Throw it, if we don't have enough for this we never will ThrowBytesOverflow(encoder, true); } } // Now we may have fallback char[] already from the encoder fallback above // Go ahead and do it, including the fallback. char ch; while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // get byte for this char byte bTemp = _mapUnicodeToBytes[ch]; // Check for fallback, this'll catch surrogate pairs too. if (bTemp == 0 && ch != (char)0) { // Get Fallback if (fallbackBuffer == null) { // Create & init fallback buffer if (encoder == null) fallbackBuffer = EncoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); // chars has moved so we need to remember figure it out so Exception fallback // index will be correct fallbackHelper.InternalInitialize(charEnd - charCount, charEnd, encoder, true); } // Make sure we have enough room. Each fallback char will be 1 output char // (or recursion exception will be thrown) fallbackHelper.InternalFallback(ch, ref chars); if (fallbackBuffer.Remaining > byteEnd - bytes) { // Didn't use this char, reset it Debug.Assert(chars > charStart, "[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (fallback)"); chars--; fallbackHelper.InternalReset(); // Throw it & drop this data ThrowBytesOverflow(encoder, chars == charStart); break; } continue; } // We'll use this one // Bounds check if (bytes >= byteEnd) { // didn't use this char, we'll throw or use buffer Debug.Assert(fallbackBuffer == null || fallbackHelper.bFallingBack == false, "[SBCSCodePageEncoding.GetBytes]Expected to NOT be falling back"); if (fallbackBuffer == null || fallbackHelper.bFallingBack == false) { Debug.Assert(chars > charStart, "[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (normal)"); chars--; // don't use last char } ThrowBytesOverflow(encoder, chars == charStart); // throw ? break; // don't throw, stop } // Go ahead and add it *bytes = bTemp; bytes++; } // encoder stuff if we have one if (encoder != null) { // Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases if (fallbackBuffer != null && !fallbackHelper.bUsedEncoder) // Clear it in case of MustFlush encoder.charLeftOver = (char)0; // Set our chars used count encoder.m_charsUsed = (int)(chars - charStart); } // Expect Empty fallback buffer for SBCS Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetBytes]Expected Empty fallback buffer at end"); return (int)(bytes - byteStart); } // This is internal and called by something else, [System.Security.SecurityCritical] // auto-generated public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder) { // Just assert, we're called internally so these should be safe, checked already Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetCharCount]bytes is null"); Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetCharCount]byteCount is negative"); CheckMemorySection(); // See if we have best fit bool bUseBestFit = false; // Only need decoder fallback buffer if not using default replacement fallback or best fit fallback. DecoderReplacementFallback fallback = null; if (decoder == null) { fallback = DecoderFallback as DecoderReplacementFallback; bUseBestFit = DecoderFallback is InternalDecoderBestFitFallback; } else { fallback = decoder.Fallback as DecoderReplacementFallback; bUseBestFit = decoder.Fallback is InternalDecoderBestFitFallback; Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start"); } if (bUseBestFit || (fallback != null && fallback.MaxCharCount == 1)) { // Just return length, SBCS stay the same length because they don't map to surrogate // pairs and we don't have a decoder fallback. return count; } // Might need one of these later DecoderFallbackBuffer fallbackBuffer = null; DecoderFallbackBufferHelper fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); // Have to do it the hard way. // Assume charCount will be == count int charCount = count; byte[] byteBuffer = new byte[1]; // Do it our fast way byte* byteEnd = bytes + count; // Quick loop while (bytes < byteEnd) { // Faster if don't use *bytes++; char c; c = _mapBytesToUnicode[*bytes]; bytes++; // If unknown we have to do fallback count if (c == UNKNOWN_CHAR) { // Must have a fallback buffer if (fallbackBuffer == null) { // Need to adjust count so we get real start if (decoder == null) fallbackBuffer = DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(byteEnd - count, null); } // Use fallback buffer byteBuffer[0] = *(bytes - 1); charCount--; // We'd already reserved one for *(bytes-1) charCount += fallbackHelper.InternalFallback(byteBuffer, bytes); } } // Fallback buffer must be empty Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetCharCount]Expected Empty fallback buffer at end"); // Converted sequence is same length as input return charCount; } [System.Security.SecurityCritical] // auto-generated public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS decoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetChars]bytes is null"); Debug.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetChars]byteCount is negative"); Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetChars]chars is null"); Debug.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetChars]charCount is negative"); CheckMemorySection(); // See if we have best fit bool bUseBestFit = false; // Do it fast way if using ? replacement or best fit fallbacks byte* byteEnd = bytes + byteCount; byte* byteStart = bytes; char* charStart = chars; // Only need decoder fallback buffer if not using default replacement fallback or best fit fallback. DecoderReplacementFallback fallback = null; if (decoder == null) { fallback = DecoderFallback as DecoderReplacementFallback; bUseBestFit = DecoderFallback is InternalDecoderBestFitFallback; } else { fallback = decoder.Fallback as DecoderReplacementFallback; bUseBestFit = decoder.Fallback is InternalDecoderBestFitFallback; Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start"); } if (bUseBestFit || (fallback != null && fallback.MaxCharCount == 1)) { // Try it the fast way char replacementChar; if (fallback == null) replacementChar = '?'; // Best fit always has ? for fallback for SBCS else replacementChar = fallback.DefaultString[0]; // Need byteCount chars, otherwise too small buffer if (charCount < byteCount) { // Need at least 1 output byte, throw if must throw ThrowCharsOverflow(decoder, charCount < 1); // Not throwing, use what we can byteEnd = bytes + charCount; } // Quick loop, just do '?' replacement because we don't have fallbacks for decodings. while (bytes < byteEnd) { char c; if (bUseBestFit) { if (arrayBytesBestFit == null) { ReadBestFitTable(); } c = arrayBytesBestFit[*bytes]; } else c = _mapBytesToUnicode[*bytes]; bytes++; if (c == UNKNOWN_CHAR) // This is an invalid byte in the ASCII encoding. *chars = replacementChar; else *chars = c; chars++; } // bytes & chars used are the same if (decoder != null) decoder.m_bytesUsed = (int)(bytes - byteStart); return (int)(chars - charStart); } // Slower way's going to need a fallback buffer DecoderFallbackBuffer fallbackBuffer = null; byte[] byteBuffer = new byte[1]; char* charEnd = chars + charCount; DecoderFallbackBufferHelper fallbackHelper = new DecoderFallbackBufferHelper( decoder != null ? decoder.FallbackBuffer : DecoderFallback.CreateFallbackBuffer()); // Not quite so fast loop while (bytes < byteEnd) { // Faster if don't use *bytes++; char c = _mapBytesToUnicode[*bytes]; bytes++; // See if it was unknown if (c == UNKNOWN_CHAR) { // Make sure we have a fallback buffer if (fallbackBuffer == null) { if (decoder == null) fallbackBuffer = DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(byteEnd - byteCount, charEnd); } // Use fallback buffer Debug.Assert(bytes > byteStart, "[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (unknown byte)"); byteBuffer[0] = *(bytes - 1); // Fallback adds fallback to chars, but doesn't increment chars unless the whole thing fits. if (!fallbackHelper.InternalFallback(byteBuffer, bytes, ref chars)) { // May or may not throw, but we didn't get this byte bytes--; // unused byte fallbackHelper.InternalReset(); // Didn't fall this back ThrowCharsOverflow(decoder, bytes == byteStart); // throw? break; // don't throw, but stop loop } } else { // Make sure we have buffer space if (chars >= charEnd) { Debug.Assert(bytes > byteStart, "[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (known byte)"); bytes--; // unused byte ThrowCharsOverflow(decoder, bytes == byteStart); // throw? break; // don't throw, but stop loop } *(chars) = c; chars++; } } // Might have had decoder fallback stuff. if (decoder != null) decoder.m_bytesUsed = (int)(bytes - byteStart); // Expect Empty fallback buffer for GetChars Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetChars]Expected Empty fallback buffer at end"); return (int)(chars - charStart); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Characters would be # of characters + 1 in case high surrogate is ? * max fallback long byteCount = (long)charCount + 1; if (EncoderFallback.MaxCharCount > 1) byteCount *= EncoderFallback.MaxCharCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less. if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Just return length, SBCS stay the same length because they don't map to surrogate long charCount = (long)byteCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer. if (DecoderFallback.MaxCharCount > 1) charCount *= DecoderFallback.MaxCharCount; if (charCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_GetCharCountOverflow); return (int)charCount; } // True if and only if the encoding only uses single byte code points. (i.e. ASCII, 1252, etc) public override bool IsSingleByte { get { return true; } } } }
using System; using System.Reflection; using System.Collections; namespace Ditto.Benchmarking.Tests { // The MIT License // // Copyright (c) 2008 Jon Skeet // // 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. /// <summary> /// The attribute to use to mark methods as being /// the targets of benchmarking. /// </summary> [AttributeUsage(AttributeTargets.Method)] public class BenchmarkAttribute : Attribute { } /// <summary> /// Very simple benchmarking framework. Looks for all types /// in the current assembly which have public static parameterless /// methods marked with the Benchmark attribute. In addition, if /// there are public static Init, Reset and Check methods with /// appropriate parameters (a string array for Init, nothing for /// Reset or Check) these are called at appropriate times. /// </summary> public class Benchmark { /// <summary> /// Number of times to run the methods in each type. /// </summary> static int runIterations = 1; public static void Main(string[] args) { args = ParseCommandLine(args); // Save all the benchmark classes from doing a nullity test if (args == null) { args = new string[0]; } // We're only ever interested in public static methods. This variable // just makes it easier to read the code... BindingFlags publicStatic = BindingFlags.Public | BindingFlags.Static; foreach (Type type in Assembly.GetCallingAssembly().GetTypes()) { // Find an Init method taking string[], if any MethodInfo initMethod = type.GetMethod("Init", publicStatic, null, new Type[] { typeof(string[]) }, null); // Find a parameterless Reset method, if any MethodInfo resetMethod = type.GetMethod("Reset", publicStatic, null, new Type[0], null); // Find a parameterless Check method, if any MethodInfo checkMethod = type.GetMethod("Check", publicStatic, null, new Type[0], null); // Find all parameterless methods with the [Benchmark] attribute ArrayList benchmarkMethods = new ArrayList(); foreach (MethodInfo method in type.GetMethods(publicStatic)) { ParameterInfo[] parameters = method.GetParameters(); if (parameters != null && parameters.Length != 0) { continue; } if (method.GetCustomAttributes (typeof(BenchmarkAttribute), false).Length != 0) { benchmarkMethods.Add(method); } } // Ignore types with no appropriate methods to benchmark if (benchmarkMethods.Count == 0) { continue; } Console.WriteLine("Benchmarking type {0}", type.Name); // If we've got an Init method, call it once try { if (initMethod != null) { initMethod.Invoke(null, new object[] { args }); } } catch (TargetInvocationException e) { Exception inner = e.InnerException; string message = (inner == null ? null : inner.Message); if (message == null) { message = "(No message)"; } Console.WriteLine("Init failed ({0})", message); continue; // Next type } for (int i = 0; i < runIterations; i++) { if (runIterations != 1) { Console.WriteLine("Run #{0}", i + 1); } foreach (MethodInfo method in benchmarkMethods) { try { // Reset (if appropriate) if (resetMethod != null) { resetMethod.Invoke(null, null); } // Give the test as good a chance as possible // of avoiding garbage collection GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); // Now run the test itself DateTime start = DateTime.Now; method.Invoke(null, null); DateTime end = DateTime.Now; // Check the results (if appropriate) // Note that this doesn't affect the timing if (checkMethod != null) { checkMethod.Invoke(null, null); } // If everything's worked, report the time taken, // nicely lined up (assuming no very long method names!) Console.WriteLine(" {0,-20} {1} ({2} ms)", method.Name, end - start,(end-start).TotalMilliseconds); } catch (TargetInvocationException e) { Exception inner = e.InnerException; string message = (inner == null ? null : inner.Message); if (message == null) { message = "(No message)"; } Console.WriteLine(" {0}: Failed ({1})", method.Name, message); } } } } } /// <summary> /// Parses the command line, returning an array of strings /// which are the arguments the tasks should receive. This /// array will definitely be non-null, even if null is /// passed in originally. /// </summary> static string[] ParseCommandLine(string[] args) { if (args == null) { return new string[0]; } for (int i = 0; i < args.Length; i++) { switch (args[i]) { case "-runtwice": runIterations = 2; break; case "-version": PrintEnvironment(); break; case "-endoptions": // All following options are for the benchmarked // types. { string[] ret = new string[args.Length - i - 1]; Array.Copy(args, i + 1, ret, 0, ret.Length); return ret; } default: // Don't understand option; copy this and // all remaining options and return them. { string[] ret = new string[args.Length - i]; Array.Copy(args, i, ret, 0, ret.Length); return ret; } } } // Understood all arguments return new string[0]; } /// <summary> /// Prints out information about the operating environment. /// </summary> static void PrintEnvironment() { Console.WriteLine("Operating System: {0}", Environment.OSVersion); Console.WriteLine("Runtime version: {0}", Environment.Version); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.Compute; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute { /// <summary> /// Operations for determining the version of the Windows Azure Guest /// Operating System on which your service is running. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ff684169.aspx for /// more information) /// </summary> internal partial class OperatingSystemOperations : IServiceOperations<ComputeManagementClient>, IOperatingSystemOperations { /// <summary> /// Initializes a new instance of the OperatingSystemOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal OperatingSystemOperations(ComputeManagementClient client) { this._client = client; } private ComputeManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient. /// </summary> public ComputeManagementClient Client { get { return this._client; } } /// <summary> /// The List Operating Systems operation lists the versions of the /// guest operating system that are currently available in Windows /// Azure. The 2010-10-28 version of List Operating Systems also /// indicates what family an operating system version belongs to. /// Currently Windows Azure supports two operating system families: /// the Windows Azure guest operating system that is substantially /// compatible with Windows Server 2008 SP2, and the Windows Azure /// guest operating system that is substantially compatible with /// Windows Server 2008 R2. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ff684168.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Operating Systems operation response. /// </returns> public async Task<OperatingSystemListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/operatingsystems"; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-11-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperatingSystemListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new OperatingSystemListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement operatingSystemsSequenceElement = responseDoc.Element(XName.Get("OperatingSystems", "http://schemas.microsoft.com/windowsazure")); if (operatingSystemsSequenceElement != null) { foreach (XElement operatingSystemsElement in operatingSystemsSequenceElement.Elements(XName.Get("OperatingSystem", "http://schemas.microsoft.com/windowsazure"))) { OperatingSystemListResponse.OperatingSystem operatingSystemInstance = new OperatingSystemListResponse.OperatingSystem(); result.OperatingSystems.Add(operatingSystemInstance); XElement versionElement = operatingSystemsElement.Element(XName.Get("Version", "http://schemas.microsoft.com/windowsazure")); if (versionElement != null) { string versionInstance = versionElement.Value; operatingSystemInstance.Version = versionInstance; } XElement labelElement = operatingSystemsElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = TypeConversion.FromBase64String(labelElement.Value); operatingSystemInstance.Label = labelInstance; } XElement isDefaultElement = operatingSystemsElement.Element(XName.Get("IsDefault", "http://schemas.microsoft.com/windowsazure")); if (isDefaultElement != null) { bool isDefaultInstance = bool.Parse(isDefaultElement.Value); operatingSystemInstance.IsDefault = isDefaultInstance; } XElement isActiveElement = operatingSystemsElement.Element(XName.Get("IsActive", "http://schemas.microsoft.com/windowsazure")); if (isActiveElement != null) { bool isActiveInstance = bool.Parse(isActiveElement.Value); operatingSystemInstance.IsActive = isActiveInstance; } XElement familyElement = operatingSystemsElement.Element(XName.Get("Family", "http://schemas.microsoft.com/windowsazure")); if (familyElement != null) { int familyInstance = int.Parse(familyElement.Value, CultureInfo.InvariantCulture); operatingSystemInstance.Family = familyInstance; } XElement familyLabelElement = operatingSystemsElement.Element(XName.Get("FamilyLabel", "http://schemas.microsoft.com/windowsazure")); if (familyLabelElement != null) { string familyLabelInstance = TypeConversion.FromBase64String(familyLabelElement.Value); operatingSystemInstance.FamilyLabel = familyLabelInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The List OS Families operation lists the guest operating system /// families available in Windows Azure, and also lists the operating /// system versions available for each family. Currently Windows Azure /// supports two operating system families: the Windows Azure guest /// operating system that is substantially compatible with Windows /// Server 2008 SP2, and the Windows Azure guest operating system that /// is substantially compatible with Windows Server 2008 R2. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/gg441291.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Operating System Families operation response. /// </returns> public async Task<OperatingSystemListFamiliesResponse> ListFamiliesAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); Tracing.Enter(invocationId, this, "ListFamiliesAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/operatingsystemfamilies"; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-11-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperatingSystemListFamiliesResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new OperatingSystemListFamiliesResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement operatingSystemFamiliesSequenceElement = responseDoc.Element(XName.Get("OperatingSystemFamilies", "http://schemas.microsoft.com/windowsazure")); if (operatingSystemFamiliesSequenceElement != null) { foreach (XElement operatingSystemFamiliesElement in operatingSystemFamiliesSequenceElement.Elements(XName.Get("OperatingSystemFamily", "http://schemas.microsoft.com/windowsazure"))) { OperatingSystemListFamiliesResponse.OperatingSystemFamily operatingSystemFamilyInstance = new OperatingSystemListFamiliesResponse.OperatingSystemFamily(); result.OperatingSystemFamilies.Add(operatingSystemFamilyInstance); XElement nameElement = operatingSystemFamiliesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { int nameInstance = int.Parse(nameElement.Value, CultureInfo.InvariantCulture); operatingSystemFamilyInstance.Name = nameInstance; } XElement labelElement = operatingSystemFamiliesElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = TypeConversion.FromBase64String(labelElement.Value); operatingSystemFamilyInstance.Label = labelInstance; } XElement operatingSystemsSequenceElement = operatingSystemFamiliesElement.Element(XName.Get("OperatingSystems", "http://schemas.microsoft.com/windowsazure")); if (operatingSystemsSequenceElement != null) { foreach (XElement operatingSystemsElement in operatingSystemsSequenceElement.Elements(XName.Get("OperatingSystem", "http://schemas.microsoft.com/windowsazure"))) { OperatingSystemListFamiliesResponse.OperatingSystem operatingSystemInstance = new OperatingSystemListFamiliesResponse.OperatingSystem(); operatingSystemFamilyInstance.OperatingSystems.Add(operatingSystemInstance); XElement versionElement = operatingSystemsElement.Element(XName.Get("Version", "http://schemas.microsoft.com/windowsazure")); if (versionElement != null) { string versionInstance = versionElement.Value; operatingSystemInstance.Version = versionInstance; } XElement labelElement2 = operatingSystemsElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement2 != null) { string labelInstance2 = TypeConversion.FromBase64String(labelElement2.Value); operatingSystemInstance.Label = labelInstance2; } XElement isDefaultElement = operatingSystemsElement.Element(XName.Get("IsDefault", "http://schemas.microsoft.com/windowsazure")); if (isDefaultElement != null) { bool isDefaultInstance = bool.Parse(isDefaultElement.Value); operatingSystemInstance.IsDefault = isDefaultInstance; } XElement isActiveElement = operatingSystemsElement.Element(XName.Get("IsActive", "http://schemas.microsoft.com/windowsazure")); if (isActiveElement != null) { bool isActiveInstance = bool.Parse(isActiveElement.Value); operatingSystemInstance.IsActive = isActiveInstance; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.IO; using System.Reactive.Disposables; using Avalonia.Media; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.Skia.Helpers; using SkiaSharp; namespace Avalonia.Skia { /// <summary> /// Skia render target that writes to a surface. /// </summary> internal class SurfaceRenderTarget : IDrawingContextLayerImpl, IDrawableBitmapImpl { private readonly ISkiaSurface _surface; private readonly SKCanvas _canvas; private readonly bool _disableLcdRendering; private readonly GRContext _grContext; private readonly ISkiaGpu _gpu; class SkiaSurfaceWrapper : ISkiaSurface { public SKSurface Surface { get; private set; } public bool CanBlit => false; public void Blit(SKCanvas canvas) => throw new NotSupportedException(); public SkiaSurfaceWrapper(SKSurface surface) { Surface = surface; } public void Dispose() { Surface?.Dispose(); Surface = null; } } /// <summary> /// Create new surface render target. /// </summary> /// <param name="createInfo">Create info.</param> public SurfaceRenderTarget(CreateInfo createInfo) { PixelSize = new PixelSize(createInfo.Width, createInfo.Height); Dpi = createInfo.Dpi; _disableLcdRendering = createInfo.DisableTextLcdRendering; _grContext = createInfo.GrContext; _gpu = createInfo.Gpu; if (!createInfo.DisableManualFbo) _surface = _gpu?.TryCreateSurface(PixelSize, createInfo.Session); if (_surface == null) _surface = new SkiaSurfaceWrapper(CreateSurface(createInfo.GrContext, PixelSize.Width, PixelSize.Height, createInfo.Format)); _canvas = _surface?.Surface.Canvas; if (_surface == null || _canvas == null) { throw new InvalidOperationException("Failed to create Skia render target surface"); } } /// <summary> /// Create backing Skia surface. /// </summary> /// <param name="gpu">GPU.</param> /// <param name="width">Width.</param> /// <param name="height">Height.</param> /// <param name="format">Format.</param> /// <returns></returns> private static SKSurface CreateSurface(GRContext gpu, int width, int height, PixelFormat? format) { var imageInfo = MakeImageInfo(width, height, format); if (gpu != null) return SKSurface.Create(gpu, false, imageInfo); return SKSurface.Create(imageInfo); } /// <inheritdoc /> public void Dispose() { _canvas.Dispose(); _surface.Dispose(); } /// <inheritdoc /> public IDrawingContextImpl CreateDrawingContext(IVisualBrushRenderer visualBrushRenderer) { _canvas.RestoreToCount(-1); _canvas.ResetMatrix(); var createInfo = new DrawingContextImpl.CreateInfo { Surface = _surface.Surface, Dpi = Dpi, VisualBrushRenderer = visualBrushRenderer, DisableTextLcdRendering = _disableLcdRendering, GrContext = _grContext, Gpu = _gpu, }; return new DrawingContextImpl(createInfo, Disposable.Create(() => Version++)); } /// <inheritdoc /> public Vector Dpi { get; } /// <inheritdoc /> public PixelSize PixelSize { get; } public int Version { get; private set; } = 1; /// <inheritdoc /> public void Save(string fileName) { using (var image = SnapshotImage()) { ImageSavingHelper.SaveImage(image, fileName); } } /// <inheritdoc /> public void Save(Stream stream) { using (var image = SnapshotImage()) { ImageSavingHelper.SaveImage(image, stream); } } public void Blit(IDrawingContextImpl contextImpl) { var context = (DrawingContextImpl)contextImpl; if (_surface.CanBlit) { _surface.Surface.Canvas.Flush(); _surface.Blit(context.Canvas); } else { var oldMatrix = context.Canvas.TotalMatrix; context.Canvas.ResetMatrix(); _surface.Surface.Draw(context.Canvas, 0, 0, null); context.Canvas.SetMatrix(oldMatrix); } } public bool CanBlit => true; /// <inheritdoc /> public void Draw(DrawingContextImpl context, SKRect sourceRect, SKRect destRect, SKPaint paint) { using var image = SnapshotImage(); context.Canvas.DrawImage(image, sourceRect, destRect, paint); } /// <summary> /// Create Skia image snapshot from a surface. /// </summary> /// <returns>Image snapshot.</returns> public SKImage SnapshotImage() { return _surface.Surface.Snapshot(); } /// <summary> /// Create image info for given parameters. /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> /// <param name="format">Format.</param> /// <returns></returns> private static SKImageInfo MakeImageInfo(int width, int height, PixelFormat? format) { var colorType = PixelFormatHelper.ResolveColorType(format); return new SKImageInfo(Math.Max(width, 1), Math.Max(height, 1), colorType, SKAlphaType.Premul); } /// <summary> /// Create info of a surface render target. /// </summary> public struct CreateInfo { /// <summary> /// Width of a render target. /// </summary> public int Width; /// <summary> /// Height of a render target. /// </summary> public int Height; /// <summary> /// Dpi used when rendering to a surface. /// </summary> public Vector Dpi; /// <summary> /// Pixel format of a render target. /// </summary> public PixelFormat? Format; /// <summary> /// Render text without Lcd rendering. /// </summary> public bool DisableTextLcdRendering; /// <summary> /// GPU-accelerated context (optional) /// </summary> public GRContext GrContext; public ISkiaGpu Gpu; public ISkiaGpuRenderSession Session; public bool DisableManualFbo; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Reflection; using CSJ2K; using Nini.Config; using log4net; using Rednettle.Warp3D; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenMetaverse.Rendering; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Physics.Manager; using OpenSim.Services.Interfaces; using WarpRenderer = global::Warp3D.Warp3D; namespace OpenSim.Region.CoreModules.World.Warp3DMap { public class Warp3DImageModule : IMapImageGenerator, INonSharedRegionModule { private static readonly UUID TEXTURE_METADATA_MAGIC = new UUID("802dc0e0-f080-4931-8b57-d1be8611c4f3"); private static readonly Color4 WATER_COLOR = new Color4(29, 71, 95, 216); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; private IRendering m_primMesher; private IConfigSource m_config; private Dictionary<UUID, Color4> m_colors = new Dictionary<UUID, Color4>(); private bool m_useAntiAliasing = true; // TODO: Make this a config option private bool m_Enabled = false; #region IRegionModule Members public void Initialise(IConfigSource source) { m_config = source; IConfig startupConfig = m_config.Configs["Startup"]; if (startupConfig.GetString("MapImageModule", "MapImageModule") != "Warp3DImageModule") return; m_Enabled = true; } public void AddRegion(Scene scene) { if (!m_Enabled) return; m_scene = scene; List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory()); if (renderers.Count > 0) { m_primMesher = RenderingLoader.LoadRenderer(renderers[0]); m_log.Info("[MAPTILE]: Loaded prim mesher " + m_primMesher.ToString()); } else { m_log.Info("[MAPTILE]: No prim mesher loaded, prim rendering will be disabled"); } m_scene.RegisterModuleInterface<IMapImageGenerator>(this); } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { } public void Close() { } public string Name { get { return "Warp3DImageModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion #region IMapImageGenerator Members public Bitmap CreateMapTile() { Vector3 camPos = new Vector3(127.5f, 127.5f, 221.7025033688163f); Viewport viewport = new Viewport(camPos, -Vector3.UnitZ, 1024f, 0.1f, (int)Constants.RegionSize, (int)Constants.RegionSize, (float)Constants.RegionSize, (float)Constants.RegionSize); return CreateMapTile(viewport, false); } public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float fov, int width, int height, bool useTextures) { Viewport viewport = new Viewport(camPos, camDir, fov, (float)Constants.RegionSize, 0.1f, width, height); return CreateMapTile(viewport, useTextures); } public Bitmap CreateMapTile(Viewport viewport, bool useTextures) { bool drawPrimVolume = true; bool textureTerrain = true; try { IConfig startupConfig = m_config.Configs["Startup"]; drawPrimVolume = startupConfig.GetBoolean("DrawPrimOnMapTile", drawPrimVolume); textureTerrain = startupConfig.GetBoolean("TextureOnMapTile", textureTerrain); } catch { m_log.Warn("[MAPTILE]: Failed to load StartupConfig"); } m_colors.Clear(); int width = viewport.Width; int height = viewport.Height; if (m_useAntiAliasing) { width *= 2; height *= 2; } WarpRenderer renderer = new WarpRenderer(); renderer.CreateScene(width, height); renderer.Scene.autoCalcNormals = false; #region Camera warp_Vector pos = ConvertVector(viewport.Position); pos.z -= 0.001f; // Works around an issue with the Warp3D camera warp_Vector lookat = warp_Vector.add(ConvertVector(viewport.Position), ConvertVector(viewport.LookDirection)); renderer.Scene.defaultCamera.setPos(pos); renderer.Scene.defaultCamera.lookAt(lookat); if (viewport.Orthographic) { renderer.Scene.defaultCamera.isOrthographic = true; renderer.Scene.defaultCamera.orthoViewWidth = viewport.OrthoWindowWidth; renderer.Scene.defaultCamera.orthoViewHeight = viewport.OrthoWindowHeight; } else { float fov = viewport.FieldOfView; fov *= 1.75f; // FIXME: ??? renderer.Scene.defaultCamera.setFov(fov); } #endregion Camera renderer.Scene.addLight("Light1", new warp_Light(new warp_Vector(0.2f, 0.2f, 1f), 0xffffff, 320, 80)); renderer.Scene.addLight("Light2", new warp_Light(new warp_Vector(-1f, -1f, 1f), 0xffffff, 100, 40)); CreateWater(renderer); CreateTerrain(renderer, textureTerrain); if (drawPrimVolume) CreateAllPrims(renderer, useTextures); renderer.Render(); Bitmap bitmap = renderer.Scene.getImage(); if (m_useAntiAliasing) bitmap = ImageUtils.ResizeImage(bitmap, viewport.Width, viewport.Height); return bitmap; } public byte[] WriteJpeg2000Image() { try { using (Bitmap mapbmp = CreateMapTile()) return OpenJPEG.EncodeFromImage(mapbmp, true); } catch (Exception e) { // JPEG2000 encoder failed m_log.Error("[MAPTILE]: Failed generating terrain map: " + e); } return null; } #endregion #region Rendering Methods private void CreateWater(WarpRenderer renderer) { float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight; renderer.AddPlane("Water", 256f * 0.5f); renderer.Scene.sceneobject("Water").setPos(127.5f, waterHeight, 127.5f); renderer.AddMaterial("WaterColor", ConvertColor(WATER_COLOR)); renderer.Scene.material("WaterColor").setTransparency((byte)((1f - WATER_COLOR.A) * 255f)); renderer.SetObjectMaterial("Water", "WaterColor"); } private void CreateTerrain(WarpRenderer renderer, bool textureTerrain) { IVoxelChannel terrain = m_scene.Voxels; float[] heightmap = terrain.GetFloatsSerialised(); warp_Object obj = new warp_Object(256 * 256, 255 * 255 * 2); for (int y = 0; y < 256; y++) { for (int x = 0; x < 256; x++) { int v = y * 256 + x; float height = heightmap[v]; warp_Vector pos = ConvertVector(new Vector3(x, y, height)); obj.addVertex(new warp_Vertex(pos, (float)x / 255f, (float)(255 - y) / 255f)); } } for (int y = 0; y < 256; y++) { for (int x = 0; x < 256; x++) { if (x < 255 && y < 255) { int v = y * 256 + x; // Normal Vector3 v1 = new Vector3(x, y, heightmap[y * 256 + x]); Vector3 v2 = new Vector3(x + 1, y, heightmap[y * 256 + x + 1]); Vector3 v3 = new Vector3(x, y + 1, heightmap[(y + 1) * 256 + x]); warp_Vector norm = ConvertVector(SurfaceNormal(v1, v2, v3)); norm = norm.reverse(); obj.vertex(v).n = norm; // Triangle 1 obj.addTriangle( v, v + 1, v + 256); // Triangle 2 obj.addTriangle( v + 256 + 1, v + 256, v + 1); } } } renderer.Scene.addObject("Terrain", obj); UUID[] textureIDs = new UUID[4]; float[] startHeights = new float[4]; float[] heightRanges = new float[4]; RegionSettings regionInfo = m_scene.RegionInfo.RegionSettings; textureIDs[0] = regionInfo.TerrainTexture1; textureIDs[1] = regionInfo.TerrainTexture2; textureIDs[2] = regionInfo.TerrainTexture3; textureIDs[3] = regionInfo.TerrainTexture4; startHeights[0] = (float)regionInfo.Elevation1SW; startHeights[1] = (float)regionInfo.Elevation1NW; startHeights[2] = (float)regionInfo.Elevation1SE; startHeights[3] = (float)regionInfo.Elevation1NE; heightRanges[0] = (float)regionInfo.Elevation2SW; heightRanges[1] = (float)regionInfo.Elevation2NW; heightRanges[2] = (float)regionInfo.Elevation2SE; heightRanges[3] = (float)regionInfo.Elevation2NE; uint globalX, globalY; Utils.LongToUInts(m_scene.RegionInfo.RegionHandle, out globalX, out globalY); Bitmap image = TerrainSplat.Splat(heightmap, textureIDs, startHeights, heightRanges, new Vector3d(globalX, globalY, 0.0), m_scene.AssetService, textureTerrain); warp_Texture texture = new warp_Texture(image); warp_Material material = new warp_Material(texture); material.setReflectivity(50); renderer.Scene.addMaterial("TerrainColor", material); renderer.SetObjectMaterial("Terrain", "TerrainColor"); } private void CreateAllPrims(WarpRenderer renderer, bool useTextures) { if (m_primMesher == null) return; m_scene.ForEachSOG( delegate(SceneObjectGroup group) { CreatePrim(renderer, group.RootPart, useTextures); foreach (SceneObjectPart child in group.Parts) CreatePrim(renderer, child, useTextures); } ); } private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim, bool useTextures) { const float MIN_SIZE = 2f; if ((PCode)prim.Shape.PCode != PCode.Prim) return; if (prim.Scale.LengthSquared() < MIN_SIZE * MIN_SIZE) return; Primitive omvPrim = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset); FacetedMesh renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium); if (renderMesh == null) return; warp_Vector primPos = ConvertVector(prim.GetWorldPosition()); warp_Quaternion primRot = ConvertQuaternion(prim.RotationOffset); warp_Matrix m = warp_Matrix.quaternionMatrix(primRot); if (prim.ParentID != 0) { SceneObjectGroup group = m_scene.SceneGraph.GetGroupByPrim(prim.LocalId); if (group != null) m.transform(warp_Matrix.quaternionMatrix(ConvertQuaternion(group.RootPart.RotationOffset))); } warp_Vector primScale = ConvertVector(prim.Scale); string primID = prim.UUID.ToString(); // Create the prim faces // TODO: Implement the useTextures flag behavior for (int i = 0; i < renderMesh.Faces.Count; i++) { Face face = renderMesh.Faces[i]; string meshName = primID + "-Face-" + i.ToString(); // Avoid adding duplicate meshes to the scene if (renderer.Scene.objectData.ContainsKey(meshName)) { continue; } warp_Object faceObj = new warp_Object(face.Vertices.Count, face.Indices.Count / 3); for (int j = 0; j < face.Vertices.Count; j++) { Vertex v = face.Vertices[j]; warp_Vector pos = ConvertVector(v.Position); warp_Vector norm = ConvertVector(v.Normal); if (prim.Shape.SculptTexture == UUID.Zero) norm = norm.reverse(); warp_Vertex vert = new warp_Vertex(pos, norm, v.TexCoord.X, v.TexCoord.Y); faceObj.addVertex(vert); } for (int j = 0; j < face.Indices.Count; j += 3) { faceObj.addTriangle( face.Indices[j + 0], face.Indices[j + 1], face.Indices[j + 2]); } Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i); Color4 faceColor = GetFaceColor(teFace); string materialName = GetOrCreateMaterial(renderer, faceColor); faceObj.transform(m); faceObj.setPos(primPos); faceObj.scaleSelf(primScale.x, primScale.y, primScale.z); renderer.Scene.addObject(meshName, faceObj); renderer.SetObjectMaterial(meshName, materialName); } } private Color4 GetFaceColor(Primitive.TextureEntryFace face) { Color4 color; if (face.TextureID == UUID.Zero) return face.RGBA; if (!m_colors.TryGetValue(face.TextureID, out color)) { bool fetched = false; // Attempt to fetch the texture metadata UUID metadataID = UUID.Combine(face.TextureID, TEXTURE_METADATA_MAGIC); AssetBase metadata = m_scene.AssetService.GetCached(metadataID.ToString()); if (metadata != null) { OSDMap map = null; try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { } if (map != null) { color = map["X-JPEG2000-RGBA"].AsColor4(); fetched = true; } } if (!fetched) { // Fetch the texture, decode and get the average color, // then save it to a temporary metadata asset AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString()); if (textureAsset != null) { int width, height; color = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height); OSDMap data = new OSDMap { { "X-JPEG2000-RGBA", OSD.FromColor4(color) } }; metadata = new AssetBase { Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)), Description = "Metadata for JPEG2000 texture " + face.TextureID.ToString(), Flags = AssetFlags.Collectable, FullID = metadataID, ID = metadataID.ToString(), Local = true, Temporary = true, Name = String.Empty, Type = (sbyte)AssetType.Unknown }; m_scene.AssetService.Store(metadata); } else { color = new Color4(0.5f, 0.5f, 0.5f, 1.0f); } } m_colors[face.TextureID] = color; } return color * face.RGBA; } private string GetOrCreateMaterial(WarpRenderer renderer, Color4 color) { string name = color.ToString(); warp_Material material = renderer.Scene.material(name); if (material != null) return name; renderer.AddMaterial(name, ConvertColor(color)); if (color.A < 1f) renderer.Scene.material(name).setTransparency((byte)((1f - color.A) * 255f)); return name; } #endregion Rendering Methods #region Static Helpers private static warp_Vector ConvertVector(Vector3 vector) { return new warp_Vector(vector.X, vector.Z, vector.Y); } private static warp_Quaternion ConvertQuaternion(Quaternion quat) { return new warp_Quaternion(quat.X, quat.Z, quat.Y, -quat.W); } private static int ConvertColor(Color4 color) { int c = warp_Color.getColor((byte)(color.R * 255f), (byte)(color.G * 255f), (byte)(color.B * 255f)); if (color.A < 1f) c |= (byte)(color.A * 255f) << 24; return c; } private static Vector3 SurfaceNormal(Vector3 c1, Vector3 c2, Vector3 c3) { Vector3 edge1 = new Vector3(c2.X - c1.X, c2.Y - c1.Y, c2.Z - c1.Z); Vector3 edge2 = new Vector3(c3.X - c1.X, c3.Y - c1.Y, c3.Z - c1.Z); Vector3 normal = Vector3.Cross(edge1, edge2); normal.Normalize(); return normal; } public static Color4 GetAverageColor(UUID textureID, byte[] j2kData, out int width, out int height) { ulong r = 0; ulong g = 0; ulong b = 0; ulong a = 0; using (MemoryStream stream = new MemoryStream(j2kData)) { try { Bitmap bitmap = (Bitmap)J2kImage.FromStream(stream); width = bitmap.Width; height = bitmap.Height; BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bitmap.PixelFormat); int pixelBytes = (bitmap.PixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4; // Sum up the individual channels unsafe { if (pixelBytes == 4) { for (int y = 0; y < height; y++) { byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride); for (int x = 0; x < width; x++) { b += row[x * pixelBytes + 0]; g += row[x * pixelBytes + 1]; r += row[x * pixelBytes + 2]; a += row[x * pixelBytes + 3]; } } } else { for (int y = 0; y < height; y++) { byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride); for (int x = 0; x < width; x++) { b += row[x * pixelBytes + 0]; g += row[x * pixelBytes + 1]; r += row[x * pixelBytes + 2]; } } } } // Get the averages for each channel const decimal OO_255 = 1m / 255m; decimal totalPixels = (decimal)(width * height); decimal rm = ((decimal)r / totalPixels) * OO_255; decimal gm = ((decimal)g / totalPixels) * OO_255; decimal bm = ((decimal)b / totalPixels) * OO_255; decimal am = ((decimal)a / totalPixels) * OO_255; if (pixelBytes == 3) am = 1m; return new Color4((float)rm, (float)gm, (float)bm, (float)am); } catch (Exception ex) { m_log.WarnFormat("[MAPTILE]: Error decoding JPEG2000 texture {0} ({1} bytes): {2}", textureID, j2kData.Length, ex.Message); width = 0; height = 0; return new Color4(0.5f, 0.5f, 0.5f, 1.0f); } } } #endregion Static Helpers } public static class ImageUtils { /// <summary> /// Performs bilinear interpolation between four values /// </summary> /// <param name="v00">First, or top left value</param> /// <param name="v01">Second, or top right value</param> /// <param name="v10">Third, or bottom left value</param> /// <param name="v11">Fourth, or bottom right value</param> /// <param name="xPercent">Interpolation value on the X axis, between 0.0 and 1.0</param> /// <param name="yPercent">Interpolation value on fht Y axis, between 0.0 and 1.0</param> /// <returns>The bilinearly interpolated result</returns> public static float Bilinear(float v00, float v01, float v10, float v11, float xPercent, float yPercent) { return Utils.Lerp(Utils.Lerp(v00, v01, xPercent), Utils.Lerp(v10, v11, xPercent), yPercent); } /// <summary> /// Performs a high quality image resize /// </summary> /// <param name="image">Image to resize</param> /// <param name="width">New width</param> /// <param name="height">New height</param> /// <returns>Resized image</returns> public static Bitmap ResizeImage(Image image, int width, int height) { Bitmap result = new Bitmap(width, height); using (Graphics graphics = Graphics.FromImage(result)) { graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; graphics.DrawImage(image, 0, 0, result.Width, result.Height); } return result; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Reflection; using log4net; using Nini.Config; using Nwc.XmlRpc; using Mono.Addins; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.OptionalModules.World.MoneyModule { /// <summary> /// This is only the functionality required to make the functionality associated with money work /// (such as land transfers). There is no money code here! Use FORGE as an example for money code. /// Demo Economy/Money Module. This is a purposely crippled module! /// // To land transfer you need to add: /// -helperuri http://serveraddress:port/ /// to the command line parameters you use to start up your client /// This commonly looks like -helperuri http://127.0.0.1:9000/ /// /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SampleMoneyModule")] public class SampleMoneyModule : IMoneyModule, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Where Stipends come from and Fees go to. /// </summary> // private UUID EconomyBaseAccount = UUID.Zero; private float EnergyEfficiency = 0f; // private ObjectPaid handerOnObjectPaid; private bool m_enabled = true; private bool m_sellEnabled = false; private IConfigSource m_gConfig; /// <summary> /// Region UUIDS indexed by AgentID /// </summary> /// <summary> /// Scenes by Region Handle /// </summary> private Dictionary<ulong, Scene> m_scenel = new Dictionary<ulong, Scene>(); // private int m_stipend = 1000; private int ObjectCount = 0; private int PriceEnergyUnit = 0; private int PriceGroupCreate = 0; private int PriceObjectClaim = 0; private float PriceObjectRent = 0f; private float PriceObjectScaleFactor = 0f; private int PriceParcelClaim = 0; private float PriceParcelClaimFactor = 0f; private int PriceParcelRent = 0; private int PricePublicObjectDecay = 0; private int PricePublicObjectDelete = 0; private int PriceRentLight = 0; private int PriceUpload = 0; private int TeleportMinPrice = 0; private float TeleportPriceExponent = 0f; #region IMoneyModule Members #pragma warning disable 0067 public event ObjectPaid OnObjectPaid; #pragma warning restore 0067 public int UploadCharge { get { return 0; } } public int GroupCreationCharge { get { return 0; } } /// <summary> /// Called on startup so the module can be configured. /// </summary> /// <param name="config">Configuration source.</param> public void Initialise(IConfigSource config) { m_gConfig = config; IConfig startupConfig = m_gConfig.Configs["Startup"]; IConfig economyConfig = m_gConfig.Configs["Economy"]; ReadConfigAndPopulate(startupConfig, "Startup"); ReadConfigAndPopulate(economyConfig, "Economy"); } public void AddRegion(Scene scene) { if (m_enabled) { scene.RegisterModuleInterface<IMoneyModule>(this); IHttpServer httpServer = MainServer.Instance; lock (m_scenel) { if (m_scenel.Count == 0) { // XMLRPCHandler = scene; // To use the following you need to add: // -helperuri <ADDRESS TO HERE OR grid MONEY SERVER> // to the command line parameters you use to start up your client // This commonly looks like -helperuri http://127.0.0.1:9000/ // Local Server.. enables functionality only. httpServer.AddXmlRPCHandler("getCurrencyQuote", quote_func); httpServer.AddXmlRPCHandler("buyCurrency", buy_func); httpServer.AddXmlRPCHandler("preflightBuyLandPrep", preflightBuyLandPrep_func); httpServer.AddXmlRPCHandler("buyLandPrep", landBuy_func); } if (m_scenel.ContainsKey(scene.RegionInfo.RegionHandle)) { m_scenel[scene.RegionInfo.RegionHandle] = scene; } else { m_scenel.Add(scene.RegionInfo.RegionHandle, scene); } } scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnMoneyTransfer += MoneyTransferAction; scene.EventManager.OnClientClosed += ClientClosed; scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel; scene.EventManager.OnMakeChildAgent += MakeChildAgent; scene.EventManager.OnClientClosed += ClientLoggedOut; scene.EventManager.OnValidateLandBuy += ValidateLandBuy; scene.EventManager.OnLandBuy += processLandBuy; } } public void RemoveRegion(Scene scene) { } public void RegionLoaded(Scene scene) { } // Please do not refactor these to be just one method // Existing implementations need the distinction // public void ApplyCharge(UUID agentID, int amount, MoneyTransactionType type, string extraData) { } public void ApplyCharge(UUID agentID, int amount, MoneyTransactionType type) { } public void ApplyUploadCharge(UUID agentID, int amount, string text) { } public bool ObjectGiveMoney(UUID objectID, UUID fromID, UUID toID, int amount) { string description = String.Format("Object {0} pays {1}", resolveObjectName(objectID), resolveAgentName(toID)); bool give_result = doMoneyTransfer(fromID, toID, amount, 2, description); BalanceUpdate(fromID, toID, give_result, description); return give_result; } public void PostInitialise() { } public void Close() { } public Type ReplaceableInterface { get { return typeof(IMoneyModule); } } public string Name { get { return "BetaGridLikeMoneyModule"; } } #endregion /// <summary> /// Parse Configuration /// </summary> /// <param name="scene"></param> /// <param name="startupConfig"></param> /// <param name="config"></param> private void ReadConfigAndPopulate(IConfig startupConfig, string config) { if (config == "Startup" && startupConfig != null) { m_enabled = (startupConfig.GetString("economymodule", "BetaGridLikeMoneyModule") == "BetaGridLikeMoneyModule"); } if (config == "Economy" && startupConfig != null) { PriceEnergyUnit = startupConfig.GetInt("PriceEnergyUnit", 100); PriceObjectClaim = startupConfig.GetInt("PriceObjectClaim", 10); PricePublicObjectDecay = startupConfig.GetInt("PricePublicObjectDecay", 4); PricePublicObjectDelete = startupConfig.GetInt("PricePublicObjectDelete", 4); PriceParcelClaim = startupConfig.GetInt("PriceParcelClaim", 1); PriceParcelClaimFactor = startupConfig.GetFloat("PriceParcelClaimFactor", 1f); PriceUpload = startupConfig.GetInt("PriceUpload", 0); PriceRentLight = startupConfig.GetInt("PriceRentLight", 5); TeleportMinPrice = startupConfig.GetInt("TeleportMinPrice", 2); TeleportPriceExponent = startupConfig.GetFloat("TeleportPriceExponent", 2f); EnergyEfficiency = startupConfig.GetFloat("EnergyEfficiency", 1); PriceObjectRent = startupConfig.GetFloat("PriceObjectRent", 1); PriceObjectScaleFactor = startupConfig.GetFloat("PriceObjectScaleFactor", 10); PriceParcelRent = startupConfig.GetInt("PriceParcelRent", 1); PriceGroupCreate = startupConfig.GetInt("PriceGroupCreate", -1); m_sellEnabled = startupConfig.GetBoolean("SellEnabled", false); } } private void GetClientFunds(IClientAPI client) { CheckExistAndRefreshFunds(client.AgentId); } /// <summary> /// New Client Event Handler /// </summary> /// <param name="client"></param> private void OnNewClient(IClientAPI client) { GetClientFunds(client); // Subscribe to Money messages client.OnEconomyDataRequest += EconomyDataRequestHandler; client.OnMoneyBalanceRequest += SendMoneyBalance; client.OnRequestPayPrice += requestPayPrice; client.OnObjectBuy += ObjectBuy; client.OnLogout += ClientClosed; } /// <summary> /// Transfer money /// </summary> /// <param name="Sender"></param> /// <param name="Receiver"></param> /// <param name="amount"></param> /// <returns></returns> private bool doMoneyTransfer(UUID Sender, UUID Receiver, int amount, int transactiontype, string description) { bool result = true; return result; } /// <summary> /// Sends the the stored money balance to the client /// </summary> /// <param name="client"></param> /// <param name="agentID"></param> /// <param name="SessionID"></param> /// <param name="TransactionID"></param> public void SendMoneyBalance(IClientAPI client, UUID agentID, UUID SessionID, UUID TransactionID) { if (client.AgentId == agentID && client.SessionId == SessionID) { int returnfunds = 0; try { returnfunds = GetFundsForAgentID(agentID); } catch (Exception e) { client.SendAlertMessage(e.Message + " "); } client.SendMoneyBalance(TransactionID, true, new byte[0], returnfunds, 0, UUID.Zero, false, UUID.Zero, false, 0, String.Empty); } else { client.SendAlertMessage("Unable to send your money balance to you!"); } } private SceneObjectPart findPrim(UUID objectID) { lock (m_scenel) { foreach (Scene s in m_scenel.Values) { SceneObjectPart part = s.GetSceneObjectPart(objectID); if (part != null) { return part; } } } return null; } private string resolveObjectName(UUID objectID) { SceneObjectPart part = findPrim(objectID); if (part != null) { return part.Name; } return String.Empty; } private string resolveAgentName(UUID agentID) { // try avatar username surname Scene scene = GetRandomScene(); UserAccount account = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, agentID); if (account != null) { string avatarname = account.FirstName + " " + account.LastName; return avatarname; } else { m_log.ErrorFormat( "[MONEY]: Could not resolve user {0}", agentID); } return String.Empty; } private void BalanceUpdate(UUID senderID, UUID receiverID, bool transactionresult, string description) { IClientAPI sender = LocateClientObject(senderID); IClientAPI receiver = LocateClientObject(receiverID); if (senderID != receiverID) { if (sender != null) { sender.SendMoneyBalance(UUID.Random(), transactionresult, Utils.StringToBytes(description), GetFundsForAgentID(senderID), 0, UUID.Zero, false, UUID.Zero, false, 0, String.Empty); } if (receiver != null) { receiver.SendMoneyBalance(UUID.Random(), transactionresult, Utils.StringToBytes(description), GetFundsForAgentID(receiverID), 0, UUID.Zero, false, UUID.Zero, false, 0, String.Empty); } } } /// <summary> /// XMLRPC handler to send alert message and sound to client /// </summary> public XmlRpcResponse UserAlert(XmlRpcRequest request, IPEndPoint remoteClient) { XmlRpcResponse ret = new XmlRpcResponse(); Hashtable retparam = new Hashtable(); Hashtable requestData = (Hashtable) request.Params[0]; UUID agentId; UUID soundId; UUID regionId; UUID.TryParse((string) requestData["agentId"], out agentId); UUID.TryParse((string) requestData["soundId"], out soundId); UUID.TryParse((string) requestData["regionId"], out regionId); string text = (string) requestData["text"]; string secret = (string) requestData["secret"]; Scene userScene = GetSceneByUUID(regionId); if (userScene != null) { if (userScene.RegionInfo.regionSecret == secret) { IClientAPI client = LocateClientObject(agentId); if (client != null) { if (soundId != UUID.Zero) client.SendPlayAttachedSound(soundId, UUID.Zero, UUID.Zero, 1.0f, 0); client.SendBlueBoxMessage(UUID.Zero, "", text); retparam.Add("success", true); } else { retparam.Add("success", false); } } else { retparam.Add("success", false); } } ret.Value = retparam; return ret; } # region Standalone box enablers only public XmlRpcResponse quote_func(XmlRpcRequest request, IPEndPoint remoteClient) { // Hashtable requestData = (Hashtable) request.Params[0]; // UUID agentId = UUID.Zero; int amount = 0; Hashtable quoteResponse = new Hashtable(); XmlRpcResponse returnval = new XmlRpcResponse(); Hashtable currencyResponse = new Hashtable(); currencyResponse.Add("estimatedCost", 0); currencyResponse.Add("currencyBuy", amount); quoteResponse.Add("success", true); quoteResponse.Add("currency", currencyResponse); quoteResponse.Add("confirm", "asdfad9fj39ma9fj"); returnval.Value = quoteResponse; return returnval; } public XmlRpcResponse buy_func(XmlRpcRequest request, IPEndPoint remoteClient) { // Hashtable requestData = (Hashtable) request.Params[0]; // UUID agentId = UUID.Zero; // int amount = 0; XmlRpcResponse returnval = new XmlRpcResponse(); Hashtable returnresp = new Hashtable(); returnresp.Add("success", true); returnval.Value = returnresp; return returnval; } public XmlRpcResponse preflightBuyLandPrep_func(XmlRpcRequest request, IPEndPoint remoteClient) { XmlRpcResponse ret = new XmlRpcResponse(); Hashtable retparam = new Hashtable(); Hashtable membershiplevels = new Hashtable(); ArrayList levels = new ArrayList(); Hashtable level = new Hashtable(); level.Add("id", "00000000-0000-0000-0000-000000000000"); level.Add("description", "some level"); levels.Add(level); //membershiplevels.Add("levels",levels); Hashtable landuse = new Hashtable(); landuse.Add("upgrade", false); landuse.Add("action", "http://invaliddomaininvalid.com/"); Hashtable currency = new Hashtable(); currency.Add("estimatedCost", 0); Hashtable membership = new Hashtable(); membershiplevels.Add("upgrade", false); membershiplevels.Add("action", "http://invaliddomaininvalid.com/"); membershiplevels.Add("levels", membershiplevels); retparam.Add("success", true); retparam.Add("currency", currency); retparam.Add("membership", membership); retparam.Add("landuse", landuse); retparam.Add("confirm", "asdfajsdkfjasdkfjalsdfjasdf"); ret.Value = retparam; return ret; } public XmlRpcResponse landBuy_func(XmlRpcRequest request, IPEndPoint remoteClient) { XmlRpcResponse ret = new XmlRpcResponse(); Hashtable retparam = new Hashtable(); // Hashtable requestData = (Hashtable) request.Params[0]; // UUID agentId = UUID.Zero; // int amount = 0; retparam.Add("success", true); ret.Value = retparam; return ret; } #endregion #region local Fund Management /// <summary> /// Ensures that the agent accounting data is set up in this instance. /// </summary> /// <param name="agentID"></param> private void CheckExistAndRefreshFunds(UUID agentID) { } /// <summary> /// Gets the amount of Funds for an agent /// </summary> /// <param name="AgentID"></param> /// <returns></returns> private int GetFundsForAgentID(UUID AgentID) { int returnfunds = 0; return returnfunds; } // private void SetLocalFundsForAgentID(UUID AgentID, int amount) // { // } #endregion #region Utility Helpers /// <summary> /// Locates a IClientAPI for the client specified /// </summary> /// <param name="AgentID"></param> /// <returns></returns> private IClientAPI LocateClientObject(UUID AgentID) { ScenePresence tPresence = null; IClientAPI rclient = null; lock (m_scenel) { foreach (Scene _scene in m_scenel.Values) { tPresence = _scene.GetScenePresence(AgentID); if (tPresence != null) { if (!tPresence.IsChildAgent) { rclient = tPresence.ControllingClient; } } if (rclient != null) { return rclient; } } } return null; } private Scene LocateSceneClientIn(UUID AgentId) { lock (m_scenel) { foreach (Scene _scene in m_scenel.Values) { ScenePresence tPresence = _scene.GetScenePresence(AgentId); if (tPresence != null) { if (!tPresence.IsChildAgent) { return _scene; } } } } return null; } /// <summary> /// Utility function Gets a Random scene in the instance. For when which scene exactly you're doing something with doesn't matter /// </summary> /// <returns></returns> public Scene GetRandomScene() { lock (m_scenel) { foreach (Scene rs in m_scenel.Values) return rs; } return null; } /// <summary> /// Utility function to get a Scene by RegionID in a module /// </summary> /// <param name="RegionID"></param> /// <returns></returns> public Scene GetSceneByUUID(UUID RegionID) { lock (m_scenel) { foreach (Scene rs in m_scenel.Values) { if (rs.RegionInfo.originRegionID == RegionID) { return rs; } } } return null; } #endregion #region event Handlers public void requestPayPrice(IClientAPI client, UUID objectID) { Scene scene = LocateSceneClientIn(client.AgentId); if (scene == null) return; SceneObjectPart task = scene.GetSceneObjectPart(objectID); if (task == null) return; SceneObjectGroup group = task.ParentGroup; SceneObjectPart root = group.RootPart; client.SendPayPrice(objectID, root.PayPrice); } /// <summary> /// When the client closes the connection we remove their accounting /// info from memory to free up resources. /// </summary> /// <param name="AgentID">UUID of agent</param> /// <param name="scene">Scene the agent was connected to.</param> /// <see cref="OpenSim.Region.Framework.Scenes.EventManager.ClientClosed"/> public void ClientClosed(UUID AgentID, Scene scene) { } /// <summary> /// Event called Economy Data Request handler. /// </summary> /// <param name="agentId"></param> public void EconomyDataRequestHandler(IClientAPI user) { Scene s = (Scene)user.Scene; user.SendEconomyData(EnergyEfficiency, s.RegionInfo.ObjectCapacity, ObjectCount, PriceEnergyUnit, PriceGroupCreate, PriceObjectClaim, PriceObjectRent, PriceObjectScaleFactor, PriceParcelClaim, PriceParcelClaimFactor, PriceParcelRent, PricePublicObjectDecay, PricePublicObjectDelete, PriceRentLight, PriceUpload, TeleportMinPrice, TeleportPriceExponent); } private void ValidateLandBuy(Object osender, EventManager.LandBuyArgs e) { lock (e) { e.economyValidated = true; } } private void processLandBuy(Object osender, EventManager.LandBuyArgs e) { } /// <summary> /// THis method gets called when someone pays someone else as a gift. /// </summary> /// <param name="osender"></param> /// <param name="e"></param> private void MoneyTransferAction(Object osender, EventManager.MoneyTransferArgs e) { } /// <summary> /// Event Handler for when a root agent becomes a child agent /// </summary> /// <param name="avatar"></param> private void MakeChildAgent(ScenePresence avatar) { } /// <summary> /// Event Handler for when the client logs out. /// </summary> /// <param name="AgentId"></param> private void ClientLoggedOut(UUID AgentId, Scene scene) { } /// <summary> /// Call this when the client disconnects. /// </summary> /// <param name="client"></param> public void ClientClosed(IClientAPI client) { ClientClosed(client.AgentId, null); } /// <summary> /// Event Handler for when an Avatar enters one of the parcels in the simulator. /// </summary> /// <param name="avatar"></param> /// <param name="localLandID"></param> /// <param name="regionID"></param> private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID) { //m_log.Info("[FRIEND]: " + avatar.Name + " status:" + (!avatar.IsChildAgent).ToString()); } public int GetBalance(UUID agentID) { return 0; } // Please do not refactor these to be just one method // Existing implementations need the distinction // public bool UploadCovered(UUID agentID, int amount) { return true; } public bool AmountCovered(UUID agentID, int amount) { return true; } #endregion public void ObjectBuy(IClientAPI remoteClient, UUID agentID, UUID sessionID, UUID groupID, UUID categoryID, uint localID, byte saleType, int salePrice) { if (!m_sellEnabled) { remoteClient.SendBlueBoxMessage(UUID.Zero, "", "Buying is not implemented in this version"); return; } if (salePrice != 0) { remoteClient.SendBlueBoxMessage(UUID.Zero, "", "Buying anything for a price other than zero is not implemented"); return; } Scene s = LocateSceneClientIn(remoteClient.AgentId); // Implmenting base sale data checking here so the default OpenSimulator implementation isn't useless // combined with other implementations. We're actually validating that the client is sending the data // that it should. In theory, the client should already know what to send here because it'll see it when it // gets the object data. If the data sent by the client doesn't match the object, the viewer probably has an // old idea of what the object properties are. Viewer developer Hazim informed us that the base module // didn't check the client sent data against the object do any. Since the base modules are the // 'crowning glory' examples of good practice.. // Validate that the object exists in the scene the user is in SceneObjectPart part = s.GetSceneObjectPart(localID); if (part == null) { remoteClient.SendAgentAlertMessage("Unable to buy now. The object was not found.", false); return; } // Validate that the client sent the price that the object is being sold for if (part.SalePrice != salePrice) { remoteClient.SendAgentAlertMessage("Cannot buy at this price. Buy Failed. If you continue to get this relog.", false); return; } // Validate that the client sent the proper sale type the object has set if (part.ObjectSaleType != saleType) { remoteClient.SendAgentAlertMessage("Cannot buy this way. Buy Failed. If you continue to get this relog.", false); return; } IBuySellModule module = s.RequestModuleInterface<IBuySellModule>(); if (module != null) module.BuyObject(remoteClient, categoryID, localID, saleType, salePrice); } } public enum TransactionType : int { SystemGenerated = 0, RegionMoneyRequest = 1, Gift = 2, Purchase = 3 } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using Microsoft.Research.DataStructures; namespace Microsoft.Research.CodeAnalysis { using Source = Int32; using Dest = Int32; /// <summary> /// Use one instance for each method. /// </summary> public class MethodHasher<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Context, Expression, SymbolicValue> : IDisposable where Type : IEquatable<Type> { // Already hashed Subroutines private readonly Set<Subroutine> hashedSubroutines = new Set<Subroutine>(); // method-unique id for a subroutine private readonly Func<Subroutine, int> subroutineIdentifier; // Already hashed types private readonly Set<Type> referencedTypes = new Set<Type>(); // method-unique id for a type private readonly Func<Type, int> typeIdentifier; // Types to be hashed private readonly Queue<Type> typesQueue = new Queue<Type>(); // Subroutines to be hashed (method subroutine + for ForAll/Exists calls the delegate subroutines) private readonly Queue<Subroutine> subroutineQueue = new Queue<Subroutine>(); // Compute hash for IL private readonly ILHasher ilHasher; // TextWriter that pipes a StreamWriter and a CryptoStream with an HashAlgorithm private readonly HashWriter tw; private readonly IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, ILogOptions> mDriver; private readonly AnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, ILogOptions, IMethodResult<SymbolicValue>> driver; public MethodHasher( AnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, ILogOptions, IMethodResult<SymbolicValue>> driver, IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, ILogOptions> mDriver, bool trace, Func<Subroutine, int> subroutineIdentifier = null, Func<Type, int> typeIdentifier = null ) { this.driver = driver; this.mDriver = mDriver; this.tw = new HashWriter(trace); this.ilHasher = new ILHasher(this.mDriver.StackLayer, this.tw, this.ReferenceType, this.InlinedSubroutine); if (subroutineIdentifier != null) this.subroutineIdentifier = subroutineIdentifier; else { // unique ID for a subroutine (used to put warnings into contexts) var subroutineLocalIds = new BijectiveMap<Subroutine, int>(); this.subroutineIdentifier = sub => { int res; if (!subroutineLocalIds.TryGetValue(sub, out res)) subroutineLocalIds.Add(sub, res = subroutineLocalIds.Count); return res; }; } if (typeIdentifier != null) this.typeIdentifier = typeIdentifier; else { // unique ID for types (used for general serialization of boxed expressions) var referencedTypesLocalIds = new BijectiveMap<Type, int>(); this.typeIdentifier = typ => { int res; if (!referencedTypesLocalIds.TryGetValue(typ, out res)) referencedTypesLocalIds.Add(typ, res = referencedTypesLocalIds.Count); return res; }; } } /// <summary> /// Entry point for the method hashing /// </summary> public byte[] GetHash(byte[] AdditionalOptionsToHash) { var md = this.mDriver.MetaDataDecoder; var currMethod = this.mDriver.CurrentMethod; // Hashing the options this.tw.WriteLine(Convert.ToBase64String(AdditionalOptionsToHash)); #region Hashing the method signature this.tw.WriteLine("{0} {1} {2} {3} {4} returnType:{5} {6}", md.IsStatic(currMethod) ? "static" : "", md.IsPropertyGetter(currMethod) ? "getter" : "", md.IsPropertySetter(currMethod) ? "setter" : "", md.IsCompilerGenerated(currMethod) ? "compilerGenerated" : "", md.IsVirtual(currMethod) ? "virtual" : "", this.ReferenceType(md.ReturnType(currMethod)), md.FullName(currMethod)); this.tw.WriteLine("Is externally visible = {0}", md.IsVisibleOutsideAssembly(currMethod)); this.tw.Write("Params : "); foreach (var param in md.Parameters(this.mDriver.CurrentMethod).Enumerate()) this.tw.Write("{0} type:{1}\t", md.Name(param), this.ReferenceType(md.ParameterType(param))); this.tw.WriteLine(); this.tw.Write("Locals : "); foreach (var local in md.Locals(this.mDriver.CurrentMethod).Enumerate()) this.tw.Write("{0} type:{1}\t", md.Name(local), this.ReferenceType(md.LocalType(local))); this.tw.WriteLine(); this.tw.Write("ImplementsOrOverrides : "); foreach (var method in md.OverriddenAndImplementedMethods(this.mDriver.CurrentMethod)) this.tw.Write("{0}\t", md.FullName(method)); this.tw.WriteLine(); #endregion // Hashing the main subroutine and all the others this.subroutineQueue.Enqueue(this.mDriver.CFG.Subroutine); while (this.subroutineQueue.Count > 0) { this.HashSubroutine(this.subroutineQueue.Dequeue()); } // Hashing the types while (this.typesQueue.Count > 0) this.HashTypeReference(this.typesQueue.Dequeue()); return this.tw.GetHash(); } private int ReferenceType(Type type) { if (this.referencedTypes.Add(type)) this.typesQueue.Enqueue(type); return this.typeIdentifier(type); } private int InlinedSubroutine(Method method) { // specialized methods have no body method = this.driver.MetaDataDecoder.Unspecialized(method); if (this.driver.MetaDataDecoder.HasBody(method)) { this.subroutineQueue.Enqueue(this.driver.MethodCache.GetCFG(method).Subroutine); } return this.subroutineQueue.Count; } private void HashTypeReference(Type type) { // TODO : // md.GetAttributes ? // md.IsModified ? var md = this.mDriver.MetaDataDecoder; this.tw.Write("Type{0} : {1}", this.typeIdentifier(type), md.FullName(type)); IIndexable<Type> @params; bool formal = md.IsFormalTypeParameter(type) || md.IsMethodFormalTypeParameter(type); if(formal) { if(md.IsMethodFormalTypeParameter(type)) this.tw.Write(" methodFormal{0}", md.MethodFormalTypeParameterIndex(type)); if(md.IsFormalTypeParameter(type)) this.tw.Write(" typeFormal{0}", md.NormalizedFormalTypeParameterIndex(type)); if(md.IsConstructorConstrained(type)) this.tw.Write(" constructorConstrained"); if(md.IsValueConstrained(type)) this.tw.Write(" valueConstrained"); if(md.IsReferenceConstrained(type)) this.tw.Write(" refConstrained"); foreach(var c in md.TypeParameterConstraints(type)) this.tw.Write(" constraint:{0}", this.ReferenceType(c)); } else if(md.IsGeneric(type, out @params, true)) { this.tw.Write(" generic :"); for(int i = 0; i < @params.Count; i++) this.tw.Write(" {0}", this.ReferenceType(@params[i])); } else if(md.IsSpecialized(type, out @params)) { this.tw.Write(" specialized :"); for(int i = 0; i < @params.Count; i++) this.tw.Write(" {0}", this.ReferenceType(@params[i])); } else if(md.IsArray(type)) { this.tw.Write(" array : {0} {1}", md.Rank(type), this.ReferenceType(md.ElementType(type))); } else if(md.IsUnmanagedPointer(type)) { this.tw.Write(" unmanaged pointer : {0}", this.ReferenceType(md.ElementType(type))); } else if(md.IsManagedPointer(type)) { this.tw.Write(" managed pointer : {0}", this.ReferenceType(md.ElementType(type))); } else if(md.IsEnum(type)) { this.tw.Write(" enum : {0}", md.TypeEnum(type)); List<int> enumValues; if(md.TryGetEnumValues(type, out enumValues)) { this.tw.Write(" enum values: {0}", string.Join(",", enumValues)); } } else if(md.IsDelegate(type)) { this.tw.Write(" delegate"); // Maybe we should hash a bit more } else if(md.IsInterface(type) || md.IsClass(type) || md.IsStruct(type)) { this.tw.Write(md.IsInterface(type) ? " interface" : md.IsStruct(type) ? " struct" : " class"); this.tw.Write(" implements :"); foreach(var i in md.Interfaces(type)) this.tw.Write(" {0}", this.ReferenceType(i)); if(md.IsClass(type) && md.HasBaseClass(type)) this.tw.Write(" inherits : {0}", this.ReferenceType(md.BaseClass(type))); } if(md.IsCompilerGenerated(type)) this.tw.Write(" compilerGenerated"); if(md.IsPrimitive(type)) this.tw.Write(" primitive"); if(md.IsReferenceType(type)) this.tw.Write(" referenceType"); this.tw.Write(" typeSize:{0}", md.TypeSize(type)); this.tw.WriteLine(); } private void HashSubroutine(Subroutine subroutine) { var ilDecoder = this.mDriver.StackLayer.Decoder; if (hashedSubroutines.Contains(subroutine)) return; this.hashedSubroutines.Add(subroutine); // Hash the name this.tw.WriteLine("SUBROUTINE{0} {1}", this.subroutineIdentifier(subroutine), subroutine.Kind); // Hash all the blocks foreach (var block in subroutine.Blocks) { this.tw.WriteLine("Block {0}", block.Index); this.tw.WriteLine(" Handlers: "); // TODO : handlers - we ignore them now, as in Clousot's analysis we do it too! this.tw.WriteLine(" Code:"); foreach (var apc in block.APCs()) { ilDecoder.ForwardDecode<Unit, Unit, ILHasher>(apc, this.ilHasher, Unit.Value); } var subroutinesToVisit = new Set<Subroutine>(subroutine.UsedSubroutines()); var stackCFG = this.mDriver.StackLayer.Decoder.Context.MethodContext.CFG; this.tw.WriteLine(" Successors:"); foreach (var taggedSucc in subroutine.SuccessorEdgesFor(block)) { this.tw.Write("({0},{1}", taggedSucc.One, taggedSucc.Two.Index); // The order of successors edges is not deterministic (why?), hence the OrderBy var edgesubs = stackCFG.GetOrdinaryEdgeSubroutines(block, taggedSucc.Two, null).GetEnumerable() .Select(edgesub => new Tuple<string, Subroutine>(String.Format(" SUBROUTINE{0}({1})", this.subroutineIdentifier(edgesub.Two), edgesub.One), edgesub.Two)) .OrderBy(x => x.Item1); foreach (var edgesub in edgesubs) { this.tw.Write(edgesub.Item1); subroutinesToVisit.Add(edgesub.Item2); } this.tw.Write(") "); } this.tw.WriteLine(); // Go recursively //foreach (var usedSubroutine in subroutine.UsedSubroutines().OrderBy(s => this.subroutineIdentifier(s))) foreach (var usedSubroutine in subroutinesToVisit.OrderBy(s => this.subroutineIdentifier(s))) HashSubroutine(usedSubroutine); } } private class ILHasher : IVisitMSIL<APC, Local, Parameter, Method, Field, Type, Source, Dest, Unit, Unit> { private readonly StreamWriter tw; private readonly ICodeLayer<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Source, Dest, IStackContext<Field, Method>, Unit> codeLayer; private readonly Func<Type, int> typeReferencer; private readonly Func<Method, int> inlineMethod; private Converter<Source, string> source2String { get { return this.codeLayer.ExpressionToString; } } private Converter<Dest, string> dest2String { get { return this.codeLayer.VariableToString; } } private IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder { get { return this.codeLayer.MetaDataDecoder; } } private IDecodeContracts<Local, Parameter, Method, Field, Type> contractDecoder { get { return this.codeLayer.ContractDecoder; } } public ILHasher( ICodeLayer<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Source, Dest, IStackContext<Field, Method>, Unit> codeLayer, StreamWriter tw, Func<Type, int> typeReferencer, Func<Method,int> inlineMethod ) { this.codeLayer = codeLayer; this.tw = tw; this.typeReferencer = typeReferencer; this.inlineMethod = inlineMethod; } #region IVisitMSIL<Label,Local,Parameter,Method,Field,Type,Source,Dest,Unit,Unit> Members public Unit Arglist(APC pc, Dest dest, Unit data) { this.tw.WriteLine(" {0} = arglist", this.dest2String(dest)); return Unit.Value; } // Should not be used in the stack based CFG. public Unit BranchCond(APC pc, APC target, BranchOperator bop, Source value1, Source value2, Unit data) { throw new NotImplementedException(); } // Should not be used in the stack based CFG. public Unit BranchTrue(APC pc, APC target, Source cond, Unit data) { throw new NotImplementedException(); } // Should not be used in the stack based CFG. public Unit BranchFalse(APC pc, APC target, Source cond, Unit data) { throw new NotImplementedException(); } // Should not be used in the stack based CFG. public Unit Branch(APC pc, APC target, bool leave, Unit data) { throw new NotImplementedException(); } // Should not be used in the stack based CFG. public Unit Switch(APC pc, Type type, IEnumerable<Pair<object, APC>> cases, Source value, Unit data) { throw new NotImplementedException(); } public Unit Break(APC pc, Unit data) { this.tw.WriteLine(" break"); return Unit.Value; } public Unit Call<TypeList, ArgList>(APC pc, Method method, bool tail, bool virt, TypeList extraVarargs, Dest dest, ArgList args, Unit data) where TypeList : IIndexable<Type> where ArgList : IIndexable<Source> { // The purity attribute may have changed, therefore we hash it var isPure = this.contractDecoder.IsPure(method); var fullname = this.mdDecoder.FullName(method); this.tw.Write(isPure.ToString()); // We need to hash the names of the methods because some built-in methods have special treatments this.tw.Write(" {3} = {0}call{2} {1}(", tail ? "tail." : null, fullname, virt ? "virt" : null, this.dest2String(dest)); if (args != null) { for (int i = 0; i < args.Count; i++) { this.tw.Write("{0} ", this.source2String(args[i])); if (this.mdDecoder.IsPure(method, i)) { this.tw.Write(i.ToString()); } } // if we call Contract.{ForAll, Exists} with a delegate that we decompile, we need to hash the delegate's il too var mName = mdDecoder.Name(method); if (isPure && ((mName == "ForAll") || (mName == "Exists"))) { // last argument is closure Method quantifierClosure; if (this.codeLayer.Decoder.Context.StackContext.TryGetCallArgumentDelegateTarget(pc, args[args.Count - 1], out quantifierClosure)) { this.tw.Write("QuantifierClosure{0}", this.inlineMethod(quantifierClosure).ToString()); } } } this.tw.Write(")"); if (extraVarargs != null) { this.tw.Write(" extra varargs types : "); for (int i = 0; i < extraVarargs.Count; i++) this.tw.Write("{0} ", this.typeReferencer(extraVarargs[i])); } this.tw.Write(" resultType : {0}", this.typeReferencer(this.mdDecoder.ReturnType(method))); this.tw.WriteLine(); return Unit.Value; } public Unit ConstrainedCallvirt<TypeList, ArgList>(APC pc, Method method, bool tail, Type constraint, TypeList extraVarargs, Dest dest, ArgList args, Unit data) where TypeList : IIndexable<Type> where ArgList : IIndexable<Source> { // The purity attribute may have changed, therefore we hash it var isPure = this.contractDecoder.IsPure(method); this.tw.Write(isPure.ToString()); // We need to hash the names of the methods because some built-in methods have special treatments this.tw.Write(" {3} = {0}constrained({1}).callvirt {2}(", tail ? "tail." : null, this.typeReferencer(constraint), this.mdDecoder.FullName(method), this.dest2String(dest)); if (args != null) { for (int i = 0; i < args.Count; i++) { this.tw.Write("{0} ", this.source2String(args[i])); if (this.mdDecoder.IsPure(method, i)) { this.tw.Write(i.ToString()); } } } this.tw.Write(")"); if (extraVarargs != null) { this.tw.Write(" extra varargs types : "); for (int i = 0; i < extraVarargs.Count; i++) this.tw.Write("{0} ", this.typeReferencer(extraVarargs[i])); } this.tw.Write(" resultType : {0}", this.typeReferencer(this.mdDecoder.ReturnType(method))); this.tw.WriteLine(); return Unit.Value; } public Unit Jmp(APC pc, Method method, Unit data) { this.tw.WriteLine(" jmp {0}", this.mdDecoder.FullName(method)); return Unit.Value; } public Unit Ldftn(APC pc, Method method, Dest dest, Unit data) { this.tw.WriteLine(" {0} = ldftn {1}", this.dest2String(dest), this.mdDecoder.FullName(method)); return Unit.Value; } public Unit Calli<TypeList, ArgList>(APC pc, Type returnType, TypeList argTypes, bool tail, bool isInstance, Dest dest, Source fp, ArgList args, Unit data) where TypeList : IIndexable<Type> where ArgList : IIndexable<Source> { // We need to hash the names of the methods because some built-in methods have special treatments this.tw.Write(" {1} = {0}calli {2}(", tail ? "tail." : null, this.dest2String(dest), this.source2String(fp)); if (args != null) { for (int i = 0; i < args.Count; i++) { this.tw.Write("{0} ", this.source2String(args[i])); } } this.tw.Write(")"); this.tw.Write(" args types : "); for (int i = 0; i < argTypes.Count; i++) this.tw.Write("{0} ", this.typeReferencer(argTypes[i])); this.tw.WriteLine(" return type : {0}", this.typeReferencer(returnType)); return Unit.Value; } public Unit Ckfinite(APC pc, Dest dest, Source source, Unit data) { this.tw.WriteLine(" {0} = ckfinite {1}", this.dest2String(dest), this.source2String(source)); return Unit.Value; } public Unit Cpblk(APC pc, bool @volatile, Source destaddr, Source srcaddr, Source len, Unit data) { this.tw.WriteLine(" {0}cpblk {1} {2} {3}", @volatile ? "volatile." : null, this.source2String(destaddr), this.source2String(srcaddr), this.source2String(len)); return Unit.Value; } public Unit Endfilter(APC pc, Source decision, Unit data) { this.tw.WriteLine(" endfilter {0}", this.source2String(decision)); return Unit.Value; } public Unit Endfinally(APC pc, Unit data) { this.tw.WriteLine(" endfinally"); return Unit.Value; } public Unit Initblk(APC pc, bool @volatile, Source destaddr, Source value, Source len, Unit data) { this.tw.WriteLine(" {0}initblk {1} {2} {3}", @volatile ? "volatile." : null, this.source2String(destaddr), this.source2String(value), this.source2String(len)); return Unit.Value; } public Unit Ldarg(APC pc, Parameter argument, bool isOld, Dest dest, Unit data) { string isOldPrefix = isOld ? "old." : null; this.tw.WriteLine(" {1} = {2}ldarg {0}", this.mdDecoder.Name(argument), this.dest2String(dest), isOldPrefix); return Unit.Value; } public Unit Ldarga(APC pc, Parameter argument, bool isOld, Dest dest, Unit data) { string isOldPrefix = isOld ? "old." : null; this.tw.WriteLine(" {1} = {2}ldarga {0}", this.mdDecoder.Name(argument), this.dest2String(dest), isOldPrefix); return Unit.Value; } public Unit Ldind(APC pc, Type type, bool @volatile, Dest dest, Source ptr, Unit data) { this.tw.WriteLine(" {2} = {0}ldind {1} {3}", @volatile ? "volatile." : null, this.typeReferencer(type), this.dest2String(dest), this.source2String(ptr)); return Unit.Value; } public Unit Ldloc(APC pc, Local local, Dest dest, Unit data) { this.tw.WriteLine(" {1} = ldloc {0}", this.mdDecoder.Name(local), this.dest2String(dest)); return Unit.Value; } public Unit Ldloca(APC pc, Local local, Dest dest, Unit data) { this.tw.WriteLine(" {1} = ldloca {0}", this.mdDecoder.Name(local), this.dest2String(dest)); return Unit.Value; } public Unit Localloc(APC pc, Dest dest, Source size, Unit data) { this.tw.WriteLine(" {0} = localloc {1}", this.dest2String(dest), this.source2String(size)); return Unit.Value; } public Unit Nop(APC pc, Unit data) { this.tw.WriteLine(" nop"); return Unit.Value; } public Unit Pop(APC pc, Source source, Unit data) { this.tw.WriteLine(" pop {0}", this.source2String(source)); return Unit.Value; } public Unit Return(APC pc, Source source, Unit data) { this.tw.WriteLine(" ret {0}", this.source2String(source)); return Unit.Value; } public Unit Starg(APC pc, Parameter argument, Source source, Unit data) { this.tw.WriteLine(" starg {0} {1}", this.mdDecoder.Name(argument), this.source2String(source)); return Unit.Value; } public Unit Stind(APC pc, Type type, bool @volatile, Source ptr, Source value, Unit data) { this.tw.WriteLine(" {0}stind {1} {2} {3}", @volatile ? "volatile." : null, this.typeReferencer(type), this.source2String(ptr), this.source2String(value)); return Unit.Value; } public Unit Stloc(APC pc, Local local, Source source, Unit data) { this.tw.WriteLine(" stloc {0} {1}", this.mdDecoder.Name(local), this.source2String(source)); return Unit.Value; } public Unit Box(APC pc, Type type, Dest dest, Source source, Unit data) { this.tw.WriteLine(" {1} = box {0} {2}", this.typeReferencer(type), this.dest2String(dest), this.source2String(source)); return Unit.Value; } public Unit Castclass(APC pc, Type type, Dest dest, Source obj, Unit data) { this.tw.WriteLine(" {1} = castclass {0} {2}", this.typeReferencer(type), this.dest2String(dest), this.source2String(obj)); return Unit.Value; } public Unit Cpobj(APC pc, Type type, Source destptr, Source srcptr, Unit data) { this.tw.WriteLine(" cpobj {0} {1} {2}", this.typeReferencer(type), this.source2String(destptr), this.source2String(srcptr)); return Unit.Value; } public Unit Initobj(APC pc, Type type, Source ptr, Unit data) { this.tw.WriteLine(" initobj {0} {1}", this.typeReferencer(type), this.source2String(ptr)); return Unit.Value; } public Unit Ldelem(APC pc, Type type, Dest dest, Source array, Source index, Unit data) { this.tw.WriteLine(" {1} = ldelem {0} {2}[{3}]", this.typeReferencer(type), this.dest2String(dest), this.source2String(array), this.source2String(index)); return Unit.Value; } public Unit Ldelema(APC pc, Type type, bool @readonly, Dest dest, Source array, Source index, Unit data) { this.tw.WriteLine(" {2} = {0}ldelema {1} {3}[{4}]", @readonly ? "readonly." : null, this.typeReferencer(type), this.dest2String(dest), this.source2String(array), this.source2String(index)); return Unit.Value; } public Unit Ldfld(APC pc, Field field, bool @volatile, Dest dest, Source obj, Unit data) { this.tw.WriteLine(" {2} = {0}ldfld {1} {3} type:{4}", @volatile ? "volatile." : null, GetStringForField(field), this.dest2String(dest), this.source2String(obj), this.typeReferencer(this.mdDecoder.FieldType(field))); return Unit.Value; } public Unit Ldflda(APC pc, Field field, Dest dest, Source obj, Unit data) { this.tw.WriteLine(" {1} = ldflda {0} {2} type:{3}", GetStringForField(field), this.dest2String(dest), this.source2String(obj), this.typeReferencer(this.mdDecoder.FieldType(field))); return Unit.Value; } public Unit Ldlen(APC pc, Dest dest, Source array, Unit data) { this.tw.WriteLine(" {0} = ldlen {1}", this.dest2String(dest), this.source2String(array)); return Unit.Value; } public Unit Ldsfld(APC pc, Field field, bool @volatile, Dest dest, Unit data) { this.tw.WriteLine(" {2} = {0}ldsfld {1} type:{3}", @volatile ? "volatile." : null, GetStringForField(field), this.dest2String(dest), this.typeReferencer(this.mdDecoder.FieldType(field))); return Unit.Value; } public Unit Ldsflda(APC pc, Field field, Dest dest, Unit data) { this.tw.WriteLine(" {1} = ldsflda {0} type:{2}", GetStringForField(field), this.dest2String(dest), this.typeReferencer(this.mdDecoder.FieldType(field))); return Unit.Value; } public Unit Ldtypetoken(APC pc, Type type, Dest dest, Unit data) { this.tw.WriteLine(" {1} = ldtoken {0}", this.typeReferencer(type), this.dest2String(dest)); return Unit.Value; } public Unit Ldfieldtoken(APC pc, Field field, Dest dest, Unit data) { this.tw.WriteLine(" {1} = ldtoken {0}", GetStringForField(field), this.dest2String(dest)); return Unit.Value; } public Unit Ldmethodtoken(APC pc, Method method, Dest dest, Unit data) { this.tw.WriteLine(" {1} = ldtoken {0}", this.mdDecoder.FullName(method), this.dest2String(dest)); return Unit.Value; } public Unit Ldvirtftn(APC pc, Method method, Dest dest, Source obj, Unit data) { this.tw.WriteLine(" {1} = ldvirtftn {0} {2}", this.mdDecoder.FullName(method), this.dest2String(dest), this.source2String(obj)); return Unit.Value; } public Unit Mkrefany(APC pc, Type type, Dest dest, Source obj, Unit data) { this.tw.WriteLine(" {1} = mkrefany {0} {2}", this.typeReferencer(type), this.dest2String(dest), this.source2String(obj)); return Unit.Value; } public Unit Newarray<ArgList>(APC pc, Type type, Dest dest, ArgList len, Unit data) where ArgList : IIndexable<Source> { this.tw.Write(" {1} = newarray {0}[", this.typeReferencer(type), this.dest2String(dest)); for (int i = 0; i < len.Count; i++) { this.tw.Write("{0} ", this.source2String(len[i])); } this.tw.WriteLine(")"); return Unit.Value; } public Unit Newobj<ArgList>(APC pc, Method ctor, Dest dest, ArgList args, Unit data) where ArgList : IIndexable<Source> { this.tw.Write(" {1} = newobj {0}(", this.mdDecoder.FullName(ctor), this.dest2String(dest)); if (args != null) { for (int i = 0; i < args.Count; i++) { this.tw.Write("{0} ", this.source2String(args[i])); } } this.tw.WriteLine(") type: {0}", this.typeReferencer(this.mdDecoder.DeclaringType(ctor))); return Unit.Value; } public Unit Refanytype(APC pc, Dest dest, Source source, Unit data) { this.tw.WriteLine(" {0} = refanytype {1}", this.dest2String(dest), this.source2String(source)); return Unit.Value; } public Unit Refanyval(APC pc, Type type, Dest dest, Source source, Unit data) { this.tw.WriteLine(" {1} = refanyval {0} {2}", this.typeReferencer(type), this.dest2String(dest), this.source2String(source)); return Unit.Value; } public Unit Rethrow(APC pc, Unit data) { this.tw.WriteLine(" rethrow"); return Unit.Value; } public Unit Stelem(APC pc, Type type, Source array, Source index, Source value, Unit data) { this.tw.WriteLine(" stelem {0} {1}[{2}] = {3}", this.typeReferencer(type), this.source2String(array), this.source2String(index), this.source2String(value)); return Unit.Value; } public Unit Stfld(APC pc, Field field, bool @volatile, Source obj, Source value, Unit data) { this.tw.WriteLine(" {0}stfld {1} {2} {3} type:{4}", @volatile ? "volatile." : null, GetStringForField(field), this.source2String(obj), this.source2String(value), this.typeReferencer(this.mdDecoder.FieldType(field))); return Unit.Value; } public Unit Stsfld(APC pc, Field field, bool @volatile, Source value, Unit data) { this.tw.WriteLine(" {0}stsfld {1} {2} type:{3}", @volatile ? "volatile." : null, GetStringForField(field), this.source2String(value), this.typeReferencer(this.mdDecoder.FieldType(field))); return Unit.Value; } public Unit Throw(APC pc, Source exn, Unit data) { this.tw.WriteLine(" throw {0}", this.source2String(exn)); return Unit.Value; } public Unit Unbox(APC pc, Type type, Dest dest, Source obj, Unit data) { this.tw.WriteLine(" {1} = unbox {0} {2}", this.typeReferencer(type), this.dest2String(dest), this.source2String(obj)); return Unit.Value; } public Unit Unboxany(APC pc, Type type, Dest dest, Source obj, Unit data) { this.tw.WriteLine(" {1} = unbox_any {0} {2}", this.typeReferencer(type), this.dest2String(dest), this.source2String(obj)); return Unit.Value; } #endregion #region IVisitSynthIL<Label,Method,Type,Source,Dest,Unit,Unit> Members public Unit Entry(APC pc, Method method, Unit data) { this.tw.WriteLine(" method_entry {0}", this.mdDecoder.FullName(method)); if (this.contractDecoder.IsPure(method)) { this.tw.WriteLine("pure"); } var md =this.mdDecoder; var pos = this.mdDecoder.IsStatic(method) ? 0 : 1; foreach (var p in this.mdDecoder.Parameters(method).Enumerate()) { if (md.IsPure(method, pos++)) { this.tw.WriteLine(pos.ToString()); } this.tw.WriteLine(GetEnumValuesIfAny(md.ParameterType(p))); } return Unit.Value; } public Unit Assume(APC pc, string tag, Source condition, object provenance, Unit data) { // TODO: do we need to hash the provenance ? this.tw.WriteLine(" assume({0}) {1}", tag, this.source2String(condition)); return Unit.Value; } public Unit Assert(APC pc, string tag, Source condition, object provenance, Unit data) { // TODO: do we need to hash the provenance ? this.tw.WriteLine(" assert({0}) {1}", tag, this.source2String(condition)); return Unit.Value; } public Unit Ldstack(APC pc, int offset, Dest dest, Source source, bool isOld, Unit data) { this.tw.WriteLine(" {0} = {3}ldstack.{1} {2}", this.dest2String(dest), offset, this.source2String(source), isOld ? "old." : ""); return Unit.Value; } public Unit Ldstacka(APC pc, int offset, Dest dest, Source source, Type origParamType, bool isOld, Unit data) { this.tw.WriteLine(" {0} = {3}ldstacka.{1} {2}", this.dest2String(dest), offset, this.source2String(source), isOld ? "old." : ""); return Unit.Value; } public Unit Ldresult(APC pc, Type type, Dest dest, Source source, Unit data) { this.tw.WriteLine(" {0} = ldresult {1}", this.dest2String(dest), this.source2String(source)); return Unit.Value; } public Unit BeginOld(APC pc, APC matchingEnd, Unit data) { this.tw.WriteLine(" begin.old"); return Unit.Value; } public Unit EndOld(APC pc, APC matchingBegin, Type type, Dest dest, Source source, Unit data) { this.tw.WriteLine(" {0} = end.old {1} {2}", this.dest2String(dest), this.source2String(source), this.typeReferencer(type)); return Unit.Value; } #endregion #region IVisitExprIL<Label,Type,Source,Dest,Unit,Unit> Members public Unit Binary(APC pc, BinaryOperator op, Dest dest, Source s1, Source s2, Unit data) { this.tw.WriteLine(" {0} = {1} {2} {3}", this.dest2String(dest), this.source2String(s1), op.ToString(), this.source2String(s2)); return Unit.Value; } public Unit Isinst(APC pc, Type type, Dest dest, Source obj, Unit data) { this.tw.WriteLine(" {1} = isinst {0} {2}", this.typeReferencer(type), this.dest2String(dest), this.source2String(obj)); return Unit.Value; } public Unit Ldconst(APC pc, object constant, Type type, Dest dest, Unit data) { this.tw.WriteLine(" {1} = ldc ({2})'{0}'", constant.ToString(), this.dest2String(dest), this.typeReferencer(type)); return Unit.Value; } public Unit Ldnull(APC pc, Dest dest, Unit data) { this.tw.WriteLine(" {0} = ldnull", this.dest2String(dest)); return Unit.Value; } public Unit Sizeof(APC pc, Type type, Dest dest, Unit data) { int actualSize = mdDecoder.TypeSize(type); this.tw.WriteLine(" {1} = sizeof {0} ({2})", this.typeReferencer(type), this.dest2String(dest), actualSize); return Unit.Value; } public Unit Unary(APC pc, UnaryOperator op, bool overflow, bool unsigned, Dest dest, Source source, Unit data) { this.tw.WriteLine(" {3} = {2}{0}{1} {4}", overflow ? "_ovf" : null, unsigned ? "_un" : null, op.ToString(), this.dest2String(dest), this.source2String(source)); return Unit.Value; } #endregion #region Helpers private string GetEnumValuesIfAny(Type enumType) { List<int> enumValues; if (this.mdDecoder.IsEnumWithoutFlagAttribute(enumType) && this.mdDecoder.TryGetEnumValues(enumType, out enumValues)) { return string.Join(",", enumValues); } return String.Empty; } private string GetStringForField(Field field) { var isReadonly = mdDecoder.IsReadonly(field) ? "(readonly)" : null; return mdDecoder.FullName(field) + isReadonly; } #endregion } #region IDisposable Members public void Dispose() { this.tw.Dispose(); } #endregion } }
#region File Description //----------------------------------------------------------------------------- // BasicEffect.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; #endregion namespace Microsoft.Xna.Framework.Graphics { /// <summary> /// Built-in effect that supports optional texturing, vertex coloring, fog, and lighting. /// </summary> public class BasicEffect : Effect, IEffectMatrices, IEffectLights, IEffectFog { #region Effect Parameters EffectParameter textureParam; EffectParameter diffuseColorParam; EffectParameter emissiveColorParam; EffectParameter specularColorParam; EffectParameter specularPowerParam; EffectParameter eyePositionParam; EffectParameter fogColorParam; EffectParameter fogVectorParam; EffectParameter worldParam; EffectParameter worldInverseTransposeParam; EffectParameter worldViewProjParam; int _shaderIndex = -1; #endregion #region Fields bool lightingEnabled; bool preferPerPixelLighting; bool oneLight; bool fogEnabled; bool textureEnabled; bool vertexColorEnabled; Matrix world = Matrix.Identity; Matrix view = Matrix.Identity; Matrix projection = Matrix.Identity; Matrix worldView; Vector3 diffuseColor = Vector3.One; Vector3 emissiveColor = Vector3.Zero; Vector3 ambientLightColor = Vector3.Zero; float alpha = 1; DirectionalLight light0; DirectionalLight light1; DirectionalLight light2; float fogStart = 0; float fogEnd = 1; EffectDirtyFlags dirtyFlags = EffectDirtyFlags.All; static readonly byte[] Bytecode = LoadEffectResource( #if DIRECTX "Microsoft.Xna.Framework.Graphics.Effect.Resources.BasicEffect.dx11.mgfxo" #elif PSM "MonoGame.Framework.PSMobile.PSSuite.Graphics.Resources.BasicEffect.cgx" //FIXME: This shader is totally incomplete #else "Microsoft.Xna.Framework.Graphics.Effect.Resources.BasicEffect.ogl.mgfxo" #endif ); #endregion #region Public Properties /// <summary> /// Gets or sets the world matrix. /// </summary> public Matrix World { get { return world; } set { world = value; dirtyFlags |= EffectDirtyFlags.World | EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the view matrix. /// </summary> public Matrix View { get { return view; } set { view = value; dirtyFlags |= EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.EyePosition | EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the projection matrix. /// </summary> public Matrix Projection { get { return projection; } set { projection = value; dirtyFlags |= EffectDirtyFlags.WorldViewProj; } } /// <summary> /// Gets or sets the material diffuse color (range 0 to 1). /// </summary> public Vector3 DiffuseColor { get { return diffuseColor; } set { diffuseColor = value; dirtyFlags |= EffectDirtyFlags.MaterialColor; } } /// <summary> /// Gets or sets the material emissive color (range 0 to 1). /// </summary> public Vector3 EmissiveColor { get { return emissiveColor; } set { emissiveColor = value; dirtyFlags |= EffectDirtyFlags.MaterialColor; } } /// <summary> /// Gets or sets the material specular color (range 0 to 1). /// </summary> public Vector3 SpecularColor { get { return specularColorParam.GetValueVector3(); } set { specularColorParam.SetValue(value); } } /// <summary> /// Gets or sets the material specular power. /// </summary> public float SpecularPower { get { return specularPowerParam.GetValueSingle(); } set { specularPowerParam.SetValue(value); } } /// <summary> /// Gets or sets the material alpha. /// </summary> public float Alpha { get { return alpha; } set { alpha = value; dirtyFlags |= EffectDirtyFlags.MaterialColor; } } /// <summary> /// Gets or sets the lighting enable flag. /// </summary> public bool LightingEnabled { get { return lightingEnabled; } set { if (lightingEnabled != value) { lightingEnabled = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex | EffectDirtyFlags.MaterialColor; } } } /// <summary> /// Gets or sets the per-pixel lighting prefer flag. /// </summary> public bool PreferPerPixelLighting { get { return preferPerPixelLighting; } set { if (preferPerPixelLighting != value) { preferPerPixelLighting = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } } /// <summary> /// Gets or sets the ambient light color (range 0 to 1). /// </summary> public Vector3 AmbientLightColor { get { return ambientLightColor; } set { ambientLightColor = value; dirtyFlags |= EffectDirtyFlags.MaterialColor; } } /// <summary> /// Gets the first directional light. /// </summary> public DirectionalLight DirectionalLight0 { get { return light0; } } /// <summary> /// Gets the second directional light. /// </summary> public DirectionalLight DirectionalLight1 { get { return light1; } } /// <summary> /// Gets the third directional light. /// </summary> public DirectionalLight DirectionalLight2 { get { return light2; } } /// <summary> /// Gets or sets the fog enable flag. /// </summary> public bool FogEnabled { get { return fogEnabled; } set { if (fogEnabled != value) { fogEnabled = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex | EffectDirtyFlags.FogEnable; } } } /// <summary> /// Gets or sets the fog start distance. /// </summary> public float FogStart { get { return fogStart; } set { fogStart = value; dirtyFlags |= EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the fog end distance. /// </summary> public float FogEnd { get { return fogEnd; } set { fogEnd = value; dirtyFlags |= EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the fog color. /// </summary> public Vector3 FogColor { get { return fogColorParam.GetValueVector3(); } set { fogColorParam.SetValue(value); } } /// <summary> /// Gets or sets whether texturing is enabled. /// </summary> public bool TextureEnabled { get { return textureEnabled; } set { if (textureEnabled != value) { textureEnabled = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } } /// <summary> /// Gets or sets the current texture. /// </summary> public Texture2D Texture { get { return textureParam.GetValueTexture2D(); } set { textureParam.SetValue(value); } } /// <summary> /// Gets or sets whether vertex color is enabled. /// </summary> public bool VertexColorEnabled { get { return vertexColorEnabled; } set { if (vertexColorEnabled != value) { vertexColorEnabled = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } } #endregion #region Methods /// <summary> /// Creates a new BasicEffect with default parameter settings. /// </summary> public BasicEffect(GraphicsDevice device) : base(device, Bytecode) { CacheEffectParameters(null); DirectionalLight0.Enabled = true; SpecularColor = Vector3.One; SpecularPower = 16; } /// <summary> /// Creates a new BasicEffect by cloning parameter settings from an existing instance. /// </summary> protected BasicEffect(BasicEffect cloneSource) : base(cloneSource) { CacheEffectParameters(cloneSource); lightingEnabled = cloneSource.lightingEnabled; preferPerPixelLighting = cloneSource.preferPerPixelLighting; fogEnabled = cloneSource.fogEnabled; textureEnabled = cloneSource.textureEnabled; vertexColorEnabled = cloneSource.vertexColorEnabled; world = cloneSource.world; view = cloneSource.view; projection = cloneSource.projection; diffuseColor = cloneSource.diffuseColor; emissiveColor = cloneSource.emissiveColor; ambientLightColor = cloneSource.ambientLightColor; alpha = cloneSource.alpha; fogStart = cloneSource.fogStart; fogEnd = cloneSource.fogEnd; } /// <summary> /// Creates a clone of the current BasicEffect instance. /// </summary> public override Effect Clone() { return new BasicEffect(this); } /// <summary> /// Sets up the standard key/fill/back lighting rig. /// </summary> public void EnableDefaultLighting() { LightingEnabled = true; AmbientLightColor = EffectHelpers.EnableDefaultLighting(light0, light1, light2); } /// <summary> /// Looks up shortcut references to our effect parameters. /// </summary> void CacheEffectParameters(BasicEffect cloneSource) { textureParam = Parameters["Texture"]; diffuseColorParam = Parameters["DiffuseColor"]; emissiveColorParam = Parameters["EmissiveColor"]; specularColorParam = Parameters["SpecularColor"]; specularPowerParam = Parameters["SpecularPower"]; eyePositionParam = Parameters["EyePosition"]; fogColorParam = Parameters["FogColor"]; fogVectorParam = Parameters["FogVector"]; worldParam = Parameters["World"]; worldInverseTransposeParam = Parameters["WorldInverseTranspose"]; worldViewProjParam = Parameters["WorldViewProj"]; light0 = new DirectionalLight(Parameters["DirLight0Direction"], Parameters["DirLight0DiffuseColor"], Parameters["DirLight0SpecularColor"], (cloneSource != null) ? cloneSource.light0 : null); light1 = new DirectionalLight(Parameters["DirLight1Direction"], Parameters["DirLight1DiffuseColor"], Parameters["DirLight1SpecularColor"], (cloneSource != null) ? cloneSource.light1 : null); light2 = new DirectionalLight(Parameters["DirLight2Direction"], Parameters["DirLight2DiffuseColor"], Parameters["DirLight2SpecularColor"], (cloneSource != null) ? cloneSource.light2 : null); } /// <summary> /// Lazily computes derived parameter values immediately before applying the effect. /// </summary> protected internal override bool OnApply() { // Recompute the world+view+projection matrix or fog vector? dirtyFlags = EffectHelpers.SetWorldViewProjAndFog(dirtyFlags, ref world, ref view, ref projection, ref worldView, fogEnabled, fogStart, fogEnd, worldViewProjParam, fogVectorParam); // Recompute the diffuse/emissive/alpha material color parameters? if ((dirtyFlags & EffectDirtyFlags.MaterialColor) != 0) { EffectHelpers.SetMaterialColor(lightingEnabled, alpha, ref diffuseColor, ref emissiveColor, ref ambientLightColor, diffuseColorParam, emissiveColorParam); dirtyFlags &= ~EffectDirtyFlags.MaterialColor; } if (lightingEnabled) { // Recompute the world inverse transpose and eye position? dirtyFlags = EffectHelpers.SetLightingMatrices(dirtyFlags, ref world, ref view, worldParam, worldInverseTransposeParam, eyePositionParam); // Check if we can use the only-bother-with-the-first-light shader optimization. bool newOneLight = !light1.Enabled && !light2.Enabled; if (oneLight != newOneLight) { oneLight = newOneLight; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } // Recompute the shader index? if ((dirtyFlags & EffectDirtyFlags.ShaderIndex) != 0) { int shaderIndex = 0; if (!fogEnabled) shaderIndex += 1; if (vertexColorEnabled) shaderIndex += 2; if (textureEnabled) shaderIndex += 4; if (lightingEnabled) { if (preferPerPixelLighting) shaderIndex += 24; else if (oneLight) shaderIndex += 16; else shaderIndex += 8; } dirtyFlags &= ~EffectDirtyFlags.ShaderIndex; #if PSM #warning Major hack as PSM Shaders don't support multiple Techinques (yet) shaderIndex = 0; #endif if (_shaderIndex != shaderIndex) { _shaderIndex = shaderIndex; CurrentTechnique = Techniques[_shaderIndex]; return true; } } return false; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Linq.Parallel.Tests { public class SingleSingleOrDefaultTests { public static IEnumerable<object[]> SingleSpecificData(int[] counts) { Func<int, IEnumerable<int>> positions = x => new[] { 0, x / 2, Math.Max(0, x - 1) }.Distinct(); foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), positions)) yield return results; foreach (object[] results in Sources.Ranges(counts.Cast<int>(), positions)) yield return results; } public static IEnumerable<object[]> SingleData(int[] elements, int[] counts) { foreach (int element in elements) { foreach (object[] results in UnorderedSources.Ranges(element, counts.Cast<int>())) { yield return new object[] { results[0], results[1], element }; } foreach (object[] results in Sources.Ranges(element, counts.Cast<int>())) { yield return new object[] { results[0], results[1], element }; } } } // // Single and SingleOrDefault // [Theory] [MemberData(nameof(SingleData), new[] { 0, 2, 16, 1024 * 1024 }, new[] { 1 })] public static void Single(Labeled<ParallelQuery<int>> labeled, int count, int element) { ParallelQuery<int> query = labeled.Item; Assert.Equal(element, query.Single()); Assert.Equal(element, query.Single(x => true)); } [Theory] [MemberData(nameof(SingleData), new[] { 0, 2, 16, 1024 * 1024 }, new[] { 0, 1 })] public static void SingleOrDefault(Labeled<ParallelQuery<int>> labeled, int count, int element) { ParallelQuery<int> query = labeled.Item; Assert.Equal(count >= 1 ? element : default(int), query.SingleOrDefault()); Assert.Equal(count >= 1 ? element : default(int), query.SingleOrDefault(x => true)); } [Theory] [MemberData(nameof(SingleData), new[] { 0, 1024 * 1024 }, new[] { 0 })] public static void Single_Empty(Labeled<ParallelQuery<int>> labeled, int count, int element) { ParallelQuery<int> query = labeled.Item; Assert.Throws<InvalidOperationException>(() => query.Single()); Assert.Throws<InvalidOperationException>(() => query.Single(x => true)); } [Theory] [MemberData(nameof(SingleData), new[] { 0 }, new[] { 0, 1, 2, 16 })] public static void Single_NoMatch(Labeled<ParallelQuery<int>> labeled, int count, int element) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.Throws<InvalidOperationException>(() => query.Single(x => !seen.Add(x))); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SingleData), new[] { 0 }, new[] { 1024 * 4, 1024 * 1024 })] public static void Single_NoMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element) { Single_NoMatch(labeled, count, element); } [Theory] [MemberData(nameof(SingleData), new[] { 0 }, new[] { 0, 1, 2, 16 })] public static void SingleOrDefault_NoMatch(Labeled<ParallelQuery<int>> labeled, int count, int element) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.Equal(default(int), query.SingleOrDefault(x => !seen.Add(x))); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SingleData), new[] { 0 }, new[] { 1024 * 4, 1024 * 1024 })] public static void SingleOrDefault_NoMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element) { SingleOrDefault_NoMatch(labeled, count, element); } [Theory] [MemberData(nameof(SingleData), new[] { 0 }, new[] { 2, 16 })] public static void Single_AllMatch(Labeled<ParallelQuery<int>> labeled, int count, int element) { ParallelQuery<int> query = labeled.Item; Assert.Throws<InvalidOperationException>(() => query.Single(x => true)); } [Theory] [OuterLoop] [MemberData(nameof(SingleData), new[] { 0 }, new[] { 1024 * 4, 1024 * 1024 })] public static void Single_AllMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element) { Single_AllMatch(labeled, count, element); } [Theory] [MemberData(nameof(SingleData), new[] { 0 }, new[] { 2, 16 })] public static void SingleOrDefault_AllMatch(Labeled<ParallelQuery<int>> labeled, int count, int element) { ParallelQuery<int> query = labeled.Item; Assert.Throws<InvalidOperationException>(() => query.SingleOrDefault(x => true)); } [Theory] [OuterLoop] [MemberData(nameof(SingleData), new[] { 0 }, new[] { 1024 * 4, 1024 * 1024 })] public static void SingleOrDefault_AllMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element) { SingleOrDefault_AllMatch(labeled, count, element); } [Theory] [MemberData(nameof(SingleSpecificData), new[] { 1, 2, 16 })] public static void Single_OneMatch(Labeled<ParallelQuery<int>> labeled, int count, int element) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.Equal(element, query.Single(x => seen.Add(x) && x == element)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SingleSpecificData), new[] { 1024 * 4, 1024 * 1024 })] public static void Single_OneMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element) { Single_OneMatch(labeled, count, element); } [Theory] [MemberData(nameof(SingleSpecificData), new[] { 0, 1, 2, 16 })] public static void SingleOrDefault_OneMatch(Labeled<ParallelQuery<int>> labeled, int count, int element) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.Equal(element, query.SingleOrDefault(x => seen.Add(x) && x == element)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SingleSpecificData), new[] { 1024 * 4, 1024 * 1024 })] public static void SingleOrDefault_OneMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element) { SingleOrDefault_OneMatch(labeled, count, element); } [Fact] public static void Single_OperationCanceledException() { AssertThrows.EventuallyCanceled((source, canceler) => source.Single(x => { canceler(); return false; })); } [Fact] public static void SingleOrDefault_OperationCanceledException() { AssertThrows.EventuallyCanceled((source, canceler) => source.SingleOrDefault(x => { canceler(); return false; })); } [Fact] public static void Single_AggregateException_Wraps_OperationCanceledException() { AssertThrows.OtherTokenCanceled((source, canceler) => source.Single(x => { canceler(); return false; })); AssertThrows.SameTokenNotCanceled((source, canceler) => source.Single(x => { canceler(); return false; })); } [Fact] public static void SingleOrDefault_AggregateException_Wraps_OperationCanceledException() { AssertThrows.OtherTokenCanceled((source, canceler) => source.SingleOrDefault(x => { canceler(); return false; })); AssertThrows.SameTokenNotCanceled((source, canceler) => source.SingleOrDefault(x => { canceler(); return false; })); } [Fact] public static void Single_OperationCanceledException_PreCanceled() { AssertThrows.AlreadyCanceled(source => source.Single()); AssertThrows.AlreadyCanceled(source => source.Single(x => true)); } [Fact] public static void SingleOrDefault_OperationCanceledException_PreCanceled() { AssertThrows.AlreadyCanceled(source => source.SingleOrDefault()); AssertThrows.AlreadyCanceled(source => source.SingleOrDefault(x => true)); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 1 }, MemberType = typeof(UnorderedSources))] public static void Single_AggregateException(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Single(x => { throw new DeliberateTestException(); })); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.SingleOrDefault(x => { throw new DeliberateTestException(); })); } [Fact] public static void Single_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).Single()); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).SingleOrDefault()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().Single(null)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().SingleOrDefault(null)); } } }
//--------------------------------------------------------------------------- // File: ButtonChrome.cs // // Description: // Implementation of thick chrome for "full figured" buttons in Aero. // // Copyright (C) by Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System.Windows.Shapes; using System.Windows.Controls; using System.Diagnostics; using System.Threading; using System.ComponentModel; using System.Windows; using System.Windows.Media; using System.Windows.Media.Animation; using MS.Internal; using System; using System.Runtime.InteropServices; using System.Security; namespace Microsoft.Windows.Themes { /// <summary> /// The ButtonChrome element /// This element is a theme-specific type that is used as an optimization /// for a common complex rendering used in Aero /// /// </summary> public sealed class ButtonChrome : Decorator { #region Constructors static ButtonChrome() { IsEnabledProperty.OverrideMetadata(typeof(ButtonChrome), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsRender)); } /// <summary> /// Instantiates a new instance of a ButtonChrome with no parent element. /// </summary> /// <ExternalAPI/> public ButtonChrome() { } #endregion Constructors #region Dynamic Properties /// <summary> /// DependencyProperty for <see cref="Background" /> property. /// </summary> public static readonly DependencyProperty BackgroundProperty = Control.BackgroundProperty.AddOwner( typeof(ButtonChrome), new FrameworkPropertyMetadata( null, FrameworkPropertyMetadataOptions.AffectsRender)); /// <summary> /// The Background property defines the brush used to fill the background of the button. /// </summary> public Brush Background { get { return (Brush) GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value); } } /// <summary> /// DependencyProperty for <see cref="BorderBrush" /> property. /// </summary> public static readonly DependencyProperty BorderBrushProperty = Border.BorderBrushProperty.AddOwner( typeof(ButtonChrome), new FrameworkPropertyMetadata( null, FrameworkPropertyMetadataOptions.AffectsRender)); /// <summary> /// The BorderBrush property defines the brush used to draw the outer border. /// </summary> public Brush BorderBrush { get { return (Brush) GetValue(BorderBrushProperty); } set { SetValue(BorderBrushProperty, value); } } /// <summary> /// DependencyProperty for <see cref="RenderDefaulted" /> property. /// </summary> public static readonly DependencyProperty RenderDefaultedProperty = DependencyProperty.Register("RenderDefaulted", typeof(bool), typeof(ButtonChrome), new FrameworkPropertyMetadata( false, new PropertyChangedCallback(OnRenderDefaultedChanged))); /// <summary> /// When true the chrome renders with a mouse over look. /// </summary> public bool RenderDefaulted { get { return (bool)GetValue(RenderDefaultedProperty); } set { SetValue(RenderDefaultedProperty, value); } } private static void OnRenderDefaultedChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ButtonChrome chrome = ((ButtonChrome)o); if (chrome.Animates) { if (((bool)e.NewValue)) { if (chrome._localResources == null) { chrome._localResources = new LocalResources(); chrome.InvalidateVisual(); } Duration duration = new Duration(TimeSpan.FromSeconds(0.3)); ColorAnimation ca = new ColorAnimation(Color.FromArgb(0xF9, 0x00, 0xCC, 0xFF), duration); GradientStopCollection gsc = ((LinearGradientBrush)chrome.InnerBorderPen.Brush).GradientStops; gsc[0].BeginAnimation(GradientStop.ColorProperty, ca); gsc[1].BeginAnimation(GradientStop.ColorProperty, ca); if (!chrome.RenderPressed) { // Create a repeating animation like: // __/ \__/ \__/ \__... DoubleAnimationUsingKeyFrames daukf = new DoubleAnimationUsingKeyFrames(); daukf.KeyFrames.Add(new LinearDoubleKeyFrame(1.0, TimeSpan.FromSeconds(0.5))); daukf.KeyFrames.Add(new DiscreteDoubleKeyFrame(1.0, TimeSpan.FromSeconds(0.75))); daukf.KeyFrames.Add(new LinearDoubleKeyFrame(0.0, TimeSpan.FromSeconds(2.0))); daukf.RepeatBehavior = RepeatBehavior.Forever; DoubleAnimationUsingKeyFrames.SetDesiredFrameRate(daukf, 10); chrome.BackgroundOverlay.BeginAnimation(LinearGradientBrush.OpacityProperty, daukf); chrome.BorderOverlayPen.Brush.BeginAnimation(SolidColorBrush.OpacityProperty, daukf); } } else if (chrome._localResources == null) { if (!chrome.RenderPressed) { chrome.InvalidateVisual(); } } else { Duration duration = new Duration(TimeSpan.FromSeconds(0.2)); if (!chrome.RenderPressed) { DoubleAnimation da = new DoubleAnimation(); da.Duration = duration; chrome.BorderOverlayPen.Brush.BeginAnimation(SolidColorBrush.OpacityProperty, da); chrome.BackgroundOverlay.BeginAnimation(LinearGradientBrush.OpacityProperty, da); } ColorAnimation ca = new ColorAnimation(); ca.Duration = duration; GradientStopCollection gsc = ((LinearGradientBrush)chrome.InnerBorderPen.Brush).GradientStops; gsc[0].BeginAnimation(GradientStop.ColorProperty, ca); gsc[1].BeginAnimation(GradientStop.ColorProperty, ca); } } else { chrome._localResources = null; chrome.InvalidateVisual(); } } /// <summary> /// DependencyProperty for <see cref="RenderMouseOver" /> property. /// </summary> public static readonly DependencyProperty RenderMouseOverProperty = DependencyProperty.Register("RenderMouseOver", typeof(bool), typeof(ButtonChrome), new FrameworkPropertyMetadata( false, new PropertyChangedCallback(OnRenderMouseOverChanged))); /// <summary> /// When true the chrome renders with a mouse over look. /// </summary> public bool RenderMouseOver { get { return (bool)GetValue(RenderMouseOverProperty); } set { SetValue(RenderMouseOverProperty, value); } } private static void OnRenderMouseOverChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ButtonChrome chrome = ((ButtonChrome)o); if (chrome.Animates) { if (!chrome.RenderPressed) { if (((bool)e.NewValue)) { if (chrome._localResources == null) { chrome._localResources = new LocalResources(); chrome.InvalidateVisual(); } Duration duration = new Duration(TimeSpan.FromSeconds(0.3)); DoubleAnimation da = new DoubleAnimation(1, duration); chrome.BorderOverlayPen.Brush.BeginAnimation(SolidColorBrush.OpacityProperty, da); chrome.BackgroundOverlay.BeginAnimation(LinearGradientBrush.OpacityProperty, da); } else if (chrome._localResources == null) { chrome.InvalidateVisual(); } else { if (chrome.RenderDefaulted) { // Since the mouse was over the button the opacity should be 1.0 // Create a repeating animation like: // \__/ \__/ \__/ \_... // But if the user quickly mouses over a button, the opacity may not be 1 yet // so the first keyframe brings the opacity to 1 double currentOpacity = chrome.BackgroundOverlay.Opacity; // This is the time needed to complete the animation to 1: double to1 = (1.0 - currentOpacity) * 0.5; DoubleAnimationUsingKeyFrames daukf = new DoubleAnimationUsingKeyFrames(); daukf.KeyFrames.Add(new LinearDoubleKeyFrame(1.0, TimeSpan.FromSeconds(to1))); daukf.KeyFrames.Add(new DiscreteDoubleKeyFrame(1.0, TimeSpan.FromSeconds(to1 + 0.25))); daukf.KeyFrames.Add(new LinearDoubleKeyFrame(0.0, TimeSpan.FromSeconds(to1 + 1.5))); daukf.KeyFrames.Add(new LinearDoubleKeyFrame(currentOpacity, TimeSpan.FromSeconds(2))); daukf.RepeatBehavior = RepeatBehavior.Forever; DoubleAnimationUsingKeyFrames.SetDesiredFrameRate(daukf, 10); chrome.BackgroundOverlay.BeginAnimation(LinearGradientBrush.OpacityProperty, daukf); chrome.BorderOverlayPen.Brush.BeginAnimation(SolidColorBrush.OpacityProperty, daukf); } else { Duration duration = new Duration(TimeSpan.FromSeconds(0.2)); DoubleAnimation da = new DoubleAnimation(); da.Duration = duration; chrome.BackgroundOverlay.BeginAnimation(SolidColorBrush.OpacityProperty, da); chrome.BorderOverlayPen.Brush.BeginAnimation(SolidColorBrush.OpacityProperty, da); } } } } else { chrome._localResources = null; chrome.InvalidateVisual(); } } /// <summary> /// DependencyProperty for <see cref="RenderPressed" /> property. /// </summary> public static readonly DependencyProperty RenderPressedProperty = DependencyProperty.Register("RenderPressed", typeof(bool), typeof(ButtonChrome), new FrameworkPropertyMetadata( false, new PropertyChangedCallback(OnRenderPressedChanged))); /// <summary> /// When true the chrome renders with a pressed look. /// </summary> public bool RenderPressed { get { return (bool)GetValue(RenderPressedProperty); } set { SetValue(RenderPressedProperty, value); } } private static void OnRenderPressedChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ButtonChrome chrome = ((ButtonChrome)o); if (chrome.Animates) { if (((bool)e.NewValue)) { if (chrome._localResources == null) { chrome._localResources = new LocalResources(); chrome.InvalidateVisual(); } Duration duration = new Duration(TimeSpan.FromSeconds(0.1)); DoubleAnimation da = new DoubleAnimation(1, duration); chrome.BackgroundOverlay.BeginAnimation(SolidColorBrush.OpacityProperty, da); chrome.BorderOverlayPen.Brush.BeginAnimation(SolidColorBrush.OpacityProperty, da); chrome.LeftDropShadowBrush.BeginAnimation(LinearGradientBrush.OpacityProperty, da); chrome.TopDropShadowBrush.BeginAnimation(LinearGradientBrush.OpacityProperty, da); da = new DoubleAnimation(0, duration); chrome.InnerBorderPen.Brush.BeginAnimation(LinearGradientBrush.OpacityProperty, da); ColorAnimation ca = new ColorAnimation(Color.FromRgb(0xC2, 0xE4, 0xF6), duration); GradientStopCollection gsc = ((LinearGradientBrush)chrome.BackgroundOverlay).GradientStops; gsc[0].BeginAnimation(GradientStop.ColorProperty, ca); gsc[1].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0xAB, 0xDA, 0xF3), duration); gsc[2].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0x90, 0xCB, 0xEB), duration); gsc[3].BeginAnimation(GradientStop.ColorProperty, ca); ca = new ColorAnimation(Color.FromRgb(0x2C, 0x62, 0x8B), duration); chrome.BorderOverlayPen.Brush.BeginAnimation(SolidColorBrush.ColorProperty, ca); } else if (chrome._localResources == null) { chrome.InvalidateVisual(); } else { bool renderMouseOver = chrome.RenderMouseOver; Duration duration = new Duration(TimeSpan.FromSeconds(0.1)); DoubleAnimation da = new DoubleAnimation(); da.Duration = duration; chrome.LeftDropShadowBrush.BeginAnimation(LinearGradientBrush.OpacityProperty, da); chrome.TopDropShadowBrush.BeginAnimation(LinearGradientBrush.OpacityProperty, da); chrome.InnerBorderPen.Brush.BeginAnimation(LinearGradientBrush.OpacityProperty, da); if (!renderMouseOver) { chrome.BorderOverlayPen.Brush.BeginAnimation(SolidColorBrush.OpacityProperty, da); chrome.BackgroundOverlay.BeginAnimation(SolidColorBrush.OpacityProperty, da); } ColorAnimation ca = new ColorAnimation(); ca.Duration = duration; chrome.BorderOverlayPen.Brush.BeginAnimation(SolidColorBrush.ColorProperty, ca); GradientStopCollection gsc = ((LinearGradientBrush)chrome.BackgroundOverlay).GradientStops; gsc[0].BeginAnimation(GradientStop.ColorProperty, ca); gsc[1].BeginAnimation(GradientStop.ColorProperty, ca); gsc[2].BeginAnimation(GradientStop.ColorProperty, ca); gsc[3].BeginAnimation(GradientStop.ColorProperty, ca); } } else { chrome._localResources = null; chrome.InvalidateVisual(); } } /// <summary> /// DependencyProperty for <see cref="RoundCorners" /> property. /// </summary> public static readonly DependencyProperty RoundCornersProperty = DependencyProperty.Register("RoundCorners", typeof(bool), typeof(ButtonChrome), new FrameworkPropertyMetadata( true, FrameworkPropertyMetadataOptions.AffectsRender)); /// <summary> /// When true, the left border will have round corners, otherwise they will be square. /// </summary> public bool RoundCorners { get { return (bool)GetValue(RoundCornersProperty); } set { SetValue(RoundCornersProperty, value); } } #endregion Dynamic Properties #region Protected Methods /// <summary> /// Updates DesiredSize of the ButtonChrome. Called by parent UIElement. This is the first pass of layout. /// </summary> /// <remarks> /// ButtonChrome basically inflates the desired size of its one child by 2 on all four sides /// </remarks> /// <param name="availableSize">Available size is an "upper limit" that the return value should not exceed.</param> /// <returns>The ButtonChrome's desired size.</returns> protected override Size MeasureOverride(Size availableSize) { Size desired; UIElement child = Child; if (child != null) { Size childConstraint = new Size(); bool isWidthTooSmall = (availableSize.Width < 4.0); bool isHeightTooSmall = (availableSize.Height < 4.0); if (!isWidthTooSmall) { childConstraint.Width = availableSize.Width - 4.0; } if (!isHeightTooSmall) { childConstraint.Height = availableSize.Height - 4.0; } child.Measure(childConstraint); desired = child.DesiredSize; if (!isWidthTooSmall) { desired.Width += 4.0; } if (!isHeightTooSmall) { desired.Height += 4.0; } } else { desired = new Size(Math.Min(4.0, availableSize.Width), Math.Min(4.0, availableSize.Height)); } return desired; } /// <summary> /// ButtonChrome computes the position of its single child inside child's Margin and calls Arrange /// on the child. /// </summary> /// <remarks> /// ButtonChrome basically inflates the desired size of its one child by 2 on all four sides /// </remarks> /// <param name="finalSize">Size the ContentPresenter will assume.</param> protected override Size ArrangeOverride(Size finalSize) { Rect childArrangeRect = new Rect(); childArrangeRect.Width = Math.Max(0d, finalSize.Width - 4.0); childArrangeRect.Height = Math.Max(0d, finalSize.Height - 4.0); childArrangeRect.X = (finalSize.Width - childArrangeRect.Width) * 0.5; childArrangeRect.Y = (finalSize.Height - childArrangeRect.Height) * 0.5; UIElement child = Child; if (child != null) { child.Arrange(childArrangeRect); } return finalSize; } /// <summary> /// Render callback. /// </summary> protected override void OnRender(DrawingContext drawingContext) { Rect bounds = new Rect(0, 0, ActualWidth, ActualHeight); // Draw Background DrawBackground(drawingContext, ref bounds); // Draw Border dropshadows DrawDropShadows(drawingContext, ref bounds); // Draw outer border DrawBorder(drawingContext, ref bounds); // Draw innerborder DrawInnerBorder(drawingContext, ref bounds); } private void DrawBackground(DrawingContext dc, ref Rect bounds) { if (!IsEnabled && !RoundCorners) return; Brush fill = Background; if ((bounds.Width > 4.0) && (bounds.Height > 4.0)) { Rect backgroundRect = new Rect(bounds.Left + 1.0, bounds.Top + 1.0, bounds.Width - 2.0, bounds.Height - 2.0); // Draw Background if (fill != null) dc.DrawRectangle(fill, null, backgroundRect); // Draw BackgroundOverlay fill = BackgroundOverlay; if( fill != null) dc.DrawRectangle(fill, null, backgroundRect); } } // Draw the Pressed dropshadows private void DrawDropShadows(DrawingContext dc, ref Rect bounds) { if ((bounds.Width > 4.0) && (bounds.Height > 4.0)) { Brush leftShadow = LeftDropShadowBrush; if (leftShadow != null) { dc.DrawRectangle(leftShadow, null, new Rect(1.0, 1.0, 2.0, bounds.Bottom - 2.0)); } Brush topShadow = TopDropShadowBrush; if (topShadow != null) { dc.DrawRectangle(topShadow, null, new Rect(1.0, 1.0, bounds.Right - 2.0, 2.0)); } } } // Draw the main border private void DrawBorder(DrawingContext dc, ref Rect bounds) { if ((bounds.Width >= 5.0) && (bounds.Height >= 5.0)) { Brush border = BorderBrush; Pen pen = null; if (border != null) { if (_commonBorderPen == null) // Common case, if non-null, avoid the lock { lock (_resourceAccess ) // If non-null, lock to create the pen for thread safety { if (_commonBorderPen == null) // Check again in case _pen was created within the last line { // Assume that the first render of Button uses the most common brush for the app. // This breaks down if (a) the first Button is disabled, (b) the first Button is // customized, or (c) ButtonChrome becomes more broadly used than just on Button. // // If these cons sufficiently weaken the effectiveness of this cache, then we need // to build a larger brush-to-pen mapping cache. // If the brush is not already frozen, we need to create our own // copy. Otherwise we will inadvertently freeze the user's // BorderBrush when we freeze the pen below. if (!border.IsFrozen && border.CanFreeze) { border = border.Clone(); border.Freeze(); } Pen commonPen = new Pen(border, 1); if (commonPen.CanFreeze) { // Only save frozen pens, some brushes such as VisualBrush // can not be frozen commonPen.Freeze(); _commonBorderPen = commonPen; } } } } if (_commonBorderPen != null && border == _commonBorderPen.Brush) { pen = _commonBorderPen; } else { if (!border.IsFrozen && border.CanFreeze) { border = border.Clone(); border.Freeze(); } pen = new Pen(border, 1); if (pen.CanFreeze) { pen.Freeze(); } } } Pen overlayPen = BorderOverlayPen; if (pen != null || overlayPen != null) { if (RoundCorners) { Rect rect = new Rect(bounds.Left + 0.5, bounds.Top + 0.5, bounds.Width - 1.0, bounds.Height - 1.0); if (IsEnabled && pen != null) dc.DrawRoundedRectangle(null, pen, rect, 2.75, 2.75); if (overlayPen != null) dc.DrawRoundedRectangle(null, overlayPen, rect, 2.75, 2.75); } else { // Left side is flat, have to generate a geometry because // DrawRoundedRectangle does not let you specify per corner radii PathFigure borderFigure = new PathFigure(); borderFigure.StartPoint = new Point(0.5, 0.5); borderFigure.Segments.Add(new LineSegment(new Point(0.5, bounds.Bottom - 0.5), true)); borderFigure.Segments.Add(new LineSegment(new Point(bounds.Right - 2.5, bounds.Bottom - 0.5), true)); borderFigure.Segments.Add(new ArcSegment(new Point(bounds.Right - 0.5, bounds.Bottom - 2.5), new Size(2.0, 2.0), 0.0, false, SweepDirection.Counterclockwise, true)); borderFigure.Segments.Add(new LineSegment(new Point(bounds.Right - 0.5, bounds.Top + 2.5), true)); borderFigure.Segments.Add(new ArcSegment(new Point(bounds.Right - 2.5, bounds.Top + 0.5), new Size(2.0, 2.0), 0.0, false, SweepDirection.Counterclockwise, true)); borderFigure.IsClosed = true; PathGeometry borderGeometry = new PathGeometry(); borderGeometry.Figures.Add(borderFigure); if (IsEnabled && pen != null) dc.DrawGeometry(null, pen, borderGeometry); if (overlayPen != null) dc.DrawGeometry(null, overlayPen, borderGeometry); } } } } // Draw the inner border private void DrawInnerBorder(DrawingContext dc, ref Rect bounds) { if (!IsEnabled && !RoundCorners) return; if ((bounds.Width >= 4.0) && (bounds.Height >= 4.0)) { Pen innerBorder = InnerBorderPen; if (innerBorder != null) { dc.DrawRoundedRectangle(null, innerBorder, new Rect(bounds.Left + 1.5, bounds.Top + 1.5, bounds.Width - 3.0, bounds.Height - 3.0), 1.75, 1.75); } } } #endregion #region Private Properties // // This property // 1. Finds the correct initial size for the _effectiveValues store on the current DependencyObject // 2. This is a performance optimization // internal override int EffectiveValuesInitialSize { get { return 9; } } private bool Animates { get { return SystemParameters.PowerLineStatus == PowerLineStatus.Online && SystemParameters.ClientAreaAnimation && RenderCapability.Tier > 0 && IsEnabled; } } private static LinearGradientBrush CommonHoverBackgroundOverlay { get { if (_commonHoverBackgroundOverlay == null) { lock (_resourceAccess) { if (_commonHoverBackgroundOverlay == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(0, 1); temp.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xEA, 0xF6, 0xFD), 0)); temp.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xD9, 0xF0, 0xFC), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xBE, 0xE6, 0xFD), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xA7, 0xD9, 0xF5), 1)); temp.Freeze(); // Static field must not be set until the local has been frozen _commonHoverBackgroundOverlay = temp; } } } return _commonHoverBackgroundOverlay; } } private static LinearGradientBrush CommonPressedBackgroundOverlay { get { if (_commonPressedBackgroundOverlay == null) { lock (_resourceAccess) { if (_commonPressedBackgroundOverlay == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(0, 1); temp.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xC2, 0xE4, 0xF6), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xAB, 0xDA, 0xF3), 0.5)); temp.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0x90, 0xCB, 0xEB), 1)); temp.Freeze(); _commonPressedBackgroundOverlay = temp; } } } return _commonPressedBackgroundOverlay; } } private static SolidColorBrush CommonDisabledBackgroundOverlay { get { if (_commonDisabledBackgroundOverlay == null) { lock (_resourceAccess) { if (_commonDisabledBackgroundOverlay == null) { SolidColorBrush temp = new SolidColorBrush(Color.FromRgb(0xF4, 0xF4, 0xF4)); temp.Freeze(); _commonDisabledBackgroundOverlay = temp; } } } return _commonDisabledBackgroundOverlay; } } private Brush BackgroundOverlay { get { if (!IsEnabled) { return CommonDisabledBackgroundOverlay; } if (!Animates) { if (RenderPressed) { return CommonPressedBackgroundOverlay; } else if (RenderMouseOver) { return CommonHoverBackgroundOverlay; } else { return null; } } if (_localResources != null) { if (_localResources.BackgroundOverlay == null) { _localResources.BackgroundOverlay = CommonHoverBackgroundOverlay.Clone(); _localResources.BackgroundOverlay.Opacity = 0; } return _localResources.BackgroundOverlay; } else { return null; } } } private static Pen CommonHoverBorderOverlay { get { if (_commonHoverBorderOverlay == null) { lock (_resourceAccess) { if (_commonHoverBorderOverlay == null) { Pen temp = new Pen(); temp.Thickness = 1; temp.Brush = new SolidColorBrush(Color.FromRgb(0x3C, 0x7F, 0xB1)); temp.Freeze(); _commonHoverBorderOverlay = temp; } } } return _commonHoverBorderOverlay; } } private static Pen CommonPressedBorderOverlay { get { if (_commonPressedBorderOverlay == null) { lock (_resourceAccess) { if (_commonPressedBorderOverlay == null) { Pen temp = new Pen(); temp.Thickness = 1; temp.Brush = new SolidColorBrush(Color.FromRgb(0x2C, 0x62, 0x8B)); temp.Freeze(); _commonPressedBorderOverlay = temp; } } } return _commonPressedBorderOverlay; } } private static Pen CommonDisabledBorderOverlay { get { if (_commonDisabledBorderOverlay == null) { lock (_resourceAccess) { if (_commonDisabledBorderOverlay == null) { Pen temp = new Pen(); temp.Thickness = 1; temp.Brush = new SolidColorBrush(Color.FromRgb(0xAD, 0xB2, 0xB5)); temp.Freeze(); _commonDisabledBorderOverlay = temp; } } } return _commonDisabledBorderOverlay; } } private Pen BorderOverlayPen { get { if (!IsEnabled) { if (RoundCorners) { return CommonDisabledBorderOverlay; } else { return null; } } if (!Animates) { if (RenderPressed) { return CommonPressedBorderOverlay; } else if (RenderMouseOver) { return CommonHoverBorderOverlay; } else { return null; } } if (_localResources != null) { if (_localResources.BorderOverlayPen == null) { _localResources.BorderOverlayPen = CommonHoverBorderOverlay.Clone(); _localResources.BorderOverlayPen.Brush.Opacity = 0; } return _localResources.BorderOverlayPen; } else { return null; } } } private static Pen CommonInnerBorderPen { get { if (_commonInnerBorderPen == null) { lock (_resourceAccess) { if (_commonInnerBorderPen == null) { Pen temp = new Pen(); temp.Thickness = 1; LinearGradientBrush brush = new LinearGradientBrush(); brush.StartPoint = new Point(0,0); brush.EndPoint = new Point(0,1); brush.GradientStops.Add(new GradientStop(Color.FromArgb(0xFA,0xFF,0xFF,0xFF), 0)); brush.GradientStops.Add(new GradientStop(Color.FromArgb(0x85,0xFF,0xFF,0xFF), 1)); temp.Brush = brush; temp.Freeze(); _commonInnerBorderPen = temp; } } } return _commonInnerBorderPen; } } private static Pen CommonDefaultedInnerBorderPen { get { if (_commonDefaultedInnerBorderPen == null) { lock (_resourceAccess) { if (_commonDefaultedInnerBorderPen == null) { Pen temp = new Pen(); temp.Thickness = 1; temp.Brush = new SolidColorBrush(Color.FromArgb(0xF9, 0x00, 0xCC, 0xFF)); temp.Freeze(); _commonDefaultedInnerBorderPen = temp; } } } return _commonDefaultedInnerBorderPen; } } private Pen InnerBorderPen { get { if (!IsEnabled) { return CommonInnerBorderPen; } if (!Animates) { if (RenderPressed) { return null; } else if (RenderDefaulted) { return CommonDefaultedInnerBorderPen; } else { return CommonInnerBorderPen; } } if (_localResources != null) { if (_localResources.InnerBorderPen == null) { _localResources.InnerBorderPen = CommonInnerBorderPen.Clone(); } return _localResources.InnerBorderPen; } else { return CommonInnerBorderPen; } } } private static LinearGradientBrush CommonPressedLeftDropShadowBrush { get { if (_commonPressedLeftDropShadowBrush == null) { lock (_resourceAccess) { if (_commonPressedLeftDropShadowBrush == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(1, 0); temp.GradientStops.Add(new GradientStop(Color.FromArgb(0x80, 0x33, 0x33, 0x33), 0)); temp.GradientStops.Add(new GradientStop(Color.FromArgb(0x00, 0x33, 0x33, 0x33), 1)); temp.Freeze(); _commonPressedLeftDropShadowBrush = temp; } } } return _commonPressedLeftDropShadowBrush; } } private LinearGradientBrush LeftDropShadowBrush { get { if (!IsEnabled) { return null; } if (!Animates) { if (RenderPressed) { return CommonPressedLeftDropShadowBrush; } else { return null; } } if (_localResources != null) { if (_localResources.LeftDropShadowBrush == null) { _localResources.LeftDropShadowBrush = CommonPressedLeftDropShadowBrush.Clone(); _localResources.LeftDropShadowBrush.Opacity = 0; } return _localResources.LeftDropShadowBrush; } else { return null; } } } private static LinearGradientBrush CommonPressedTopDropShadowBrush { get { if (_commonPressedTopDropShadowBrush == null) { lock (_resourceAccess) { if (_commonPressedTopDropShadowBrush == null) { LinearGradientBrush temp = new LinearGradientBrush(); temp.StartPoint = new Point(0, 0); temp.EndPoint = new Point(0, 1); temp.GradientStops.Add(new GradientStop(Color.FromArgb(0x80, 0x33, 0x33, 0x33), 0)); temp.GradientStops.Add(new GradientStop(Color.FromArgb(0x00, 0x33, 0x33, 0x33), 1)); temp.Freeze(); _commonPressedTopDropShadowBrush = temp; } } } return _commonPressedTopDropShadowBrush; } } private LinearGradientBrush TopDropShadowBrush { get { if (!IsEnabled) { return null; } if (!Animates) { if (RenderPressed) { return CommonPressedTopDropShadowBrush; } else { return null; } } if (_localResources != null) { if (_localResources.TopDropShadowBrush == null) { _localResources.TopDropShadowBrush = CommonPressedTopDropShadowBrush.Clone(); _localResources.TopDropShadowBrush.Opacity = 0; } return _localResources.TopDropShadowBrush; } else { return null; } } } // Common LocalResources private static Pen _commonBorderPen; private static Pen _commonInnerBorderPen; private static Pen _commonDisabledBorderOverlay; private static SolidColorBrush _commonDisabledBackgroundOverlay; private static Pen _commonDefaultedInnerBorderPen; private static LinearGradientBrush _commonHoverBackgroundOverlay; private static Pen _commonHoverBorderOverlay; private static LinearGradientBrush _commonPressedBackgroundOverlay; private static Pen _commonPressedBorderOverlay; private static LinearGradientBrush _commonPressedLeftDropShadowBrush; private static LinearGradientBrush _commonPressedTopDropShadowBrush; private static object _resourceAccess = new object(); // Per instance resources private LocalResources _localResources; private class LocalResources { public Pen BorderOverlayPen; public Pen InnerBorderPen; public LinearGradientBrush BackgroundOverlay; public LinearGradientBrush LeftDropShadowBrush; public LinearGradientBrush TopDropShadowBrush; } #endregion } }
using System; using System.Collections.Generic; /* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace com.google.zxing.qrcode.detector { using NotFoundException = com.google.zxing.NotFoundException; using ResultPointCallback = com.google.zxing.ResultPointCallback; using BitMatrix = com.google.zxing.common.BitMatrix; /// <summary> /// <p>This class attempts to find alignment patterns in a QR Code. Alignment patterns look like finder /// patterns but are smaller and appear at regular intervals throughout the image.</p> /// /// <p>At the moment this only looks for the bottom-right alignment pattern.</p> /// /// <p>This is mostly a simplified copy of <seealso cref="FinderPatternFinder"/>. It is copied, /// pasted and stripped down here for maximum performance but does unfortunately duplicate /// some code.</p> /// /// <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.</p> /// /// @author Sean Owen /// </summary> internal sealed class AlignmentPatternFinder { private readonly BitMatrix image; private readonly IList<AlignmentPattern> possibleCenters; private readonly int startX; private readonly int startY; private readonly int width; private readonly int height; private readonly float moduleSize; private readonly int[] crossCheckStateCount; private readonly ResultPointCallback resultPointCallback; /// <summary> /// <p>Creates a finder that will look in a portion of the whole image.</p> /// </summary> /// <param name="image"> image to search </param> /// <param name="startX"> left column from which to start searching </param> /// <param name="startY"> top row from which to start searching </param> /// <param name="width"> width of region to search </param> /// <param name="height"> height of region to search </param> /// <param name="moduleSize"> estimated module size so far </param> internal AlignmentPatternFinder(BitMatrix image, int startX, int startY, int width, int height, float moduleSize, ResultPointCallback resultPointCallback) { this.image = image; this.possibleCenters = new List<AlignmentPattern>(5); this.startX = startX; this.startY = startY; this.width = width; this.height = height; this.moduleSize = moduleSize; this.crossCheckStateCount = new int[3]; this.resultPointCallback = resultPointCallback; } /// <summary> /// <p>This method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since /// it's pretty performance-critical and so is written to be fast foremost.</p> /// </summary> /// <returns> <seealso cref="AlignmentPattern"/> if found </returns> /// <exception cref="NotFoundException"> if not found </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: AlignmentPattern find() throws com.google.zxing.NotFoundException internal AlignmentPattern find() { int startX = this.startX; int height = this.height; int maxJ = startX + width; int middleI = startY + (height >> 1); // We are looking for black/white/black modules in 1:1:1 ratio; // this tracks the number of black/white/black modules seen so far int[] stateCount = new int[3]; for (int iGen = 0; iGen < height; iGen++) { // Search from middle outwards int i = middleI + ((iGen & 0x01) == 0 ? (iGen + 1) >> 1 : -((iGen + 1) >> 1)); stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; int j = startX; // Burn off leading white pixels before anything else; if we start in the middle of // a white run, it doesn't make sense to count its length, since we don't know if the // white run continued to the left of the start point while (j < maxJ && !image.get(j, i)) { j++; } int currentState = 0; while (j < maxJ) { if (image.get(j, i)) { // Black pixel if (currentState == 1) // Counting black pixels { stateCount[currentState]++; } // Counting white pixels else { if (currentState == 2) // A winner? { if (foundPatternCross(stateCount)) // Yes { AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, j); if (confirmed != null) { return confirmed; } } stateCount[0] = stateCount[2]; stateCount[1] = 1; stateCount[2] = 0; currentState = 1; } else { stateCount[++currentState]++; } } } // White pixel else { if (currentState == 1) // Counting black pixels { currentState++; } stateCount[currentState]++; } j++; } if (foundPatternCross(stateCount)) { AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, maxJ); if (confirmed != null) { return confirmed; } } } // Hmm, nothing we saw was observed and confirmed twice. If we had // any guess at all, return it. if (possibleCenters.Count > 0) { return possibleCenters[0]; } throw NotFoundException.NotFoundInstance; } /// <summary> /// Given a count of black/white/black pixels just seen and an end position, /// figures the location of the center of this black/white/black run. /// </summary> private static float centerFromEnd(int[] stateCount, int end) { return (float)(end - stateCount[2]) - stateCount[1] / 2.0f; } /// <param name="stateCount"> count of black/white/black pixels just read </param> /// <returns> true iff the proportions of the counts is close enough to the 1/1/1 ratios /// used by alignment patterns to be considered a match </returns> private bool foundPatternCross(int[] stateCount) { float moduleSize = this.moduleSize; float maxVariance = moduleSize / 2.0f; for (int i = 0; i < 3; i++) { if (Math.Abs(moduleSize - stateCount[i]) >= maxVariance) { return false; } } return true; } /// <summary> /// <p>After a horizontal scan finds a potential alignment pattern, this method /// "cross-checks" by scanning down vertically through the center of the possible /// alignment pattern to see if the same proportion is detected.</p> /// </summary> /// <param name="startI"> row where an alignment pattern was detected </param> /// <param name="centerJ"> center of the section that appears to cross an alignment pattern </param> /// <param name="maxCount"> maximum reasonable number of modules that should be /// observed in any reading state, based on the results of the horizontal scan </param> /// <returns> vertical center of alignment pattern, or <seealso cref="Float#NaN"/> if not found </returns> private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal) { BitMatrix image = this.image; int maxI = image.Height; int[] stateCount = crossCheckStateCount; stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; // Start counting up from center int i = startI; while (i >= 0 && image.get(centerJ, i) && stateCount[1] <= maxCount) { stateCount[1]++; i--; } // If already too many modules in this state or ran off the edge: if (i < 0 || stateCount[1] > maxCount) { return float.NaN; } while (i >= 0 && !image.get(centerJ, i) && stateCount[0] <= maxCount) { stateCount[0]++; i--; } if (stateCount[0] > maxCount) { return float.NaN; } // Now also count down from center i = startI + 1; while (i < maxI && image.get(centerJ, i) && stateCount[1] <= maxCount) { stateCount[1]++; i++; } if (i == maxI || stateCount[1] > maxCount) { return float.NaN; } while (i < maxI && !image.get(centerJ, i) && stateCount[2] <= maxCount) { stateCount[2]++; i++; } if (stateCount[2] > maxCount) { return float.NaN; } int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; if (5 * Math.Abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) { return float.NaN; } return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : float.NaN; } /// <summary> /// <p>This is called when a horizontal scan finds a possible alignment pattern. It will /// cross check with a vertical scan, and if successful, will see if this pattern had been /// found on a previous horizontal scan. If so, we consider it confirmed and conclude we have /// found the alignment pattern.</p> /// </summary> /// <param name="stateCount"> reading state module counts from horizontal scan </param> /// <param name="i"> row where alignment pattern may be found </param> /// <param name="j"> end of possible alignment pattern in row </param> /// <returns> <seealso cref="AlignmentPattern"/> if we have found the same pattern twice, or null if not </returns> private AlignmentPattern handlePossibleCenter(int[] stateCount, int i, int j) { int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; float centerJ = centerFromEnd(stateCount, j); float centerI = crossCheckVertical(i, (int) centerJ, 2 * stateCount[1], stateCountTotal); if (!float.IsNaN(centerI)) { float estimatedModuleSize = (float)(stateCount[0] + stateCount[1] + stateCount[2]) / 3.0f; foreach (AlignmentPattern center in possibleCenters) { // Look for about the same center and module size: if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) { return center.combineEstimate(centerI, centerJ, estimatedModuleSize); } } // Hadn't found this before; save it AlignmentPattern point = new AlignmentPattern(centerJ, centerI, estimatedModuleSize); possibleCenters.Add(point); if (resultPointCallback != null) { resultPointCallback.foundPossibleResultPoint(point); } } return null; } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// Contains information about a billing invoice. /// </summary> [DataContract] public partial class BillingInvoice : IEquatable<BillingInvoice>, IValidatableObject { public BillingInvoice() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="BillingInvoice" /> class. /// </summary> /// <param name="Amount">Reserved: TBD.</param> /// <param name="Balance">Reserved: TBD.</param> /// <param name="DueDate">Reserved: TBD.</param> /// <param name="InvoiceId">Reserved: TBD.</param> /// <param name="InvoiceItems">Reserved: TBD.</param> /// <param name="InvoiceNumber">Reserved: TBD.</param> /// <param name="InvoiceUri">Contains a URI for an endpoint that you can use to retrieve invoice information..</param> /// <param name="NonTaxableAmount">NonTaxableAmount.</param> /// <param name="PdfAvailable">PdfAvailable.</param> /// <param name="TaxableAmount">TaxableAmount.</param> public BillingInvoice(string Amount = default(string), string Balance = default(string), string DueDate = default(string), string InvoiceId = default(string), List<BillingInvoiceItem> InvoiceItems = default(List<BillingInvoiceItem>), string InvoiceNumber = default(string), string InvoiceUri = default(string), string NonTaxableAmount = default(string), string PdfAvailable = default(string), string TaxableAmount = default(string)) { this.Amount = Amount; this.Balance = Balance; this.DueDate = DueDate; this.InvoiceId = InvoiceId; this.InvoiceItems = InvoiceItems; this.InvoiceNumber = InvoiceNumber; this.InvoiceUri = InvoiceUri; this.NonTaxableAmount = NonTaxableAmount; this.PdfAvailable = PdfAvailable; this.TaxableAmount = TaxableAmount; } /// <summary> /// Reserved: TBD /// </summary> /// <value>Reserved: TBD</value> [DataMember(Name="amount", EmitDefaultValue=false)] public string Amount { get; set; } /// <summary> /// Reserved: TBD /// </summary> /// <value>Reserved: TBD</value> [DataMember(Name="balance", EmitDefaultValue=false)] public string Balance { get; set; } /// <summary> /// Reserved: TBD /// </summary> /// <value>Reserved: TBD</value> [DataMember(Name="dueDate", EmitDefaultValue=false)] public string DueDate { get; set; } /// <summary> /// Reserved: TBD /// </summary> /// <value>Reserved: TBD</value> [DataMember(Name="invoiceId", EmitDefaultValue=false)] public string InvoiceId { get; set; } /// <summary> /// Reserved: TBD /// </summary> /// <value>Reserved: TBD</value> [DataMember(Name="invoiceItems", EmitDefaultValue=false)] public List<BillingInvoiceItem> InvoiceItems { get; set; } /// <summary> /// Reserved: TBD /// </summary> /// <value>Reserved: TBD</value> [DataMember(Name="invoiceNumber", EmitDefaultValue=false)] public string InvoiceNumber { get; set; } /// <summary> /// Contains a URI for an endpoint that you can use to retrieve invoice information. /// </summary> /// <value>Contains a URI for an endpoint that you can use to retrieve invoice information.</value> [DataMember(Name="invoiceUri", EmitDefaultValue=false)] public string InvoiceUri { get; set; } /// <summary> /// Gets or Sets NonTaxableAmount /// </summary> [DataMember(Name="nonTaxableAmount", EmitDefaultValue=false)] public string NonTaxableAmount { get; set; } /// <summary> /// Gets or Sets PdfAvailable /// </summary> [DataMember(Name="pdfAvailable", EmitDefaultValue=false)] public string PdfAvailable { get; set; } /// <summary> /// Gets or Sets TaxableAmount /// </summary> [DataMember(Name="taxableAmount", EmitDefaultValue=false)] public string TaxableAmount { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class BillingInvoice {\n"); sb.Append(" Amount: ").Append(Amount).Append("\n"); sb.Append(" Balance: ").Append(Balance).Append("\n"); sb.Append(" DueDate: ").Append(DueDate).Append("\n"); sb.Append(" InvoiceId: ").Append(InvoiceId).Append("\n"); sb.Append(" InvoiceItems: ").Append(InvoiceItems).Append("\n"); sb.Append(" InvoiceNumber: ").Append(InvoiceNumber).Append("\n"); sb.Append(" InvoiceUri: ").Append(InvoiceUri).Append("\n"); sb.Append(" NonTaxableAmount: ").Append(NonTaxableAmount).Append("\n"); sb.Append(" PdfAvailable: ").Append(PdfAvailable).Append("\n"); sb.Append(" TaxableAmount: ").Append(TaxableAmount).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as BillingInvoice); } /// <summary> /// Returns true if BillingInvoice instances are equal /// </summary> /// <param name="other">Instance of BillingInvoice to be compared</param> /// <returns>Boolean</returns> public bool Equals(BillingInvoice other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Amount == other.Amount || this.Amount != null && this.Amount.Equals(other.Amount) ) && ( this.Balance == other.Balance || this.Balance != null && this.Balance.Equals(other.Balance) ) && ( this.DueDate == other.DueDate || this.DueDate != null && this.DueDate.Equals(other.DueDate) ) && ( this.InvoiceId == other.InvoiceId || this.InvoiceId != null && this.InvoiceId.Equals(other.InvoiceId) ) && ( this.InvoiceItems == other.InvoiceItems || this.InvoiceItems != null && this.InvoiceItems.SequenceEqual(other.InvoiceItems) ) && ( this.InvoiceNumber == other.InvoiceNumber || this.InvoiceNumber != null && this.InvoiceNumber.Equals(other.InvoiceNumber) ) && ( this.InvoiceUri == other.InvoiceUri || this.InvoiceUri != null && this.InvoiceUri.Equals(other.InvoiceUri) ) && ( this.NonTaxableAmount == other.NonTaxableAmount || this.NonTaxableAmount != null && this.NonTaxableAmount.Equals(other.NonTaxableAmount) ) && ( this.PdfAvailable == other.PdfAvailable || this.PdfAvailable != null && this.PdfAvailable.Equals(other.PdfAvailable) ) && ( this.TaxableAmount == other.TaxableAmount || this.TaxableAmount != null && this.TaxableAmount.Equals(other.TaxableAmount) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Amount != null) hash = hash * 59 + this.Amount.GetHashCode(); if (this.Balance != null) hash = hash * 59 + this.Balance.GetHashCode(); if (this.DueDate != null) hash = hash * 59 + this.DueDate.GetHashCode(); if (this.InvoiceId != null) hash = hash * 59 + this.InvoiceId.GetHashCode(); if (this.InvoiceItems != null) hash = hash * 59 + this.InvoiceItems.GetHashCode(); if (this.InvoiceNumber != null) hash = hash * 59 + this.InvoiceNumber.GetHashCode(); if (this.InvoiceUri != null) hash = hash * 59 + this.InvoiceUri.GetHashCode(); if (this.NonTaxableAmount != null) hash = hash * 59 + this.NonTaxableAmount.GetHashCode(); if (this.PdfAvailable != null) hash = hash * 59 + this.PdfAvailable.GetHashCode(); if (this.TaxableAmount != null) hash = hash * 59 + this.TaxableAmount.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010-2016 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- using System; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Reflection.Emit; using MsgPack.Serialization.AbstractSerializers; using MsgPack.Serialization.Reflection; namespace MsgPack.Serialization.EmittingSerializers { /// <summary> /// Represents code construct for <see cref="AssemblyBuilderSerializerBuilder"/>s. /// </summary> internal abstract class ILConstruct : ICodeConstruct { public static readonly ILConstruct[] NoArguments = new ILConstruct[ 0 ]; private readonly TypeDefinition _contextType; /// <summary> /// Gets the context type of this construct. /// </summary> /// <value> /// The context type of this construct. /// This value will not be <c>null</c>, but might be <see cref="Void" />. /// </value> /// <remarks> /// A context type represents the type of the evaluation context. /// </remarks> public TypeDefinition ContextType { get { return this._contextType; } } /// <summary> /// Gets a value indicating whether this instance is terminating. /// </summary> /// <value> /// <c>true</c> if this instruction terminates method; otherwise, <c>false</c>. /// </value> public virtual bool IsTerminating { get { return false; } } /// <summary> /// Initializes a new instance of the <see cref="ILConstruct"/> class. /// </summary> /// <param name="contextType">The type.</param> protected ILConstruct( TypeDefinition contextType ) { this._contextType = contextType; } /// <summary> /// Evaluates this construct that is executing this construct as instruction. /// </summary> /// <param name="il">The <see cref="TracingILGenerator"/>.</param> /// <exception cref="InvalidOperationException"> /// This construct does not have eval semantics. /// </exception> public virtual void Evaluate( TracingILGenerator il ) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "'{0}' does not define stand alone instruction.", this ) ); } /// <summary> /// Loads value from the storage represented by this construct. /// </summary> /// <param name="il">The <see cref="TracingILGenerator"/>.</param> /// <param name="shouldBeAddress"> /// <c>true</c>, if value type value should be pushed its address instead of bits; otherwise, <c>false</c>. /// </param> /// <exception cref="InvalidOperationException"> /// This construct does not have load value semantics. /// </exception> public virtual void LoadValue( TracingILGenerator il, bool shouldBeAddress ) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "'{0}' does not define load value instruction.", this ) ); } /// <summary> /// Stores value to the storage represented by this construct. /// </summary> /// <param name="il">The <see cref="TracingILGenerator"/>.</param> /// <exception cref="InvalidOperationException"> /// This construct does not have store value semantics. /// </exception> public virtual void StoreValue( TracingILGenerator il ) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "'{0}' does not define store value instruction.", this ) ); } /// <summary> /// Evaluates this construct as branch instruction. /// </summary> /// <param name="il">The <see cref="TracingILGenerator"/>.</param> /// <param name="else">The <see cref="Label"/> which points the head of 'else' instructions.</param> /// <exception cref="InvalidOperationException"> /// This construct does not have branch semantics. /// </exception> public virtual void Branch( TracingILGenerator il, Label @else ) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "'{0}' does not define branch instruction.", this ) ); } public static ILConstruct LoadField( ILConstruct instance, FieldInfo field ) { return new LoadFieldILConstruct( instance, field ); } public static ILConstruct StoreField( ILConstruct instance, FieldInfo field, ILConstruct value ) { return new StoreFieldILConstruct( instance, field, value ); } public static ILConstruct StoreLocal( ILConstruct variable, ILConstruct value ) { return new StoreVariableILConstruct( variable, value ); } public static ILConstruct Instruction( string description, TypeDefinition contextType, bool isTerminating, Action<TracingILGenerator> instructions ) { return new SinglelStepILConstruct( contextType, description, isTerminating, instructions ); } public static ILConstruct Argument( int index, TypeDefinition type, string name ) { return new VariableILConstruct( name, type, index ); } public static ILConstruct IfThenElse( ILConstruct conditionExpression, ILConstruct thenExpression, ILConstruct elseExpression ) { return new ConditionalILConstruct( conditionExpression, thenExpression, elseExpression ); } public static ILConstruct AndCondition( IList<ILConstruct> conditionExpressions ) { return new AndConditionILConstruct( conditionExpressions ); } public static ILConstruct UnaryOperator( string @operator, ILConstruct input, Action<TracingILGenerator, ILConstruct> operation ) { return new UnaryOperatorILConstruct( @operator, input, operation ); } public static ILConstruct UnaryOperator( string @operator, ILConstruct input, Action<TracingILGenerator, ILConstruct> operation, Action<TracingILGenerator, ILConstruct, Label> branchOperation ) { return new UnaryOperatorILConstruct( @operator, input, operation, branchOperation ); } public static ILConstruct BinaryOperator( string @operator, TypeDefinition resultType, ILConstruct left, ILConstruct right, Action<TracingILGenerator, ILConstruct, ILConstruct> operation, Action<TracingILGenerator, ILConstruct, ILConstruct, Label> branchOperation ) { return new BinaryOperatorILConstruct( @operator, resultType, left, right, operation, branchOperation ); } public static ILConstruct Invoke( ILConstruct target, MethodDefinition method, IEnumerable<ILConstruct> arguments ) { return new InvocationILConsruct( method.ResolveRuntimeMethod(), method.Interface, target, arguments ); } public static ILConstruct Invoke( ILConstruct target, MethodInfo runtimeMethod, IEnumerable<ILConstruct> arguments ) { return new InvocationILConsruct( runtimeMethod, null, target, arguments ); } internal static ILConstruct NewObject( ILConstruct variable, ConstructorInfo constructor, IEnumerable<ILConstruct> arguments ) { return new InvocationILConsruct( constructor, variable, arguments ); } public static ILConstruct Sequence( TypeDefinition contextType, IEnumerable<ILConstruct> statements ) { return new SequenceILConstruct( contextType, statements ); } public static ILConstruct Composite( ILConstruct before, ILConstruct context ) { return new StatementExpressionILConstruct( before, context ); } public static ILConstruct Literal<T>( TypeDefinition type, T literalValue, Action<TracingILGenerator> instruction ) { // ReSharper disable CompareNonConstrainedGenericWithNull return new SinglelStepILConstruct( type, "literal " + ( literalValue == null ? "(null)" : literalValue.ToString() ), false, instruction ); // ReSharper restore CompareNonConstrainedGenericWithNull } public static ILConstruct Variable( TypeDefinition type, string name ) { return new VariableILConstruct( name, type ); } public static ILConstruct MakeRef(ILConstruct variable ) { return new SinglelStepILConstruct( variable.ContextType, "mkref", false, il => variable.LoadValue( il, true ) ); } protected static void ValidateContextTypeMatch( ILConstruct left, ILConstruct right ) { if ( GetNormalizedType( left.ContextType.ResolveRuntimeType() ) != GetNormalizedType( right.ContextType.ResolveRuntimeType() ) ) { throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, "Right type '{1}' does not equal to left type '{0}'.", left.ContextType, right.ContextType ), "right" ); } } private static Type GetNormalizedType( Type type ) { if ( type == typeof( sbyte ) || type == typeof( short ) || type == typeof( int ) || type == typeof( byte ) || type == typeof( ushort ) || type == typeof( uint ) ) { return typeof( long ); } if ( type == typeof( float ) ) { return typeof( double ); } if ( type.GetIsEnum() ) { return GetNormalizedType( Enum.GetUnderlyingType( type ) ); } return type; } } }
//------------------------------------------------------------------------------ // <copyright file="XPathNodeHelper.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ using System; using System.Diagnostics; using System.Text; using System.Xml; using System.Xml.XPath; using System.Xml.Schema; namespace MS.Internal.Xml.Cache { /// <summary> /// Library of XPathNode helper routines. /// </summary> internal abstract class XPathNodeHelper { /// <summary> /// Return chain of namespace nodes. If specified node has no local namespaces, then 0 will be /// returned. Otherwise, the first node in the chain is guaranteed to be a local namespace (its /// parent is this node). Subsequent nodes may not have the same node as parent, so the caller will /// need to test the parent in order to terminate a search that processes only local namespaces. /// </summary> public static int GetLocalNamespaces(XPathNode[] pageElem, int idxElem, out XPathNode[] pageNmsp) { if (pageElem[idxElem].HasNamespaceDecls) { // Only elements have namespace nodes Debug.Assert(pageElem[idxElem].NodeType == XPathNodeType.Element); return pageElem[idxElem].Document.LookupNamespaces(pageElem, idxElem, out pageNmsp); } pageNmsp = null; return 0; } /// <summary> /// Return chain of in-scope namespace nodes for nodes of type Element. Nodes in the chain might not /// have this element as their parent. Since the xmlns:xml namespace node is always in scope, this /// method will never return 0 if the specified node is an element. /// </summary> public static int GetInScopeNamespaces(XPathNode[] pageElem, int idxElem, out XPathNode[] pageNmsp) { XPathDocument doc; // Only elements have namespace nodes if (pageElem[idxElem].NodeType == XPathNodeType.Element) { doc = pageElem[idxElem].Document; // Walk ancestors, looking for an ancestor that has at least one namespace declaration while (!pageElem[idxElem].HasNamespaceDecls) { idxElem = pageElem[idxElem].GetParent(out pageElem); if (idxElem == 0) { // There are no namespace nodes declared on ancestors, so return xmlns:xml node return doc.GetXmlNamespaceNode(out pageNmsp); } } // Return chain of in-scope namespace nodes return doc.LookupNamespaces(pageElem, idxElem, out pageNmsp); } pageNmsp = null; return 0; } /// <summary> /// Return the first attribute of the specified node. If no attribute exist, do not /// set pageNode or idxNode and return false. /// </summary> public static bool GetFirstAttribute(ref XPathNode[] pageNode, ref int idxNode) { Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); if (pageNode[idxNode].HasAttribute) { GetChild(ref pageNode, ref idxNode); Debug.Assert(pageNode[idxNode].NodeType == XPathNodeType.Attribute); return true; } return false; } /// <summary> /// Return the next attribute sibling of the specified node. If the node is not itself an /// attribute, or if there are no siblings, then do not set pageNode or idxNode and return false. /// </summary> public static bool GetNextAttribute(ref XPathNode[] pageNode, ref int idxNode) { XPathNode[] page; int idx; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); idx = pageNode[idxNode].GetSibling(out page); if (idx != 0 && page[idx].NodeType == XPathNodeType.Attribute) { pageNode = page; idxNode = idx; return true; } return false; } /// <summary> /// Return the first content-typed child of the specified node. If the node has no children, or /// if the node is not content-typed, then do not set pageNode or idxNode and return false. /// </summary> public static bool GetContentChild(ref XPathNode[] pageNode, ref int idxNode) { XPathNode[] page = pageNode; int idx = idxNode; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); if (page[idx].HasContentChild) { GetChild(ref page, ref idx); // Skip past attribute children while (page[idx].NodeType == XPathNodeType.Attribute) { idx = page[idx].GetSibling(out page); Debug.Assert(idx != 0); } pageNode = page; idxNode = idx; return true; } return false; } /// <summary> /// Return the next content-typed sibling of the specified node. If the node has no siblings, or /// if the node is not content-typed, then do not set pageNode or idxNode and return false. /// </summary> public static bool GetContentSibling(ref XPathNode[] pageNode, ref int idxNode) { XPathNode[] page = pageNode; int idx = idxNode; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); if (!page[idx].IsAttrNmsp) { idx = page[idx].GetSibling(out page); if (idx != 0) { pageNode = page; idxNode = idx; return true; } } return false; } /// <summary> /// Return the parent of the specified node. If the node has no parent, do not set pageNode /// or idxNode and return false. /// </summary> public static bool GetParent(ref XPathNode[] pageNode, ref int idxNode) { XPathNode[] page = pageNode; int idx = idxNode; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); idx = page[idx].GetParent(out page); if (idx != 0) { pageNode = page; idxNode = idx; return true; } return false; } /// <summary> /// Return a location integer that can be easily compared with other locations from the same document /// in order to determine the relative document order of two nodes. /// </summary> public static int GetLocation(XPathNode[] pageNode, int idxNode) { Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); Debug.Assert(idxNode <= UInt16.MaxValue); Debug.Assert(pageNode[0].PageInfo.PageNumber <= Int16.MaxValue); return (pageNode[0].PageInfo.PageNumber << 16) | idxNode; } /// <summary> /// Return the first element child of the specified node that has the specified name. If no such child exists, /// then do not set pageNode or idxNode and return false. Assume that the localName has been atomized with respect /// to this document's name table, but not the namespaceName. /// </summary> public static bool GetElementChild(ref XPathNode[] pageNode, ref int idxNode, string localName, string namespaceName) { XPathNode[] page = pageNode; int idx = idxNode; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); // Only check children if at least one element child exists if (page[idx].HasElementChild) { GetChild(ref page, ref idx); Debug.Assert(idx != 0); // Find element with specified localName and namespaceName do { if (page[idx].ElementMatch(localName, namespaceName)) { pageNode = page; idxNode = idx; return true; } idx = page[idx].GetSibling(out page); } while (idx != 0); } return false; } /// <summary> /// Return a following sibling element of the specified node that has the specified name. If no such /// sibling exists, or if the node is not content-typed, then do not set pageNode or idxNode and /// return false. Assume that the localName has been atomized with respect to this document's name table, /// but not the namespaceName. /// </summary> public static bool GetElementSibling(ref XPathNode[] pageNode, ref int idxNode, string localName, string namespaceName) { XPathNode[] page = pageNode; int idx = idxNode; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); // Elements should not be returned as "siblings" of attributes (namespaces don't link to elements, so don't need to check them) if (page[idx].NodeType != XPathNodeType.Attribute) { while (true) { idx = page[idx].GetSibling(out page); if (idx == 0) break; if (page[idx].ElementMatch(localName, namespaceName)) { pageNode = page; idxNode = idx; return true; } } } return false; } /// <summary> /// Return the first child of the specified node that has the specified type (must be a content type). If no such /// child exists, then do not set pageNode or idxNode and return false. /// </summary> public static bool GetContentChild(ref XPathNode[] pageNode, ref int idxNode, XPathNodeType typ) { XPathNode[] page = pageNode; int idx = idxNode; int mask; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); // Only check children if at least one content-typed child exists if (page[idx].HasContentChild) { mask = XPathNavigator.GetContentKindMask(typ); GetChild(ref page, ref idx); do { if (((1 << (int) page[idx].NodeType) & mask) != 0) { // Never return attributes, as Attribute is not a content type if (typ == XPathNodeType.Attribute) return false; pageNode = page; idxNode = idx; return true; } idx = page[idx].GetSibling(out page); } while (idx != 0); } return false; } /// <summary> /// Return a following sibling of the specified node that has the specified type. If no such /// sibling exists, then do not set pageNode or idxNode and return false. /// </summary> public static bool GetContentSibling(ref XPathNode[] pageNode, ref int idxNode, XPathNodeType typ) { XPathNode[] page = pageNode; int idx = idxNode; int mask = XPathNavigator.GetContentKindMask(typ); Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); if (page[idx].NodeType != XPathNodeType.Attribute) { while (true) { idx = page[idx].GetSibling(out page); if (idx == 0) break; if (((1 << (int) page[idx].NodeType) & mask) != 0) { Debug.Assert(typ != XPathNodeType.Attribute && typ != XPathNodeType.Namespace); pageNode = page; idxNode = idx; return true; } } } return false; } /// <summary> /// Return the first preceding sibling of the specified node. If no such sibling exists, then do not set /// pageNode or idxNode and return false. /// </summary> public static bool GetPreviousContentSibling(ref XPathNode[] pageNode, ref int idxNode) { XPathNode[] pageParent = pageNode, pagePrec, pageAnc; int idxParent = idxNode, idxPrec, idxAnc; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); Debug.Assert(pageNode[idxNode].NodeType != XPathNodeType.Attribute); // Since nodes are laid out in document order on pages, the algorithm is: // 1. Get parent of current node // 2. If no parent, then there is no previous sibling, so return false // 3. Get node that immediately precedes the current node in document order // 4. If preceding node is parent, then there is no previous sibling, so return false // 5. Walk ancestors of preceding node, until parent of current node is found idxParent = pageParent[idxParent].GetParent(out pageParent); if (idxParent != 0) { idxPrec = idxNode - 1; if (idxPrec == 0) { // Need to get previous page pagePrec = pageNode[0].PageInfo.PreviousPage; idxPrec = pagePrec.Length - 1; } else { // Previous node is on the same page pagePrec = pageNode; } // If parent node is previous node, then no previous sibling if (idxParent == idxPrec && pageParent == pagePrec) return false; // Find child of parent node by walking ancestor chain pageAnc = pagePrec; idxAnc = idxPrec; do { pagePrec = pageAnc; idxPrec = idxAnc; idxAnc = pageAnc[idxAnc].GetParent(out pageAnc); Debug.Assert(idxAnc != 0 && pageAnc != null); } while (idxAnc != idxParent || pageAnc != pageParent); // We found the previous sibling, but if it's an attribute node, then return false if (pagePrec[idxPrec].NodeType != XPathNodeType.Attribute) { pageNode = pagePrec; idxNode = idxPrec; return true; } } return false; } /// <summary> /// Return a previous sibling element of the specified node that has the specified name. If no such /// sibling exists, or if the node is not content-typed, then do not set pageNode or idxNode and /// return false. Assume that the localName has been atomized with respect to this document's name table, /// but not the namespaceName. /// </summary> public static bool GetPreviousElementSibling(ref XPathNode[] pageNode, ref int idxNode, string localName, string namespaceName) { XPathNode[] page = pageNode; int idx = idxNode; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); if (page[idx].NodeType != XPathNodeType.Attribute) { while (true) { if (!GetPreviousContentSibling(ref page, ref idx)) break; if (page[idx].ElementMatch(localName, namespaceName)) { pageNode = page; idxNode = idx; return true; } } } return false; } /// <summary> /// Return a previous sibling of the specified node that has the specified type. If no such /// sibling exists, then do not set pageNode or idxNode and return false. /// </summary> public static bool GetPreviousContentSibling(ref XPathNode[] pageNode, ref int idxNode, XPathNodeType typ) { XPathNode[] page = pageNode; int idx = idxNode; int mask = XPathNavigator.GetContentKindMask(typ); Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); while (true) { if (!GetPreviousContentSibling(ref page, ref idx)) break; if (((1 << (int) page[idx].NodeType) & mask) != 0) { pageNode = page; idxNode = idx; return true; } } return false; } /// <summary> /// Return the attribute of the specified node that has the specified name. If no such attribute exists, /// then do not set pageNode or idxNode and return false. Assume that the localName has been atomized with respect /// to this document's name table, but not the namespaceName. /// </summary> public static bool GetAttribute(ref XPathNode[] pageNode, ref int idxNode, string localName, string namespaceName) { XPathNode[] page = pageNode; int idx = idxNode; Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)"); // Find attribute with specified localName and namespaceName if (page[idx].HasAttribute) { GetChild(ref page, ref idx); do { if (page[idx].NameMatch(localName, namespaceName)) { pageNode = page; idxNode = idx; return true; } idx = page[idx].GetSibling(out page); } while (idx != 0 && page[idx].NodeType == XPathNodeType.Attribute); } return false; } /// <summary> /// Get the next non-virtual (not collapsed text, not namespaces) node that follows the specified node in document order. /// If no such node exists, then do not set pageNode or idxNode and return false. /// </summary> public static bool GetFollowing(ref XPathNode[] pageNode, ref int idxNode) { XPathNode[] page = pageNode; int idx = idxNode; do { // Next non-virtual node is in next slot within the page if (++idx < page[0].PageInfo.NodeCount) { pageNode = page; idxNode = idx; return true; } // Otherwise, start at the beginning of the next page page = page[0].PageInfo.NextPage; idx = 0; } while (page != null); return false; } /// <summary> /// Get the next element node that: /// 1. Follows the current node in document order (includes descendants, unlike XPath following axis) /// 2. Precedes the ending node in document order (if pageEnd is null, then all following nodes in the document are considered) /// 3. Has the specified QName /// If no such element exists, then do not set pageCurrent or idxCurrent and return false. /// Assume that the localName has been atomized with respect to this document's name table, but not the namespaceName. /// </summary> public static bool GetElementFollowing(ref XPathNode[] pageCurrent, ref int idxCurrent, XPathNode[] pageEnd, int idxEnd, string localName, string namespaceName) { XPathNode[] page = pageCurrent; int idx = idxCurrent; Debug.Assert(pageCurrent != null && idxCurrent != 0, "Cannot pass null argument(s)"); // If current node is an element having a matching name, if (page[idx].NodeType == XPathNodeType.Element && (object) page[idx].LocalName == (object) localName) { // Then follow similar element name pointers int idxPageEnd = 0; int idxPageCurrent; if (pageEnd != null) { idxPageEnd = pageEnd[0].PageInfo.PageNumber; idxPageCurrent = page[0].PageInfo.PageNumber; // If ending node is <= starting node in document order, then scan to end of document if (idxPageCurrent > idxPageEnd || (idxPageCurrent == idxPageEnd && idx >= idxEnd)) pageEnd = null; } while (true) { idx = page[idx].GetSimilarElement(out page); if (idx == 0) break; // Only scan to ending node if (pageEnd != null) { idxPageCurrent = page[0].PageInfo.PageNumber; if (idxPageCurrent > idxPageEnd) break; if (idxPageCurrent == idxPageEnd && idx >= idxEnd) break; } if ((object) page[idx].LocalName == (object) localName && page[idx].NamespaceUri == namespaceName) goto FoundNode; } return false; } // Since nodes are laid out in document order on pages, scan them sequentially // rather than following links. idx++; do { if ((object) page == (object) pageEnd && idx <= idxEnd) { // Only scan to termination point while (idx != idxEnd) { if (page[idx].ElementMatch(localName, namespaceName)) goto FoundNode; idx++; } break; } else { // Scan all nodes in the page while (idx < page[0].PageInfo.NodeCount) { if (page[idx].ElementMatch(localName, namespaceName)) goto FoundNode; idx++; } } page = page[0].PageInfo.NextPage; idx = 1; } while (page != null); return false; FoundNode: // Found match pageCurrent = page; idxCurrent = idx; return true; } /// <summary> /// Get the next node that: /// 1. Follows the current node in document order (includes descendants, unlike XPath following axis) /// 2. Precedes the ending node in document order (if pageEnd is null, then all following nodes in the document are considered) /// 3. Has the specified XPathNodeType (but Attributes and Namespaces never match) /// If no such node exists, then do not set pageCurrent or idxCurrent and return false. /// </summary> public static bool GetContentFollowing(ref XPathNode[] pageCurrent, ref int idxCurrent, XPathNode[] pageEnd, int idxEnd, XPathNodeType typ) { XPathNode[] page = pageCurrent; int idx = idxCurrent; int mask = XPathNavigator.GetContentKindMask(typ); Debug.Assert(pageCurrent != null && idxCurrent != 0, "Cannot pass null argument(s)"); Debug.Assert(typ != XPathNodeType.Text, "Text should be handled by GetTextFollowing in order to take into account collapsed text."); Debug.Assert(page[idx].NodeType != XPathNodeType.Attribute, "Current node should never be an attribute or namespace--caller should handle this case."); // Since nodes are laid out in document order on pages, scan them sequentially // rather than following sibling/child/parent links. idx++; do { if ((object) page == (object) pageEnd && idx <= idxEnd) { // Only scan to termination point while (idx != idxEnd) { if (((1 << (int) page[idx].NodeType) & mask) != 0) goto FoundNode; idx++; } break; } else { // Scan all nodes in the page while (idx < page[0].PageInfo.NodeCount) { if (((1 << (int) page[idx].NodeType) & mask) != 0) goto FoundNode; idx++; } } page = page[0].PageInfo.NextPage; idx = 1; } while (page != null); return false; FoundNode: Debug.Assert(!page[idx].IsAttrNmsp, "GetContentFollowing should never return attributes or namespaces."); // Found match pageCurrent = page; idxCurrent = idx; return true; } /// <summary> /// Scan all nodes that follow the current node in document order, but precede the ending node in document order. /// Return two types of nodes with non-null text: /// 1. Element parents of collapsed text nodes (since it is the element parent that has the collapsed text) /// 2. Non-collapsed text nodes /// If no such node exists, then do not set pageCurrent or idxCurrent and return false. /// </summary> public static bool GetTextFollowing(ref XPathNode[] pageCurrent, ref int idxCurrent, XPathNode[] pageEnd, int idxEnd) { XPathNode[] page = pageCurrent; int idx = idxCurrent; Debug.Assert(pageCurrent != null && idxCurrent != 0, "Cannot pass null argument(s)"); Debug.Assert(!page[idx].IsAttrNmsp, "Current node should never be an attribute or namespace--caller should handle this case."); // Since nodes are laid out in document order on pages, scan them sequentially // rather than following sibling/child/parent links. idx++; do { if ((object) page == (object) pageEnd && idx <= idxEnd) { // Only scan to termination point while (idx != idxEnd) { if (page[idx].IsText || (page[idx].NodeType == XPathNodeType.Element && page[idx].HasCollapsedText)) goto FoundNode; idx++; } break; } else { // Scan all nodes in the page while (idx < page[0].PageInfo.NodeCount) { if (page[idx].IsText || (page[idx].NodeType == XPathNodeType.Element && page[idx].HasCollapsedText)) goto FoundNode; idx++; } } page = page[0].PageInfo.NextPage; idx = 1; } while (page != null); return false; FoundNode: // Found match pageCurrent = page; idxCurrent = idx; return true; } /// <summary> /// Get the next non-virtual (not collapsed text, not namespaces) node that follows the specified node in document order, /// but is not a descendant. If no such node exists, then do not set pageNode or idxNode and return false. /// </summary> public static bool GetNonDescendant(ref XPathNode[] pageNode, ref int idxNode) { XPathNode[] page = pageNode; int idx = idxNode; // Get page, idx at which to end sequential scan of nodes do { // If the current node has a sibling, if (page[idx].HasSibling) { // Then that is the first non-descendant pageNode = page; idxNode = page[idx].GetSibling(out pageNode); return true; } // Otherwise, try finding a sibling at the parent level idx = page[idx].GetParent(out page); } while (idx != 0); return false; } /// <summary> /// Return the page and index of the first child (attribute or content) of the specified node. /// </summary> private static void GetChild(ref XPathNode[] pageNode, ref int idxNode) { Debug.Assert(pageNode[idxNode].HasAttribute || pageNode[idxNode].HasContentChild, "Caller must check HasAttribute/HasContentChild on parent before calling GetChild."); Debug.Assert(pageNode[idxNode].HasAttribute || !pageNode[idxNode].HasCollapsedText, "Text child is virtualized and therefore is not present in the physical node page."); if (++idxNode >= pageNode.Length) { // Child is first node on next page pageNode = pageNode[0].PageInfo.NextPage; idxNode = 1; } // Else child is next node on this page } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using Spatial4n.Core.Context; using Spatial4n.Core.Shapes; namespace Lucene.Net.Spatial.Prefix.Tree { /// <summary> /// A spatial Prefix Tree, or Trie, which decomposes shapes into prefixed strings at variable lengths corresponding to /// variable precision. Each string corresponds to a spatial region. /// /// Implementations of this class should be thread-safe and immutable once initialized. /// </summary> public abstract class SpatialPrefixTree { protected readonly int maxLevels; internal readonly SpatialContext ctx;// it's internal to allow Node to access it protected SpatialPrefixTree(SpatialContext ctx, int maxLevels) { Debug.Assert(maxLevels > 0); this.ctx = ctx; this.maxLevels = maxLevels; } public SpatialContext GetSpatialContext() { return ctx; } public int GetMaxLevels() { return maxLevels; } public override String ToString() { return GetType().Name + "(maxLevels:" + maxLevels + ",ctx:" + ctx + ")"; } /// <summary> /// Returns the level of the largest grid in which its longest side is less /// than or equal to the provided distance (in degrees). Consequently {@link /// dist} acts as an error epsilon declaring the amount of detail needed in the /// grid, such that you can get a grid with just the right amount of /// precision. /// </summary> /// <param name="dist">>= 0</param> /// <returns>level [1 to maxLevels]</returns> public abstract int GetLevelForDistance(double dist); //TODO double getDistanceForLevel(int level) //[NotSerialized] private Node worldNode;//cached /* * Returns the level 0 cell which encompasses all spatial data. Equivalent to {@link #getNode(String)} with "". * This cell is threadsafe, just like a spatial prefix grid is, although cells aren't * generally threadsafe. * TODO rename to getTopCell or is this fine? */ public Node GetWorldNode() { if (worldNode == null) { worldNode = GetNode(""); } return worldNode; } /* * The cell for the specified token. The empty string should be equal to {@link #getWorldNode()}. * Precondition: Never called when token length > maxLevel. */ public abstract Node GetNode(String token); public abstract Node GetNode(byte[] bytes, int offset, int len); //public Node GetNode(byte[] bytes, int offset, int len, Node target) //{ // if (target == null) // { // return GetNode(bytes, offset, len); // } // target.Reset(bytes, offset, len); // return target; //} public Node GetNode(string token, Node target) { if (target == null) { return GetNode(token); } target.Reset(token); return target; } protected virtual Node GetNode(Point p, int level) { return GetNodes(p, level, false).ElementAt(0); } /* * Gets the intersecting & including cells for the specified shape, without exceeding detail level. * The result is a set of cells (no dups), sorted. Unmodifiable. * <p/> * This implementation checks if shape is a Point and if so uses an implementation that * recursively calls {@link Node#getSubCell(com.spatial4j.core.shape.Point)}. Cell subclasses * ideally implement that method with a quick implementation, otherwise, subclasses should * override this method to invoke {@link #getNodesAltPoint(com.spatial4j.core.shape.Point, int, boolean)}. * TODO consider another approach returning an iterator -- won't build up all cells in memory. */ public virtual IList<Node> GetNodes(Shape shape, int detailLevel, bool inclParents) { if (detailLevel > maxLevels) { throw new ArgumentException("detailLevel > maxLevels", "detailLevel"); } List<Node> cells; if (shape is Point) { //optimized point algorithm int initialCapacity = inclParents ? 1 + detailLevel : 1; cells = new List<Node>(initialCapacity); RecursiveGetNodes(GetWorldNode(), (Point)shape, detailLevel, true, cells); Debug.Assert(cells.Count == initialCapacity); } else { cells = new List<Node>(inclParents ? 1024 : 512); RecursiveGetNodes(GetWorldNode(), shape, detailLevel, inclParents, cells); } if (inclParents) { Debug.Assert(cells[0].GetLevel() == 0); cells.RemoveAt(0);//remove getWorldNode() } return cells; } private void RecursiveGetNodes(Node node, Shape shape, int detailLevel, bool inclParents, IList<Node> result) { if (node.IsLeaf()) {//cell is within shape result.Add(node); return; } var subCells = node.GetSubCells(shape); if (node.GetLevel() == detailLevel - 1) { if (subCells.Count < node.GetSubCellsSize()) { if (inclParents) result.Add(node); foreach (var subCell in subCells) { subCell.SetLeaf(); result.Add(subCell); } } else {//a bottom level (i.e. detail level) optimization where all boxes intersect, so use parent cell. node.SetLeaf(); result.Add(node); } } else { if (inclParents) { result.Add(node); } foreach (var subCell in subCells) { RecursiveGetNodes(subCell, shape, detailLevel, inclParents, result);//tail call } } } private void RecursiveGetNodes(Node node, Point point, int detailLevel, bool inclParents, IList<Node> result) { if (inclParents) { result.Add(node); } Node pCell = node.GetSubCell(point); if (node.GetLevel() == detailLevel - 1) { pCell.SetLeaf(); result.Add(pCell); } else { RecursiveGetNodes(pCell, point, detailLevel, inclParents, result);//tail call } } /* * Subclasses might override {@link #getNodes(com.spatial4j.core.shape.Shape, int, boolean)} * and check if the argument is a shape and if so, delegate * to this implementation, which calls {@link #getNode(com.spatial4j.core.shape.Point, int)} and * then calls {@link #getNode(String)} repeatedly if inclParents is true. */ protected virtual IList<Node> GetNodesAltPoint(Point p, int detailLevel, bool inclParents) { Node cell = GetNode(p, detailLevel); if (!inclParents) { #if !NET35 return new ReadOnlyCollectionBuilder<Node>(new[] { cell }).ToReadOnlyCollection(); #else return new List<Node>(new[] { cell }).AsReadOnly(); #endif } String endToken = cell.GetTokenString(); Debug.Assert(endToken.Length == detailLevel); var cells = new List<Node>(detailLevel); for (int i = 1; i < detailLevel; i++) { cells.Add(GetNode(endToken.Substring(0, i))); } cells.Add(cell); return cells; } /* * Will add the trailing leaf byte for leaves. This isn't particularly efficient. */ public static List<String> NodesToTokenStrings(Collection<Node> nodes) { var tokens = new List<String>((nodes.Count)); foreach (Node node in nodes) { String token = node.GetTokenString(); if (node.IsLeaf()) { tokens.Add(token + (char)Node.LEAF_BYTE); } else { tokens.Add(token); } } return tokens; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System.Collections.Generic; namespace System.IO.Tests { public partial class MemoryStreamTests { [Fact] public static void MemoryStream_Write_BeyondCapacity() { using (MemoryStream memoryStream = new MemoryStream()) { long origLength = memoryStream.Length; byte[] bytes = new byte[10]; for (int i = 0; i < bytes.Length; i++) bytes[i] = (byte)i; int spanPastEnd = 5; memoryStream.Seek(spanPastEnd, SeekOrigin.End); Assert.Equal(memoryStream.Length + spanPastEnd, memoryStream.Position); // Test Write memoryStream.Write(bytes, 0, bytes.Length); long pos = memoryStream.Position; Assert.Equal(pos, origLength + spanPastEnd + bytes.Length); Assert.Equal(memoryStream.Length, origLength + spanPastEnd + bytes.Length); // Verify bytes were correct. memoryStream.Position = origLength; byte[] newData = new byte[bytes.Length + spanPastEnd]; int n = memoryStream.Read(newData, 0, newData.Length); Assert.Equal(n, newData.Length); for (int i = 0; i < spanPastEnd; i++) Assert.Equal(0, newData[i]); for (int i = 0; i < bytes.Length; i++) Assert.Equal(bytes[i], newData[i + spanPastEnd]); } } [Fact] public static void MemoryStream_WriteByte_BeyondCapacity() { using (MemoryStream memoryStream = new MemoryStream()) { long origLength = memoryStream.Length; byte[] bytes = new byte[10]; for (int i = 0; i < bytes.Length; i++) bytes[i] = (byte)i; int spanPastEnd = 5; memoryStream.Seek(spanPastEnd, SeekOrigin.End); Assert.Equal(memoryStream.Length + spanPastEnd, memoryStream.Position); // Test WriteByte origLength = memoryStream.Length; memoryStream.Position = memoryStream.Length + spanPastEnd; memoryStream.WriteByte(0x42); long expected = origLength + spanPastEnd + 1; Assert.Equal(expected, memoryStream.Position); Assert.Equal(expected, memoryStream.Length); } } [Fact] public static void MemoryStream_GetPositionTest_Negative() { int iArrLen = 100; byte[] bArr = new byte[iArrLen]; using (MemoryStream ms = new MemoryStream(bArr)) { long iCurrentPos = ms.Position; for (int i = -1; i > -6; i--) { Assert.Throws<ArgumentOutOfRangeException>(() => ms.Position = i); Assert.Equal(ms.Position, iCurrentPos); } } } [Fact] public static void MemoryStream_LengthTest() { using (MemoryStream ms2 = new MemoryStream()) { // [] Get the Length when position is at length ms2.SetLength(50); ms2.Position = 50; StreamWriter sw2 = new StreamWriter(ms2); for (char c = 'a'; c < 'f'; c++) sw2.Write(c); sw2.Flush(); Assert.Equal(55, ms2.Length); // Somewhere in the middle (set the length to be shorter.) ms2.SetLength(30); Assert.Equal(30, ms2.Length); Assert.Equal(30, ms2.Position); // Increase the length ms2.SetLength(100); Assert.Equal(100, ms2.Length); Assert.Equal(30, ms2.Position); } } [Fact] public static void MemoryStream_LengthTest_Negative() { using (MemoryStream ms2 = new MemoryStream()) { Assert.Throws<ArgumentOutOfRangeException>(() => ms2.SetLength(Int64.MaxValue)); Assert.Throws<ArgumentOutOfRangeException>(() => ms2.SetLength(-2)); } } [Fact] public static void MemoryStream_ReadTest_Negative() { MemoryStream ms2 = new MemoryStream(); Assert.Throws<ArgumentNullException>(() => ms2.Read(null, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ms2.Read(new byte[] { 1 }, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ms2.Read(new byte[] { 1 }, 0, -1)); AssertExtensions.Throws<ArgumentException>(null, () => ms2.Read(new byte[] { 1 }, 2, 0)); AssertExtensions.Throws<ArgumentException>(null, () => ms2.Read(new byte[] { 1 }, 0, 2)); ms2.Dispose(); Assert.Throws<ObjectDisposedException>(() => ms2.Read(new byte[] { 1 }, 0, 1)); } [Fact] public static void MemoryStream_WriteToTests() { using (MemoryStream ms2 = new MemoryStream()) { byte[] bytArrRet; byte[] bytArr = new byte[] { byte.MinValue, byte.MaxValue, 1, 2, 3, 4, 5, 6, 128, 250 }; // [] Write to FileStream, check the filestream ms2.Write(bytArr, 0, bytArr.Length); using (MemoryStream readonlyStream = new MemoryStream()) { ms2.WriteTo(readonlyStream); readonlyStream.Flush(); readonlyStream.Position = 0; bytArrRet = new byte[(int)readonlyStream.Length]; readonlyStream.Read(bytArrRet, 0, (int)readonlyStream.Length); for (int i = 0; i < bytArr.Length; i++) { Assert.Equal(bytArr[i], bytArrRet[i]); } } } // [] Write to memoryStream, check the memoryStream using (MemoryStream ms2 = new MemoryStream()) using (MemoryStream ms3 = new MemoryStream()) { byte[] bytArrRet; byte[] bytArr = new byte[] { byte.MinValue, byte.MaxValue, 1, 2, 3, 4, 5, 6, 128, 250 }; ms2.Write(bytArr, 0, bytArr.Length); ms2.WriteTo(ms3); ms3.Position = 0; bytArrRet = new byte[(int)ms3.Length]; ms3.Read(bytArrRet, 0, (int)ms3.Length); for (int i = 0; i < bytArr.Length; i++) { Assert.Equal(bytArr[i], bytArrRet[i]); } } } [Fact] public static void MemoryStream_WriteToTests_Negative() { using (MemoryStream ms2 = new MemoryStream()) { Assert.Throws<ArgumentNullException>(() => ms2.WriteTo(null)); ms2.Write(new byte[] { 1 }, 0, 1); MemoryStream readonlyStream = new MemoryStream(new byte[1028], false); Assert.Throws<NotSupportedException>(() => ms2.WriteTo(readonlyStream)); readonlyStream.Dispose(); // [] Pass in a closed stream Assert.Throws<ObjectDisposedException>(() => ms2.WriteTo(readonlyStream)); } } [Fact] public static void MemoryStream_CopyTo_Invalid() { MemoryStream memoryStream; using (memoryStream = new MemoryStream()) { AssertExtensions.Throws<ArgumentNullException>("destination", () => memoryStream.CopyTo(destination: null)); // Validate the destination parameter first. AssertExtensions.Throws<ArgumentNullException>("destination", () => memoryStream.CopyTo(destination: null, bufferSize: 0)); AssertExtensions.Throws<ArgumentNullException>("destination", () => memoryStream.CopyTo(destination: null, bufferSize: -1)); // Then bufferSize. AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => memoryStream.CopyTo(Stream.Null, bufferSize: 0)); // 0-length buffer doesn't make sense. AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => memoryStream.CopyTo(Stream.Null, bufferSize: -1)); } // After the Stream is disposed, we should fail on all CopyTos. AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => memoryStream.CopyTo(Stream.Null, bufferSize: 0)); // Not before bufferSize is validated. AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => memoryStream.CopyTo(Stream.Null, bufferSize: -1)); MemoryStream disposedStream = memoryStream; // We should throw first for the source being disposed... Assert.Throws<ObjectDisposedException>(() => memoryStream.CopyTo(disposedStream, 1)); // Then for the destination being disposed. memoryStream = new MemoryStream(); Assert.Throws<ObjectDisposedException>(() => memoryStream.CopyTo(disposedStream, 1)); // Then we should check whether we can't read but can write, which isn't possible for non-subclassed MemoryStreams. // THen we should check whether the destination can read but can't write. var readOnlyStream = new DelegateStream( canReadFunc: () => true, canWriteFunc: () => false ); Assert.Throws<NotSupportedException>(() => memoryStream.CopyTo(readOnlyStream, 1)); } [Theory] [MemberData(nameof(CopyToData))] public void CopyTo(Stream source, byte[] expected) { using (var destination = new MemoryStream()) { source.CopyTo(destination); Assert.InRange(source.Position, source.Length, int.MaxValue); // Copying the data should have read to the end of the stream or stayed past the end. Assert.Equal(expected, destination.ToArray()); } } public static IEnumerable<object[]> CopyToData() { // Stream is positioned @ beginning of data var data1 = new byte[] { 1, 2, 3 }; var stream1 = new MemoryStream(data1); yield return new object[] { stream1, data1 }; // Stream is positioned in the middle of data var data2 = new byte[] { 0xff, 0xf3, 0xf0 }; var stream2 = new MemoryStream(data2) { Position = 1 }; yield return new object[] { stream2, new byte[] { 0xf3, 0xf0 } }; // Stream is positioned after end of data var data3 = data2; var stream3 = new MemoryStream(data3) { Position = data3.Length + 1 }; yield return new object[] { stream3, Array.Empty<byte>() }; } } }
using OpenSim.Framework; using OpenSim.Region.Physics.Manager; /* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyrightD * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using OMV = OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { /* * Class to wrap all objects. * The rest of BulletSim doesn't need to keep checking for avatars or prims * unless the difference is significant. * * Variables in the physicsl objects are in three forms: * VariableName: used by the simulator and performs taint operations, etc * RawVariableName: direct reference to the BulletSim storage for the variable value * ForceVariableName: direct reference (store and fetch) to the value in the physics engine. * The last one should only be referenced in taint-time. */ /* * As of 20121221, the following are the call sequences (going down) for different script physical functions: * llApplyImpulse llApplyRotImpulse llSetTorque llSetForce * SOP.ApplyImpulse SOP.ApplyAngularImpulse SOP.SetAngularImpulse SOP.SetForce * SOG.ApplyImpulse SOG.ApplyAngularImpulse SOG.SetAngularImpulse * PA.AddForce PA.AddAngularForce PA.Torque = v PA.Force = v * BS.ApplyCentralForce BS.ApplyTorque */ // Flags used to denote which properties updates when making UpdateProperties calls to linksets, etc. public enum UpdatedProperties : uint { Position = 1 << 0, Orientation = 1 << 1, Velocity = 1 << 2, Acceleration = 1 << 3, RotationalVelocity = 1 << 4, EntPropUpdates = Position | Orientation | Velocity | Acceleration | RotationalVelocity, } public abstract class BSPhysObject : PhysicsActor { public const float FreeAxis = 1f; public readonly OMV.Vector3 LockedAxisFree = new OMV.Vector3(FreeAxis, FreeAxis, FreeAxis); // Reference to the physical body (btCollisionObject) of this object public BulletBody PhysBody; // Reference to the physical shape (btCollisionShape) of this object public BSShape PhysShape; protected BSPhysObject() { } protected BSPhysObject(BSScene parentScene, uint localID, string name, string typeName) { IsInitialized = false; PhysScene = parentScene; LocalID = localID; PhysObjectName = name; Name = name; // PhysicsActor also has the name of the object. Someday consolidate. TypeName = typeName; // The collection of things that push me around PhysicalActors = new BSActorCollection(PhysScene); // Initialize variables kept in base. GravModifier = 1.0f; Gravity = new OMV.Vector3(0f, 0f, BSParam.Gravity); HoverActive = false; // We don't have any physical representation yet. PhysBody = new BulletBody(localID); PhysShape = new BSShapeNull(); UserSetCenterOfMassDisplacement = null; PrimAssetState = PrimAssetCondition.Unknown; // Default material type. Also sets Friction, Restitution and Density. SetMaterial((int)MaterialAttributes.Material.Wood); CollisionCollection = new CollisionEventUpdate(); CollisionsLastReported = CollisionCollection; CollisionsLastTick = new CollisionEventUpdate(); CollisionsLastTickStep = -1; SubscribedEventsMs = 0; // Crazy values that will never be true CollidingStep = BSScene.NotASimulationStep; CollidingGroundStep = BSScene.NotASimulationStep; CollisionAccumulation = BSScene.NotASimulationStep; ColliderIsMoving = false; CollisionScore = 0; // All axis free. LockedLinearAxis = LockedAxisFree; LockedAngularAxis = LockedAxisFree; } // 'actors' act on the physical object to change or constrain its motion. These can range from // hovering to complex vehicle motion. // May be called at non-taint time as this just adds the actor to the action list and the real // work is done during the simulation step. // Note that, if the actor is already in the list and we are disabling same, the actor is just left // in the list disabled. public delegate BSActor CreateActor(); // The physical representation of the prim might require an asset fetch. // The asset state is first 'Unknown' then 'Waiting' then either 'Failed' or 'Fetched'. public enum PrimAssetCondition { Unknown, Waiting, FailedAssetFetch, FailedMeshing, Fetched } public override bool APIDActive { set { return; } } public override float APIDDamping { set { return; } } public override float APIDStrength { set { return; } } // For RotLookAt public override OMV.Quaternion APIDTarget { set { return; } } // The objects base shape information. Null if not a prim type shape. public PrimitiveBaseShape BaseShape { get; protected set; } // When the physical properties are updated, an EntityProperty holds the update values. // Keep the current and last EntityProperties to enable computation of differences // between the current update and the previous values. public EntityProperties CurrentEntityProperties { get; set; } public override float Density { get { return base.Density; } set { DetailLog("{0},BSPhysObject.Density,set,den={1}", LocalID, value); base.Density = value; } } public abstract float ForceBuoyancy { get; set; } public abstract OMV.Quaternion ForceOrientation { get; set; } public abstract OMV.Vector3 ForcePosition { get; set; } public abstract OMV.Vector3 ForceRotationalVelocity { get; set; } public abstract OMV.Vector3 ForceVelocity { get; set; } // The current velocity forward public virtual float ForwardSpeed { get { OMV.Vector3 characterOrientedVelocity = RawVelocity * OMV.Quaternion.Inverse(OMV.Quaternion.Normalize(RawOrientation)); return characterOrientedVelocity.X; } } // The gravity being applied to the object. A function of default grav, GravityModifier and Buoyancy. public virtual OMV.Vector3 Gravity { get; set; } public bool HoverActive { get; set; } public float HoverHeight { get; set; } public float HoverTau { get; set; } public PIDHoverType HoverType { get; set; } // The last value calculated for the prim's inertia public OMV.Vector3 Inertia { get; set; } // Set to 'true' when the object is completely initialized. // This mostly prevents property updates and collisions until the object is completely here. public bool IsInitialized { get; protected set; } // It can be confusing for an actor to know if it should move or update an object // depeneding on the setting of 'selected', 'physical, ... // This flag is the true test -- if true, the object is being acted on in the physical world public abstract bool IsPhysicallyActive { get; } public abstract bool IsSelected { get; } // Detailed state of the object. public abstract bool IsSolid { get; } public abstract bool IsStatic { get; } public abstract bool IsVolumeDetect { get; } public EntityProperties LastEntityProperties { get; set; } public OMV.Vector3 LockedAngularAxis { get; set; } public OMV.Vector3 LockedLinearAxis { get; set; } // Materialness public MaterialAttributes.Material Material { get; private set; } public bool MoveToTargetActive { get; set; } public OMV.Vector3 MoveToTargetTarget { get; set; } public float MoveToTargetTau { get; set; } // public override uint LocalID { get; set; } // Use the LocalID definition in PhysicsActor public string PhysObjectName { get; protected set; } public BSScene PhysScene { get; protected set; } public override bool PIDActive { set { MoveToTargetActive = value; } } // Used for llSetHoverHeight and maybe vehicle height. Hover Height will override MoveTo target's Z public override bool PIDHoverActive { set { HoverActive = value; } } public override float PIDHoverHeight { set { HoverHeight = value; } } public override float PIDHoverTau { set { HoverTau = value; } } public override PIDHoverType PIDHoverType { set { HoverType = value; } } public override OMV.Vector3 PIDTarget { set { MoveToTargetTarget = value; } } public override float PIDTau { set { MoveToTargetTau = value; } } public PrimAssetCondition PrimAssetState { get; set; } public OMV.Vector3 RawForce { get; set; } // Return the object mass without calculating it or having side effects public abstract float RawMass { get; } public virtual OMV.Quaternion RawOrientation { get; set; } public virtual OMV.Vector3 RawPosition { get; set; } public OMV.Vector3 RawTorque { get; set; } public OMV.Vector3 RawVelocity { get; set; } public virtual OMV.Vector3 Scale { get; set; } // The forward speed we are trying to achieve (TargetVelocity) public virtual float TargetVelocitySpeed { get { OMV.Vector3 characterOrientedVelocity = TargetVelocity * OMV.Quaternion.Inverse(OMV.Quaternion.Normalize(RawOrientation)); return characterOrientedVelocity.X; } } public string TypeName { get; protected set; } // The user can optionally set the center of mass. The user's setting will override any // computed center-of-mass (like in linksets). // Note this is a displacement from the root's coordinates. Zero means use the root prim as center-of-mass. public OMV.Vector3? UserSetCenterOfMassDisplacement { get; set; } // Enable physical actions. Bullet will keep sleeping non-moving physical objects so // they need waking up when parameters are changed. // Called in taint-time!! public void ActivateIfPhysical(bool forceIt) { if (PhysBody.HasPhysicalBody) { if (IsPhysical) { // Physical objects might need activating PhysScene.PE.Activate(PhysBody, forceIt); } else { // Clear the collision cache since we've changed some properties. PhysScene.PE.ClearCollisionProxyCache(PhysScene.World, PhysBody); } } } public override void AddAngularForce(OMV.Vector3 force, bool pushforce) { AddAngularForce(force, pushforce, false); } public abstract void AddAngularForce(OMV.Vector3 force, bool pushforce, bool inTaintTime); public abstract void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime); // Tell the object to clean up. public virtual void Destroy() { PhysicalActors.Enable(false); PhysScene.TaintedObject(LocalID, "BSPhysObject.Destroy", delegate() { PhysicalActors.Dispose(); }); } // zero means locked. one means free. // All axis are free public void EnableActor(bool enableActor, string actorName, CreateActor creator) { lock (PhysicalActors) { BSActor theActor; if (PhysicalActors.TryGetActor(actorName, out theActor)) { // The actor already exists so just turn it on or off DetailLog("{0},BSPhysObject.EnableActor,enablingExistingActor,name={1},enable={2}", LocalID, actorName, enableActor); theActor.Enabled = enableActor; } else { // The actor does not exist. If it should, create it. if (enableActor) { DetailLog("{0},BSPhysObject.EnableActor,creatingActor,name={1}", LocalID, actorName); theActor = creator(); PhysicalActors.Add(actorName, theActor); theActor.Enabled = true; } else { DetailLog("{0},BSPhysObject.EnableActor,notCreatingActorSinceNotEnabled,name={1}", LocalID, actorName); } } } } public virtual bool ForceBodyShapeRebuild(bool inTaintTime) { return false; } public override void SetMaterial(int material) { Material = (MaterialAttributes.Material)material; // Setting the material sets the material attributes also. // TODO: decide if this is necessary -- the simulator does this. MaterialAttributes matAttrib = BSMaterials.GetAttributes(Material, false); Friction = matAttrib.friction; Restitution = matAttrib.restitution; Density = matAttrib.density; // DetailLog("{0},{1}.SetMaterial,Mat={2},frict={3},rest={4},den={5}", LocalID, TypeName, Material, Friction, Restitution, Density); } // Set the raw mass but also update physical mass properties (inertia, ...) // 'inWorld' true if the object has already been added to the dynamic world. public abstract void UpdatePhysicalMassProperties(float mass, bool inWorld); // Update the physical location and motion of the object. Called with data from Bullet. public abstract void UpdateProperties(EntityProperties entprop); public abstract void ZeroAngularMotion(bool inTaintTime); // Stop all physical motion. public abstract void ZeroMotion(bool inTaintTime); // zero means locked. one means free. #region Collisions // On a collision, check the collider and remember if the last collider was moving // Used to modify the standing of avatars (avatars on stationary things stand still) public bool ColliderIsMoving; // 'true' if the last collider was a volume detect object public bool ColliderIsVolumeDetect; // This is the collision collection last reported to the Simulator. public CollisionEventUpdate CollisionsLastReported; // Remember the collisions recorded in the last tick for fancy collision checking // (like a BSCharacter walking up stairs). public CollisionEventUpdate CollisionsLastTick; // Used by BSCharacter to manage standing (and not slipping) public bool IsStationary; // The collisions that have been collected for the next collision reporting (throttled by subscription) protected CollisionEventUpdate CollisionCollection; private long CollisionsLastTickStep = -1; // The simulation step is telling this object about a collision. // Return 'true' if a collision was processed and should be sent up. // Return 'false' if this object is not enabled/subscribed/appropriate for or has already seen this collision. // Called at taint time from within the Step() function public delegate bool CollideCall(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth); public override bool CollidingGround { get { return (CollidingGroundStep == PhysScene.SimulationStep); } set { if (value) CollidingGroundStep = PhysScene.SimulationStep; else CollidingGroundStep = BSScene.NotASimulationStep; } } public override bool CollidingObj { get { return (CollidingObjectStep == PhysScene.SimulationStep); } set { if (value) CollidingObjectStep = PhysScene.SimulationStep; else CollidingObjectStep = BSScene.NotASimulationStep; } } public override float CollisionScore { get; set; } // Complex objects (like linksets) need to know if there is a collision on any part of // their shape. 'IsColliding' has an existing definition of reporting a collision on // only this specific prim or component of linksets. // 'HasSomeCollision' is defined as reporting if there is a collision on any part of // the complex body that this prim is the root of. public virtual bool HasSomeCollision { get { return IsColliding; } set { IsColliding = value; } } public override bool IsColliding { get { return (CollidingStep == PhysScene.SimulationStep); } set { if (value) CollidingStep = PhysScene.SimulationStep; else CollidingStep = BSScene.NotASimulationStep; } } // The simulation step that last had a collision with the ground protected long CollidingGroundStep { get; set; } // The simulation step that last collided with an object protected long CollidingObjectStep { get; set; } // The simulation step that last had a collision protected long CollidingStep { get; set; } // Count of collisions for this object protected long CollisionAccumulation { get; set; } // The collision flags we think are set in Bullet protected CollisionFlags CurrentCollisionFlags { get; set; } // Given subscription, the time that a collision may be passed up protected int NextCollisionOkTime { get; set; } // Requested number of milliseconds between collision events. Zero means disabled. protected int SubscribedEventsMs { get; set; } public virtual bool Collide(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { bool ret = false; // The following lines make IsColliding(), CollidingGround() and CollidingObj work CollidingStep = PhysScene.SimulationStep; if (collidingWith <= PhysScene.TerrainManager.HighestTerrainID) { CollidingGroundStep = PhysScene.SimulationStep; } else { CollidingObjectStep = PhysScene.SimulationStep; } CollisionAccumulation++; // For movement tests, remember if we are colliding with an object that is moving. ColliderIsMoving = collidee != null ? (collidee.RawVelocity != OMV.Vector3.Zero) : false; ColliderIsVolumeDetect = collidee != null ? (collidee.IsVolumeDetect) : false; // Make a collection of the collisions that happened the last simulation tick. // This is different than the collection created for sending up to the simulator as it is cleared every tick. if (CollisionsLastTickStep != PhysScene.SimulationStep) { CollisionsLastTick = new CollisionEventUpdate(); CollisionsLastTickStep = PhysScene.SimulationStep; } CollisionsLastTick.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth)); // If someone has subscribed for collision events log the collision so it will be reported up if (SubscribedEvents()) { CollisionCollection.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth)); DetailLog("{0},{1}.Collison.AddCollider,call,with={2},point={3},normal={4},depth={5},colliderMoving={6}", LocalID, TypeName, collidingWith, contactPoint, contactNormal, pentrationDepth, ColliderIsMoving); ret = true; } return ret; } // Because 'CollisionScore' is called many times while sorting, it should not be recomputed // each time called. So this is built to be light weight for each collision and to do // all the processing when the user asks for the info. public void ComputeCollisionScore() { // Scale the collision count by the time since the last collision. // The "+1" prevents dividing by zero. long timeAgo = PhysScene.SimulationStep - CollidingStep + 1; CollisionScore = CollisionAccumulation / timeAgo; } // Send the collected collisions into the simulator. // Called at taint time from within the Step() function thus no locking problems // with CollisionCollection and ObjectsWithNoMoreCollisions. // Return 'true' if there were some actual collisions passed up public virtual bool SendCollisions() { bool ret = true; // If the 'no collision' call, force it to happen right now so quick collision_end bool force = (CollisionCollection.Count == 0 && CollisionsLastReported.Count != 0); // throttle the collisions to the number of milliseconds specified in the subscription if (force || (PhysScene.SimulationNowTime >= NextCollisionOkTime)) { NextCollisionOkTime = PhysScene.SimulationNowTime + SubscribedEventsMs; // We are called if we previously had collisions. If there are no collisions // this time, send up one last empty event so OpenSim can sense collision end. if (CollisionCollection.Count == 0) { // If I have no collisions this time, remove me from the list of objects with collisions. ret = false; } DetailLog("{0},{1}.SendCollisionUpdate,call,numCollisions={2}", LocalID, TypeName, CollisionCollection.Count); base.SendCollisionUpdate(CollisionCollection); // Remember the collisions from this tick for some collision specific processing. CollisionsLastReported = CollisionCollection; // The CollisionCollection instance is passed around in the simulator. // Make sure we don't have a handle to that one and that a new one is used for next time. // This fixes an interesting 'gotcha'. If we call CollisionCollection.Clear() here, // a race condition is created for the other users of this instance. CollisionCollection = new CollisionEventUpdate(); } return ret; } // Return 'true' if the simulator wants collision events public override bool SubscribedEvents() { return (SubscribedEventsMs > 0); } // Subscribe for collision events. // Parameter is the millisecond rate the caller wishes collision events to occur. public override void SubscribeEvents(int ms) { // DetailLog("{0},{1}.SubscribeEvents,subscribing,ms={2}", LocalID, TypeName, ms); SubscribedEventsMs = ms; if (ms > 0) { // make sure first collision happens NextCollisionOkTime = Util.EnvironmentTickCountSubtract(SubscribedEventsMs); PhysScene.TaintedObject(LocalID, TypeName + ".SubscribeEvents", delegate() { if (PhysBody.HasPhysicalBody) CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); } else { // Subscribing for zero or less is the same as unsubscribing UnSubscribeEvents(); } } public override void UnSubscribeEvents() { // DetailLog("{0},{1}.UnSubscribeEvents,unsubscribing", LocalID, TypeName); SubscribedEventsMs = 0; PhysScene.TaintedObject(LocalID, TypeName + ".UnSubscribeEvents", delegate() { // Make sure there is a body there because sometimes destruction happens in an un-ideal order. if (PhysBody.HasPhysicalBody) CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); } #endregion Collisions #region Per Simulation Step actions public BSActorCollection PhysicalActors; // When an update to the physical properties happens, this event is fired to let // different actors to modify the update before it is passed around public delegate void PreUpdatePropertyAction(ref EntityProperties entprop); public event PreUpdatePropertyAction OnPreUpdateProperty; protected void TriggerPreUpdatePropertyAction(ref EntityProperties entprop) { PreUpdatePropertyAction actions = OnPreUpdateProperty; if (actions != null) actions(ref entprop); } #endregion Per Simulation Step actions // High performance detailed logging routine used by the physical objects. protected void DetailLog(string msg, params Object[] args) { if (PhysScene.PhysicsLogging.Enabled) PhysScene.DetailLog(msg, args); } } }
namespace AIM.Annotation.View.WinForms { partial class FormUserInfo { /// <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._btnSave = new System.Windows.Forms.Button(); this._btnCancel = new System.Windows.Forms.Button(); this._lblUserName = new System.Windows.Forms.Label(); this._lblLoginName = new System.Windows.Forms.Label(); this._lblRoleInTrial = new System.Windows.Forms.Label(); this._lblNumberWithinRoleInTrial = new System.Windows.Forms.Label(); this._tboxUserName = new System.Windows.Forms.TextBox(); this._tboxLoginName = new System.Windows.Forms.TextBox(); this._updownNumberWithinRoleInTrial = new System.Windows.Forms.NumericUpDown(); this._cmbRoleInTrial = new System.Windows.Forms.ComboBox(); ((System.ComponentModel.ISupportInitialize)(this._updownNumberWithinRoleInTrial)).BeginInit(); this.SuspendLayout(); // // _btnSave // this._btnSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this._btnSave.DialogResult = System.Windows.Forms.DialogResult.OK; this._btnSave.Location = new System.Drawing.Point(275, 150); this._btnSave.Name = "_btnSave"; this._btnSave.Size = new System.Drawing.Size(75, 23); this._btnSave.TabIndex = 8; this._btnSave.Text = "&Save"; this._btnSave.UseVisualStyleBackColor = true; this._btnSave.Click += new System.EventHandler(this.btnSave_Click); // // _btnCancel // this._btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this._btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this._btnCancel.Location = new System.Drawing.Point(356, 150); this._btnCancel.Name = "_btnCancel"; this._btnCancel.Size = new System.Drawing.Size(75, 23); this._btnCancel.TabIndex = 9; this._btnCancel.Text = "&Cancel"; this._btnCancel.UseVisualStyleBackColor = true; this._btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // _lblUserName // this._lblUserName.AutoSize = true; this._lblUserName.Location = new System.Drawing.Point(12, 16); this._lblUserName.Name = "_lblUserName"; this._lblUserName.Size = new System.Drawing.Size(88, 17); this._lblUserName.TabIndex = 0; this._lblUserName.Text = "User Name*:"; this._lblUserName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // _lblLoginName // this._lblLoginName.AutoSize = true; this._lblLoginName.Location = new System.Drawing.Point(12, 45); this._lblLoginName.Name = "_lblLoginName"; this._lblLoginName.Size = new System.Drawing.Size(93, 17); this._lblLoginName.TabIndex = 2; this._lblLoginName.Text = "Login Name*:"; // // _lblRoleInTrial // this._lblRoleInTrial.AutoSize = true; this._lblRoleInTrial.Location = new System.Drawing.Point(12, 74); this._lblRoleInTrial.Name = "_lblRoleInTrial"; this._lblRoleInTrial.Size = new System.Drawing.Size(88, 17); this._lblRoleInTrial.TabIndex = 4; this._lblRoleInTrial.Text = "Role In Trial:"; // // _lblNumberWithinRoleInTrial // this._lblNumberWithinRoleInTrial.AutoSize = true; this._lblNumberWithinRoleInTrial.Location = new System.Drawing.Point(12, 104); this._lblNumberWithinRoleInTrial.Name = "_lblNumberWithinRoleInTrial"; this._lblNumberWithinRoleInTrial.Size = new System.Drawing.Size(138, 17); this._lblNumberWithinRoleInTrial.TabIndex = 6; this._lblNumberWithinRoleInTrial.Text = "Number Within Role:"; // // _tboxUserName // this._tboxUserName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._tboxUserName.Location = new System.Drawing.Point(158, 13); this._tboxUserName.Name = "_tboxUserName"; this._tboxUserName.Size = new System.Drawing.Size(270, 22); this._tboxUserName.TabIndex = 1; // // _tboxLoginName // this._tboxLoginName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._tboxLoginName.Location = new System.Drawing.Point(158, 42); this._tboxLoginName.Name = "_tboxLoginName"; this._tboxLoginName.Size = new System.Drawing.Size(270, 22); this._tboxLoginName.TabIndex = 3; // // _updownNumberWithinRoleInTrial // this._updownNumberWithinRoleInTrial.Location = new System.Drawing.Point(158, 99); this._updownNumberWithinRoleInTrial.Maximum = new decimal(new int[] { 5000, 0, 0, 0}); this._updownNumberWithinRoleInTrial.Minimum = new decimal(new int[] { 1, 0, 0, -2147483648}); this._updownNumberWithinRoleInTrial.Name = "_updownNumberWithinRoleInTrial"; this._updownNumberWithinRoleInTrial.Size = new System.Drawing.Size(87, 22); this._updownNumberWithinRoleInTrial.TabIndex = 7; this._updownNumberWithinRoleInTrial.Value = new decimal(new int[] { 1, 0, 0, -2147483648}); // // _cmbRoleInTrial // this._cmbRoleInTrial.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._cmbRoleInTrial.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._cmbRoleInTrial.FormattingEnabled = true; this._cmbRoleInTrial.Items.AddRange(new object[] { "<Select Role>", "Performing", "Referring", "Requesting", "Recording", "Verifying", "Assisting", "Circulating", "Standby"}); this._cmbRoleInTrial.Location = new System.Drawing.Point(158, 70); this._cmbRoleInTrial.Name = "_cmbRoleInTrial"; this._cmbRoleInTrial.Size = new System.Drawing.Size(270, 24); this._cmbRoleInTrial.TabIndex = 5; // // FormUserInfo // this.AcceptButton = this._btnSave; this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this._btnCancel; this.ClientSize = new System.Drawing.Size(443, 185); this.Controls.Add(this._cmbRoleInTrial); this.Controls.Add(this._updownNumberWithinRoleInTrial); this.Controls.Add(this._tboxLoginName); this.Controls.Add(this._tboxUserName); this.Controls.Add(this._lblNumberWithinRoleInTrial); this.Controls.Add(this._lblRoleInTrial); this.Controls.Add(this._lblLoginName); this.Controls.Add(this._lblUserName); this.Controls.Add(this._btnCancel); this.Controls.Add(this._btnSave); this.MaximizeBox = false; this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(451, 224); this.Name = "FormUserInfo"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "AIM User Information"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormUserInfo_FormClosing); ((System.ComponentModel.ISupportInitialize)(this._updownNumberWithinRoleInTrial)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button _btnSave; private System.Windows.Forms.Button _btnCancel; private System.Windows.Forms.Label _lblUserName; private System.Windows.Forms.Label _lblLoginName; private System.Windows.Forms.Label _lblRoleInTrial; private System.Windows.Forms.Label _lblNumberWithinRoleInTrial; private System.Windows.Forms.TextBox _tboxUserName; private System.Windows.Forms.TextBox _tboxLoginName; private System.Windows.Forms.NumericUpDown _updownNumberWithinRoleInTrial; private System.Windows.Forms.ComboBox _cmbRoleInTrial; } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, 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. // #if !NETSTANDARD1_3 namespace NLog.Targets { using System; using System.Text; using System.Collections.Generic; using System.ComponentModel; using System.IO; using NLog.Common; using NLog.Config; /// <summary> /// Writes log messages to the console with customizable coloring. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/ColoredConsole-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/ColoredConsole-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="https://github.com/NLog/NLog/wiki/Configuration-file">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/ColoredConsole/NLog.config" /> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/ColoredConsole/Simple/Example.cs" /> /// </example> [Target("ColoredConsole")] public sealed class ColoredConsoleTarget : TargetWithLayoutHeaderAndFooter { /// <summary> /// Should logging being paused/stopped because of the race condition bug in Console.Writeline? /// </summary> /// <remarks> /// Console.Out.Writeline / Console.Error.Writeline could throw 'IndexOutOfRangeException', which is a bug. /// See https://stackoverflow.com/questions/33915790/console-out-and-console-error-race-condition-error-in-a-windows-service-written /// and https://connect.microsoft.com/VisualStudio/feedback/details/2057284/console-out-probable-i-o-race-condition-issue-in-multi-threaded-windows-service /// /// Full error: /// Error during session close: System.IndexOutOfRangeException: Probable I/ O race condition detected while copying memory. /// The I/ O package is not thread safe by default.In multithreaded applications, /// a stream must be accessed in a thread-safe way, such as a thread - safe wrapper returned by TextReader's or /// TextWriter's Synchronized methods.This also applies to classes like StreamWriter and StreamReader. /// /// </remarks> private bool _pauseLogging; private bool _disableColors; private IColoredConsolePrinter _consolePrinter; /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> public ColoredConsoleTarget() { WordHighlightingRules = new List<ConsoleWordHighlightingRule>(); RowHighlightingRules = new List<ConsoleRowHighlightingRule>(); _consolePrinter = CreateConsolePrinter(EnableAnsiOutput); } /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> /// <param name="name">Name of the target.</param> public ColoredConsoleTarget(string name) : this() { Name = name; } /// <summary> /// Gets or sets a value indicating whether the error stream (stderr) should be used instead of the output stream (stdout). /// </summary> /// <docgen category='Console Options' order='10' /> [Obsolete("Replaced by StdErr to align with ConsoleTarget. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool ErrorStream { get => StdErr; set => StdErr = value; } /// <summary> /// Gets or sets a value indicating whether to send the log messages to the standard error instead of the standard output. /// </summary> /// <docgen category='Console Options' order='10' /> public bool StdErr { get; set; } /// <summary> /// Gets or sets a value indicating whether to use default row highlighting rules. /// </summary> /// <remarks> /// The default rules are: /// <table> /// <tr> /// <th>Condition</th> /// <th>Foreground Color</th> /// <th>Background Color</th> /// </tr> /// <tr> /// <td>level == LogLevel.Fatal</td> /// <td>Red</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Error</td> /// <td>Yellow</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Warn</td> /// <td>Magenta</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Info</td> /// <td>White</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Debug</td> /// <td>Gray</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Trace</td> /// <td>DarkGray</td> /// <td>NoChange</td> /// </tr> /// </table> /// </remarks> /// <docgen category='Highlighting Rules' order='9' /> public bool UseDefaultRowHighlightingRules { get; set; } = true; /// <summary> /// The encoding for writing messages to the <see cref="Console"/>. /// </summary> /// <remarks>Has side effect</remarks> /// <docgen category='Console Options' order='10' /> public Encoding Encoding { get => ConsoleTargetHelper.GetConsoleOutputEncoding(_encoding, IsInitialized, _pauseLogging); set { if (ConsoleTargetHelper.SetConsoleOutputEncoding(value, IsInitialized, _pauseLogging)) _encoding = value; } } private Encoding _encoding; /// <summary> /// Gets or sets a value indicating whether to auto-check if the console is available. /// - Disables console writing if Environment.UserInteractive = False (Windows Service) /// - Disables console writing if Console Standard Input is not available (Non-Console-App) /// </summary> /// <docgen category='Console Options' order='10' /> public bool DetectConsoleAvailable { get; set; } /// <summary> /// Gets or sets a value indicating whether to auto-check if the console has been redirected to file /// - Disables coloring logic when System.Console.IsOutputRedirected = true /// </summary> /// <docgen category='Console Options' order='11' /> public bool DetectOutputRedirected { get; set; } /// <summary> /// Gets or sets a value indicating whether to auto-flush after <see cref="Console.WriteLine()"/> /// </summary> /// <remarks> /// Normally not required as standard Console.Out will have <see cref="StreamWriter.AutoFlush"/> = true, but not when pipe to file /// </remarks> /// <docgen category='Console Options' order='11' /> public bool AutoFlush { get; set; } /// <summary> /// Enables output using ANSI Color Codes /// </summary> /// <docgen category='Console Options' order='10' /> public bool EnableAnsiOutput { get; set; } /// <summary> /// Gets the row highlighting rules. /// </summary> /// <docgen category='Highlighting Rules' order='10' /> [ArrayParameter(typeof(ConsoleRowHighlightingRule), "highlight-row")] public IList<ConsoleRowHighlightingRule> RowHighlightingRules { get; private set; } /// <summary> /// Gets the word highlighting rules. /// </summary> /// <docgen category='Highlighting Rules' order='11' /> [ArrayParameter(typeof(ConsoleWordHighlightingRule), "highlight-word")] public IList<ConsoleWordHighlightingRule> WordHighlightingRules { get; private set; } /// <inheritdoc/> protected override void InitializeTarget() { _pauseLogging = false; _disableColors = false; if (DetectConsoleAvailable) { string reason; _pauseLogging = !ConsoleTargetHelper.IsConsoleAvailable(out reason); if (_pauseLogging) { InternalLogger.Info("{0}: Console detected as turned off. Disable DetectConsoleAvailable to skip detection. Reason: {1}", this, reason); } } if (_encoding != null) ConsoleTargetHelper.SetConsoleOutputEncoding(_encoding, true, _pauseLogging); #if !NET35 && !NET40 if (DetectOutputRedirected) { try { _disableColors = StdErr ? Console.IsErrorRedirected : Console.IsOutputRedirected; if (_disableColors) { InternalLogger.Info("{0}: Console output is redirected so no colors. Disable DetectOutputRedirected to skip detection.", this); if (!AutoFlush && GetOutput() is StreamWriter streamWriter && !streamWriter.AutoFlush) { AutoFlush = true; } } } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed checking if Console Output Redirected.", this); } } #endif base.InitializeTarget(); if (Header != null) { LogEventInfo lei = LogEventInfo.CreateNullEvent(); WriteToOutput(lei, RenderLogEvent(Header, lei)); } _consolePrinter = CreateConsolePrinter(EnableAnsiOutput); } private static IColoredConsolePrinter CreateConsolePrinter(bool enableAnsiOutput) { if (!enableAnsiOutput) return new ColoredConsoleSystemPrinter(); else return new ColoredConsoleAnsiPrinter(); } /// <inheritdoc/> protected override void CloseTarget() { if (Footer != null) { LogEventInfo lei = LogEventInfo.CreateNullEvent(); WriteToOutput(lei, RenderLogEvent(Footer, lei)); } ExplicitConsoleFlush(); base.CloseTarget(); } /// <inheritdoc/> protected override void FlushAsync(AsyncContinuation asyncContinuation) { try { ExplicitConsoleFlush(); base.FlushAsync(asyncContinuation); } catch (Exception ex) { asyncContinuation(ex); } } private void ExplicitConsoleFlush() { if (!_pauseLogging && !AutoFlush) { var output = GetOutput(); output.Flush(); } } /// <inheritdoc/> protected override void Write(LogEventInfo logEvent) { if (_pauseLogging) { //check early for performance (See also DetectConsoleAvailable) return; } WriteToOutput(logEvent, RenderLogEvent(Layout, logEvent)); } private void WriteToOutput(LogEventInfo logEvent, string message) { try { WriteToOutputWithColor(logEvent, message ?? string.Empty); } catch (Exception ex) when (ex is OverflowException || ex is IndexOutOfRangeException || ex is ArgumentOutOfRangeException) { // This is a bug and will therefore stop the logging. For docs, see the PauseLogging property. _pauseLogging = true; InternalLogger.Warn(ex, "{0}: {1} has been thrown and this is probably due to a race condition." + "Logging to the console will be paused. Enable by reloading the config or re-initialize the targets", this, ex.GetType()); } } private void WriteToOutputWithColor(LogEventInfo logEvent, string message) { string colorMessage = message; ConsoleColor? newForegroundColor = null; ConsoleColor? newBackgroundColor = null; if (!_disableColors) { var matchingRule = GetMatchingRowHighlightingRule(logEvent); if (WordHighlightingRules.Count > 0) { colorMessage = GenerateColorEscapeSequences(logEvent, message); } newForegroundColor = matchingRule.ForegroundColor != ConsoleOutputColor.NoChange ? (ConsoleColor)matchingRule.ForegroundColor : default(ConsoleColor?); newBackgroundColor = matchingRule.BackgroundColor != ConsoleOutputColor.NoChange ? (ConsoleColor)matchingRule.BackgroundColor : default(ConsoleColor?); } var consoleStream = GetOutput(); if (ReferenceEquals(colorMessage, message) && !newForegroundColor.HasValue && !newBackgroundColor.HasValue) { ConsoleTargetHelper.WriteLineThreadSafe(consoleStream, message, AutoFlush); } else { bool wordHighlighting = !ReferenceEquals(colorMessage, message); if (!wordHighlighting && message.IndexOf('\n') >= 0) { wordHighlighting = true; // Newlines requires additional handling when doing colors colorMessage = EscapeColorCodes(message); } WriteToOutputWithPrinter(consoleStream, colorMessage, newForegroundColor, newBackgroundColor, wordHighlighting); } } private void WriteToOutputWithPrinter(TextWriter consoleStream, string colorMessage, ConsoleColor? newForegroundColor, ConsoleColor? newBackgroundColor, bool wordHighlighting) { using (var targetBuilder = ReusableLayoutBuilder.Allocate()) { TextWriter consoleWriter = _consolePrinter.AcquireTextWriter(consoleStream, targetBuilder.Result); ConsoleColor? oldForegroundColor = null; ConsoleColor? oldBackgroundColor = null; try { if (wordHighlighting) { oldForegroundColor = _consolePrinter.ChangeForegroundColor(consoleWriter, newForegroundColor); oldBackgroundColor = _consolePrinter.ChangeBackgroundColor(consoleWriter, newBackgroundColor); var rowForegroundColor = newForegroundColor ?? oldForegroundColor; var rowBackgroundColor = newBackgroundColor ?? oldBackgroundColor; ColorizeEscapeSequences(_consolePrinter, consoleWriter, colorMessage, oldForegroundColor, oldBackgroundColor, rowForegroundColor, rowBackgroundColor); _consolePrinter.WriteLine(consoleWriter, string.Empty); } else { if (newForegroundColor.HasValue) { oldForegroundColor = _consolePrinter.ChangeForegroundColor(consoleWriter, newForegroundColor.Value); if (oldForegroundColor == newForegroundColor) oldForegroundColor = null; // No color restore is needed } if (newBackgroundColor.HasValue) { oldBackgroundColor = _consolePrinter.ChangeBackgroundColor(consoleWriter, newBackgroundColor.Value); if (oldBackgroundColor == newBackgroundColor) oldBackgroundColor = null; // No color restore is needed } _consolePrinter.WriteLine(consoleWriter, colorMessage); } } finally { _consolePrinter.ReleaseTextWriter(consoleWriter, consoleStream, oldForegroundColor, oldBackgroundColor, AutoFlush); } } } private ConsoleRowHighlightingRule GetMatchingRowHighlightingRule(LogEventInfo logEvent) { var matchingRule = GetMatchingRowHighlightingRule(RowHighlightingRules, logEvent); if (matchingRule is null && UseDefaultRowHighlightingRules) { matchingRule = GetMatchingRowHighlightingRule(_consolePrinter.DefaultConsoleRowHighlightingRules, logEvent); } return matchingRule ?? ConsoleRowHighlightingRule.Default; } private ConsoleRowHighlightingRule GetMatchingRowHighlightingRule(IList<ConsoleRowHighlightingRule> rules, LogEventInfo logEvent) { for (int i = 0; i < rules.Count; ++i) { var rule = rules[i]; if (rule.CheckCondition(logEvent)) return rule; } return null; } private string GenerateColorEscapeSequences(LogEventInfo logEvent, string message) { if (string.IsNullOrEmpty(message)) return message; message = EscapeColorCodes(message); using (var targetBuilder = ReusableLayoutBuilder.Allocate()) { StringBuilder sb = targetBuilder.Result; for (int i = 0; i < WordHighlightingRules.Count; ++i) { var hl = WordHighlightingRules[i]; var matches = hl.Matches(logEvent, message); if (matches is null || matches.Count == 0) continue; if (sb != null) sb.Length = 0; int previousIndex = 0; foreach (System.Text.RegularExpressions.Match match in matches) { sb = sb ?? new StringBuilder(message.Length + 5); sb.Append(message, previousIndex, match.Index - previousIndex); sb.Append('\a'); sb.Append((char)((int)hl.ForegroundColor + 'A')); sb.Append((char)((int)hl.BackgroundColor + 'A')); sb.Append(match.Value); sb.Append('\a'); sb.Append('X'); previousIndex = match.Index + match.Length; } if (sb?.Length > 0) { sb.Append(message, previousIndex, message.Length - previousIndex); message = sb.ToString(); } } } return message; } private static string EscapeColorCodes(string message) { if (message.IndexOf('\a') >= 0) message = message.Replace("\a", "\a\a"); return message; } private static void ColorizeEscapeSequences( IColoredConsolePrinter consolePrinter, TextWriter consoleWriter, string message, ConsoleColor? defaultForegroundColor, ConsoleColor? defaultBackgroundColor, ConsoleColor? rowForegroundColor, ConsoleColor? rowBackgroundColor) { var colorStack = new Stack<KeyValuePair<ConsoleColor?, ConsoleColor?>>(); colorStack.Push(new KeyValuePair<ConsoleColor?, ConsoleColor?>(rowForegroundColor, rowBackgroundColor)); int p0 = 0; while (p0 < message.Length) { int p1 = p0; while (p1 < message.Length && message[p1] >= 32) { p1++; } // text if (p1 != p0) { consolePrinter.WriteSubString(consoleWriter, message, p0, p1); } if (p1 >= message.Length) { p0 = p1; break; } // control characters char c1 = message[p1]; if (c1 == '\r' || c1 == '\n') { // Newline control characters var currentColorConfig = colorStack.Peek(); var resetForegroundColor = currentColorConfig.Key != defaultForegroundColor ? defaultForegroundColor : null; var resetBackgroundColor = currentColorConfig.Value != defaultBackgroundColor ? defaultBackgroundColor : null; consolePrinter.ResetDefaultColors(consoleWriter, resetForegroundColor, resetBackgroundColor); if (p1 + 1 < message.Length && message[p1 + 1] == '\n') { consolePrinter.WriteSubString(consoleWriter, message, p1, p1 + 2); p0 = p1 + 2; } else { consolePrinter.WriteChar(consoleWriter, c1); p0 = p1 + 1; } consolePrinter.ChangeForegroundColor(consoleWriter, currentColorConfig.Key, defaultForegroundColor); consolePrinter.ChangeBackgroundColor(consoleWriter, currentColorConfig.Value, defaultBackgroundColor); continue; } if (c1 != '\a' || p1 + 1 >= message.Length) { // Other control characters consolePrinter.WriteChar(consoleWriter, c1); p0 = p1 + 1; continue; } // coloring control characters char c2 = message[p1 + 1]; if (c2 == '\a') { consolePrinter.WriteChar(consoleWriter, '\a'); p0 = p1 + 2; continue; } if (c2 == 'X') { var oldColorConfig = colorStack.Pop(); var newColorConfig = colorStack.Peek(); if (newColorConfig.Key != oldColorConfig.Key || newColorConfig.Value != oldColorConfig.Value) { if ((oldColorConfig.Key.HasValue && !newColorConfig.Key.HasValue) || (oldColorConfig.Value.HasValue && !newColorConfig.Value.HasValue)) { consolePrinter.ResetDefaultColors(consoleWriter, defaultForegroundColor, defaultBackgroundColor); } consolePrinter.ChangeForegroundColor(consoleWriter, newColorConfig.Key, oldColorConfig.Key); consolePrinter.ChangeBackgroundColor(consoleWriter, newColorConfig.Value, oldColorConfig.Value); } p0 = p1 + 2; continue; } var currentForegroundColor = colorStack.Peek().Key; var currentBackgroundColor = colorStack.Peek().Value; var foreground = (ConsoleOutputColor)(c2 - 'A'); var background = (ConsoleOutputColor)(message[p1 + 2] - 'A'); if (foreground != ConsoleOutputColor.NoChange) { currentForegroundColor = (ConsoleColor)foreground; consolePrinter.ChangeForegroundColor(consoleWriter, currentForegroundColor); } if (background != ConsoleOutputColor.NoChange) { currentBackgroundColor = (ConsoleColor)background; consolePrinter.ChangeBackgroundColor(consoleWriter, currentBackgroundColor); } colorStack.Push(new KeyValuePair<ConsoleColor?, ConsoleColor?>(currentForegroundColor, currentBackgroundColor)); p0 = p1 + 3; } if (p0 < message.Length) { consolePrinter.WriteSubString(consoleWriter, message, p0, message.Length); } } private TextWriter GetOutput() { return StdErr ? Console.Error : Console.Out; } } } #endif
// 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: Provides a fast, AV free, cross-language way of ** accessing unmanaged memory in a random fashion. ** ** ===========================================================*/ using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Security.Permissions; using Microsoft.Win32.SafeHandles; using System.Diagnostics.Contracts; namespace System.IO { /// Perf notes: ReadXXX, WriteXXX (for basic types) acquire and release the /// SafeBuffer pointer rather than relying on generic Read(T) from SafeBuffer because /// this gives better throughput; benchmarks showed about 12-15% better. public class UnmanagedMemoryAccessor : IDisposable { [System.Security.SecurityCritical] // auto-generated private SafeBuffer _buffer; private Int64 _offset; [ContractPublicPropertyName("Capacity")] private Int64 _capacity; private FileAccess _access; private bool _isOpen; private bool _canRead; private bool _canWrite; protected UnmanagedMemoryAccessor() { _isOpen = false; } #region SafeBuffer ctors and initializers // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Method: Initialize(SafeBuffer, Int64, Int64, FileAccess):Void" Ring="1" /> // </SecurityKernel> [System.Security.SecuritySafeCritical] public UnmanagedMemoryAccessor(SafeBuffer buffer, Int64 offset, Int64 capacity) { Initialize(buffer, offset, capacity, FileAccess.Read); } [System.Security.SecuritySafeCritical] // auto-generated public UnmanagedMemoryAccessor(SafeBuffer buffer, Int64 offset, Int64 capacity, FileAccess access) { Initialize(buffer, offset, capacity, access); } [System.Security.SecuritySafeCritical] // auto-generated #pragma warning disable 618 [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] #pragma warning restore 618 protected void Initialize(SafeBuffer buffer, Int64 offset, Int64 capacity, FileAccess access) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (buffer.ByteLength < (UInt64)(offset + capacity)) { throw new ArgumentException(Environment.GetResourceString("Argument_OffsetAndCapacityOutOfBounds")); } if (access < FileAccess.Read || access > FileAccess.ReadWrite) { throw new ArgumentOutOfRangeException("access"); } Contract.EndContractBlock(); if (_isOpen) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice")); } unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { buffer.AcquirePointer(ref pointer); if (((byte*)((Int64)pointer + offset + capacity)) < pointer) { throw new ArgumentException(Environment.GetResourceString("Argument_UnmanagedMemAccessorWrapAround")); } } finally { if (pointer != null) { buffer.ReleasePointer(); } } } _offset = offset; _buffer = buffer; _capacity = capacity; _access = access; _isOpen = true; _canRead = (_access & FileAccess.Read) != 0; _canWrite = (_access & FileAccess.Write) != 0; } #endregion public Int64 Capacity { get { return _capacity; } } public bool CanRead { get { return _isOpen && _canRead; } } public bool CanWrite { get { return _isOpen && _canWrite; } } protected virtual void Dispose(bool disposing) { _isOpen = false; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected bool IsOpen { get { return _isOpen; } } public bool ReadBoolean(Int64 position) { int sizeOfType = sizeof(bool); EnsureSafeToRead(position, sizeOfType); byte b = InternalReadByte(position); return b != 0; } public byte ReadByte(Int64 position) { int sizeOfType = sizeof(byte); EnsureSafeToRead(position, sizeOfType); return InternalReadByte(position); } [System.Security.SecuritySafeCritical] // auto-generated public char ReadChar(Int64 position) { int sizeOfType = sizeof(char); EnsureSafeToRead(position, sizeOfType); char result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif result = *((char*)(pointer)); #if ALIGN_ACCESS } else { result = (char)( *pointer | *(pointer + 1) << 8 ) ; } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } // See comment above. [System.Security.SecuritySafeCritical] public Int16 ReadInt16(Int64 position) { int sizeOfType = sizeof(Int16); EnsureSafeToRead(position, sizeOfType); Int16 result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif result = *((Int16*)(pointer)); #if ALIGN_ACCESS } else { result = (Int16)( *pointer | *(pointer + 1) << 8 ); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } [System.Security.SecuritySafeCritical] // auto-generated public Int32 ReadInt32(Int64 position) { int sizeOfType = sizeof(Int32); EnsureSafeToRead(position, sizeOfType); Int32 result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif result = *((Int32*)(pointer)); #if ALIGN_ACCESS } else { result = (Int32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 ); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } [System.Security.SecuritySafeCritical] // auto-generated public Int64 ReadInt64(Int64 position) { int sizeOfType = sizeof(Int64); EnsureSafeToRead(position, sizeOfType); Int64 result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif result = *((Int64*)(pointer)); #if ALIGN_ACCESS } else { int lo = *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24; int hi = *(pointer + 4) | *(pointer + 5) << 8 | *(pointer + 6) << 16 | *(pointer + 7) << 24; result = (Int64)(((Int64)hi << 32) | (UInt32)lo); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } [System.Security.SecurityCritical] [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe Int32 UnsafeReadInt32(byte* pointer) { Int32 result; // check if pointer is aligned if (((int)pointer & (sizeof(Int32) - 1)) == 0) { result = *((Int32*)pointer); } else { result = (Int32)(*(pointer) | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24); } return result; } [System.Security.SecuritySafeCritical] // auto-generated public Decimal ReadDecimal(Int64 position) { const int ScaleMask = 0x00FF0000; const int SignMask = unchecked((int)0x80000000); int sizeOfType = sizeof(Decimal); EnsureSafeToRead(position, sizeOfType); unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); int lo = UnsafeReadInt32(pointer); int mid = UnsafeReadInt32(pointer + 4); int hi = UnsafeReadInt32(pointer + 8); int flags = UnsafeReadInt32(pointer + 12); // Check for invalid Decimal values if (!((flags & ~(SignMask | ScaleMask)) == 0 && (flags & ScaleMask) <= (28 << 16))) { throw new ArgumentException(Environment.GetResourceString("Arg_BadDecimal")); // Throw same Exception type as Decimal(int[]) ctor for compat } bool isNegative = (flags & SignMask) != 0; byte scale = (byte)(flags >> 16); return new decimal(lo, mid, hi, isNegative, scale); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated public Single ReadSingle(Int64 position) { int sizeOfType = sizeof(Single); EnsureSafeToRead(position, sizeOfType); Single result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif result = *((Single*)(pointer)); #if ALIGN_ACCESS } else { UInt32 tempResult = (UInt32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 ); result = *((float*)&tempResult); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } [System.Security.SecuritySafeCritical] // auto-generated public Double ReadDouble(Int64 position) { int sizeOfType = sizeof(Double); EnsureSafeToRead(position, sizeOfType); Double result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif result = *((Double*)(pointer)); #if ALIGN_ACCESS } else { UInt32 lo = (UInt32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 ); UInt32 hi = (UInt32)( *(pointer + 4) | *(pointer + 5) << 8 | *(pointer + 6) << 16 | *(pointer + 7) << 24 ); UInt64 tempResult = ((UInt64)hi) << 32 | lo; result = *((double*)&tempResult); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] public SByte ReadSByte(Int64 position) { int sizeOfType = sizeof(SByte); EnsureSafeToRead(position, sizeOfType); SByte result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); result = *((SByte*)pointer); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] public UInt16 ReadUInt16(Int64 position) { int sizeOfType = sizeof(UInt16); EnsureSafeToRead(position, sizeOfType); UInt16 result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif result = *((UInt16*)(pointer)); #if ALIGN_ACCESS } else { result = (UInt16)( *pointer | *(pointer + 1) << 8 ); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] public UInt32 ReadUInt32(Int64 position) { int sizeOfType = sizeof(UInt32); EnsureSafeToRead(position, sizeOfType); UInt32 result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif result = *((UInt32*)(pointer)); #if ALIGN_ACCESS } else { result = (UInt32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 ); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] public UInt64 ReadUInt64(Int64 position) { int sizeOfType = sizeof(UInt64); EnsureSafeToRead(position, sizeOfType); UInt64 result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif result = *((UInt64*)(pointer)); #if ALIGN_ACCESS } else { UInt32 lo = (UInt32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 ); UInt32 hi = (UInt32)( *(pointer + 4) | *(pointer + 5) << 8 | *(pointer + 6) << 16 | *(pointer + 7) << 24 ); result = (UInt64)(((UInt64)hi << 32) | lo ); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } // Reads a struct of type T from unmanaged memory, into the reference pointed to by ref value. // Note: this method is not safe, since it overwrites the contents of a structure, it can be // used to modify the private members of a struct. Furthermore, using this with a struct that // contains reference members will most likely cause the runtime to AV. Note, that despite // various checks made by the C++ code used by Marshal.PtrToStructure, Marshal.PtrToStructure // will still overwrite privates and will also crash the runtime when used with structs // containing reference members. For this reason, I am sticking an UnmanagedCode requirement // on this method to match Marshal.PtrToStructure. // Alos note that this method is most performant when used with medium to large sized structs // (larger than 8 bytes -- though this is number is JIT and architecture dependent). As // such, it is best to use the ReadXXX methods for small standard types such as ints, longs, // bools, etc. [System.Security.SecurityCritical] // auto-generated_required public void Read<T>(Int64 position, out T structure) where T : struct { if (position < 0) { throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (!_isOpen) { throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed")); } if (!CanRead) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_Reading")); } UInt32 sizeOfT = Marshal.SizeOfType(typeof(T)); if (position > _capacity - sizeOfT) { if (position >= _capacity) { throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired")); } else { throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToRead", typeof(T).FullName), "position"); } } structure = _buffer.Read<T>((UInt64)(_offset + position)); } // Reads 'count' structs of type T from unmanaged memory, into 'array' starting at 'offset'. // Note: this method is not safe, since it overwrites the contents of structures, it can // be used to modify the private members of a struct. Furthermore, using this with a // struct that contains reference members will most likely cause the runtime to AV. This // is consistent with Marshal.PtrToStructure. [System.Security.SecurityCritical] // auto-generated_required public int ReadArray<T>(Int64 position, T[] array, Int32 offset, Int32 count) where T : struct { if (array == null) { throw new ArgumentNullException("array", "Buffer cannot be null."); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (count < 0) { throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (array.Length - offset < count) { throw new ArgumentException(Environment.GetResourceString("Argument_OffsetAndLengthOutOfBounds")); } Contract.EndContractBlock(); if (!CanRead) { if (!_isOpen) { throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed")); } else { throw new NotSupportedException(Environment.GetResourceString("NotSupported_Reading")); } } if (position < 0) { throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } UInt32 sizeOfT = Marshal.AlignedSizeOf<T>(); // only check position and ask for fewer Ts if count is too big if (position >= _capacity) { throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired")); } int n = count; long spaceLeft = _capacity - position; if (spaceLeft < 0) { n = 0; } else { ulong spaceNeeded = (ulong)(sizeOfT * count); if ((ulong)spaceLeft < spaceNeeded) { n = (int)(spaceLeft / sizeOfT); } } _buffer.ReadArray<T>((UInt64)(_offset + position), array, offset, n); return n; } // ************** Write Methods ****************/ // The following 13 WriteXXX methods write a value of type XXX into unmanaged memory at 'positon'. // The bounds of the unmanaged memory are checked against to ensure that there is enough // space after 'position' to write a value of type XXX. XXX can be a bool, byte, char, decimal, // double, short, int, long, sbyte, float, ushort, uint, or ulong. public void Write(Int64 position, bool value) { int sizeOfType = sizeof(bool); EnsureSafeToWrite(position, sizeOfType); byte b = (byte)(value ? 1 : 0); InternalWrite(position, b); } public void Write(Int64 position, byte value) { int sizeOfType = sizeof(byte); EnsureSafeToWrite(position, sizeOfType); InternalWrite(position, value); } [System.Security.SecuritySafeCritical] // auto-generated public void Write(Int64 position, char value) { int sizeOfType = sizeof(char); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif *((char*)pointer) = value; #if ALIGN_ACCESS } else { *(pointer) = (byte)value; *(pointer+1) = (byte)(value >> 8); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated public void Write(Int64 position, Int16 value) { int sizeOfType = sizeof(Int16); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif *((Int16*)pointer) = value; #if ALIGN_ACCESS } else { *(pointer) = (byte)value; *(pointer + 1) = (byte)(value >> 8); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated public void Write(Int64 position, Int32 value) { int sizeOfType = sizeof(Int32); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif *((Int32*)pointer) = value; #if ALIGN_ACCESS } else { *(pointer) = (byte)value; *(pointer + 1) = (byte)(value >> 8); *(pointer + 2) = (byte)(value >> 16); *(pointer + 3) = (byte)(value >> 24); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated public void Write(Int64 position, Int64 value) { int sizeOfType = sizeof(Int64); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif *((Int64*)pointer) = value; #if ALIGN_ACCESS } else { *(pointer) = (byte)value; *(pointer + 1) = (byte)(value >> 8); *(pointer + 2) = (byte)(value >> 16); *(pointer + 3) = (byte)(value >> 24); *(pointer + 4) = (byte)(value >> 32); *(pointer + 5) = (byte)(value >> 40); *(pointer + 6) = (byte)(value >> 48); *(pointer + 7) = (byte)(value >> 56); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecurityCritical] [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe void UnsafeWriteInt32(byte* pointer, Int32 value) { // check if pointer is aligned if (((int)pointer & (sizeof(Int32) - 1)) == 0) { *((Int32*)pointer) = value; } else { *(pointer) = (byte)value; *(pointer + 1) = (byte)(value >> 8); *(pointer + 2) = (byte)(value >> 16); *(pointer + 3) = (byte)(value >> 24); } } [System.Security.SecuritySafeCritical] // auto-generated public void Write(Int64 position, Decimal value) { int sizeOfType = sizeof(Decimal); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); int* valuePtr = (int*)(&value); int flags = *valuePtr; int hi = *(valuePtr + 1); int lo = *(valuePtr + 2); int mid = *(valuePtr + 3); UnsafeWriteInt32(pointer, lo); UnsafeWriteInt32(pointer + 4, mid); UnsafeWriteInt32(pointer + 8, hi); UnsafeWriteInt32(pointer + 12, flags); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated public void Write(Int64 position, Single value) { int sizeOfType = sizeof(Single); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif *((Single*)pointer) = value; #if ALIGN_ACCESS } else { UInt32 tmpValue = *(UInt32*)&value; *(pointer) = (byte)tmpValue; *(pointer + 1) = (byte)(tmpValue >> 8); *(pointer + 2) = (byte)(tmpValue >> 16); *(pointer + 3) = (byte)(tmpValue >> 24); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated public void Write(Int64 position, Double value) { int sizeOfType = sizeof(Double); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif *((Double*)pointer) = value; #if ALIGN_ACCESS } else { UInt64 tmpValue = *(UInt64 *)&value; *(pointer) = (byte) tmpValue; *(pointer + 1) = (byte) (tmpValue >> 8); *(pointer + 2) = (byte) (tmpValue >> 16); *(pointer + 3) = (byte) (tmpValue >> 24); *(pointer + 4) = (byte) (tmpValue >> 32); *(pointer + 5) = (byte) (tmpValue >> 40); *(pointer + 6) = (byte) (tmpValue >> 48); *(pointer + 7) = (byte) (tmpValue >> 56); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] public void Write(Int64 position, SByte value) { int sizeOfType = sizeof(SByte); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); *((SByte*)pointer) = value; } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] public void Write(Int64 position, UInt16 value) { int sizeOfType = sizeof(UInt16); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif *((UInt16*)pointer) = value; #if ALIGN_ACCESS } else { *(pointer) = (byte)value; *(pointer + 1) = (byte)(value >> 8); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] public void Write(Int64 position, UInt32 value) { int sizeOfType = sizeof(UInt32); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif *((UInt32*)pointer) = value; #if ALIGN_ACCESS } else { *(pointer) = (byte)value; *(pointer + 1) = (byte)(value >> 8); *(pointer + 2) = (byte)(value >> 16); *(pointer + 3) = (byte)(value >> 24); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] public void Write(Int64 position, UInt64 value) { int sizeOfType = sizeof(UInt64); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif *((UInt64*)pointer) = value; #if ALIGN_ACCESS } else { *(pointer) = (byte)value; *(pointer + 1) = (byte)(value >> 8); *(pointer + 2) = (byte)(value >> 16); *(pointer + 3) = (byte)(value >> 24); *(pointer + 4) = (byte)(value >> 32); *(pointer + 5) = (byte)(value >> 40); *(pointer + 6) = (byte)(value >> 48); *(pointer + 7) = (byte)(value >> 56); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } // Writes the struct pointed to by ref value into unmanaged memory. Note that this method // is most performant when used with medium to large sized structs (larger than 8 bytes // though this is number is JIT and architecture dependent). As such, it is best to use // the WriteX methods for small standard types such as ints, longs, bools, etc. [System.Security.SecurityCritical] // auto-generated_required public void Write<T>(Int64 position, ref T structure) where T : struct { if (position < 0) { throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (!_isOpen) { throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed")); } if (!CanWrite) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_Writing")); } UInt32 sizeOfT = Marshal.SizeOfType(typeof(T)); if (position > _capacity - sizeOfT) { if (position >= _capacity) { throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired")); } else { throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToWrite", typeof(T).FullName), "position"); } } _buffer.Write<T>((UInt64)(_offset + position), structure); } // Writes 'count' structs of type T from 'array' (starting at 'offset') into unmanaged memory. [System.Security.SecurityCritical] // auto-generated_required public void WriteArray<T>(Int64 position, T[] array, Int32 offset, Int32 count) where T : struct { if (array == null) { throw new ArgumentNullException("array", "Buffer cannot be null."); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (count < 0) { throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (array.Length - offset < count) { throw new ArgumentException(Environment.GetResourceString("Argument_OffsetAndLengthOutOfBounds")); } if (position < 0) { throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (position >= Capacity) { throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired")); } Contract.EndContractBlock(); if (!_isOpen) { throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed")); } if (!CanWrite) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_Writing")); } _buffer.WriteArray<T>((UInt64)(_offset + position), array, offset, count); } [System.Security.SecuritySafeCritical] // auto-generated private byte InternalReadByte(Int64 position) { Contract.Assert(CanRead, "UMA not readable"); Contract.Assert(position >= 0, "position less than 0"); Contract.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)"); byte result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); result = *((byte*)(pointer + _offset + position)); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } [System.Security.SecuritySafeCritical] // auto-generated private void InternalWrite(Int64 position, byte value) { Contract.Assert(CanWrite, "UMA not writable"); Contract.Assert(position >= 0, "position less than 0"); Contract.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)"); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); *((byte*)(pointer + _offset + position)) = value; } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } private void EnsureSafeToRead(Int64 position, int sizeOfType) { if (!_isOpen) { throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed")); } if (!CanRead) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_Reading")); } if (position < 0) { throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (position > _capacity - sizeOfType) { if (position >= _capacity) { throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired")); } else { throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToRead"), "position"); } } } private void EnsureSafeToWrite(Int64 position, int sizeOfType) { if (!_isOpen) { throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed")); } if (!CanWrite) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_Writing")); } if (position < 0) { throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (position > _capacity - sizeOfType) { if (position >= _capacity) { throw new ArgumentOutOfRangeException("position", Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired")); } else { throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToWrite", "Byte"), "position"); } } } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Microsoft.DotNet.Cli.Utils; using Microsoft.Dnx.Runtime.Common.CommandLine; using Microsoft.DotNet.ProjectModel; using Microsoft.Extensions.Testing.Abstractions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NuGet.Frameworks; namespace Microsoft.DotNet.Tools.Test { public class TestCommand { public static int Run(string[] args) { DebugHelper.HandleDebugSwitch(ref args); var app = new CommandLineApplication(false) { Name = "dotnet test", FullName = ".NET Test Driver", Description = "Test Driver for the .NET Platform" }; app.HelpOption("-?|-h|--help"); var parentProcessIdOption = app.Option("--parentProcessId", "Used by IDEs to specify their process ID. Test will exit if the parent process does.", CommandOptionType.SingleValue); var portOption = app.Option("--port", "Used by IDEs to specify a port number to listen for a connection.", CommandOptionType.SingleValue); var configurationOption = app.Option("-c|--configuration <CONFIGURATION>", "Configuration under which to build", CommandOptionType.SingleValue); var projectPath = app.Argument("<PROJECT>", "The project to test, defaults to the current directory. Can be a path to a project.json or a project directory."); app.OnExecute(() => { try { // Register for parent process's exit event if (parentProcessIdOption.HasValue()) { int processId; if (!Int32.TryParse(parentProcessIdOption.Value(), out processId)) { throw new InvalidOperationException($"Invalid process id '{parentProcessIdOption.Value()}'. Process id must be an integer."); } RegisterForParentProcessExit(processId); } var projectContexts = CreateProjectContexts(projectPath.Value); var projectContext = projectContexts.First(); var testRunner = projectContext.ProjectFile.TestRunner; var configuration = configurationOption.Value() ?? Constants.DefaultConfiguration; if (portOption.HasValue()) { int port; if (!Int32.TryParse(portOption.Value(), out port)) { throw new InvalidOperationException($"{portOption.Value()} is not a valid port number."); } return RunDesignTime(port, projectContext, testRunner, configuration); } else { return RunConsole(projectContext, app, testRunner, configuration); } } catch (InvalidOperationException ex) { TestHostTracing.Source.TraceEvent(TraceEventType.Error, 0, ex.ToString()); return -1; } catch (Exception ex) { TestHostTracing.Source.TraceEvent(TraceEventType.Error, 0, ex.ToString()); return -2; } }); return app.Execute(args); } private static int RunConsole(ProjectContext projectContext, CommandLineApplication app, string testRunner, string configuration) { var commandArgs = new List<string> { projectContext.GetOutputPaths(configuration).CompilationFiles.Assembly }; commandArgs.AddRange(app.RemainingArguments); return Command.CreateDotNet($"{GetCommandName(testRunner)}", commandArgs, projectContext.TargetFramework) .ForwardStdErr() .ForwardStdOut() .Execute() .ExitCode; } private static int RunDesignTime(int port, ProjectContext projectContext, string testRunner, string configuration) { Console.WriteLine("Listening on port {0}", port); using (var channel = ReportingChannel.ListenOn(port)) { Console.WriteLine("Client accepted {0}", channel.Socket.LocalEndPoint); HandleDesignTimeMessages(projectContext, testRunner, channel, configuration); return 0; } } private static void HandleDesignTimeMessages(ProjectContext projectContext, string testRunner, ReportingChannel channel, string configuration) { try { var message = channel.ReadQueue.Take(); if (message.MessageType == "ProtocolVersion") { HandleProtocolVersionMessage(message, channel); // Take the next message, which should be the command to execute. message = channel.ReadQueue.Take(); } if (message.MessageType == "TestDiscovery.Start") { HandleTestDiscoveryStartMessage(testRunner, channel, projectContext, configuration); } else if (message.MessageType == "TestExecution.Start") { HandleTestExecutionStartMessage(testRunner, message, channel, projectContext, configuration); } else { HandleUnknownMessage(message, channel); } } catch (Exception ex) { channel.SendError(ex); } } private static void HandleProtocolVersionMessage(Message message, ReportingChannel channel) { var version = message.Payload?.ToObject<ProtocolVersionMessage>().Version; var supportedVersion = 1; TestHostTracing.Source.TraceInformation( "[ReportingChannel]: Requested Version: {0} - Using Version: {1}", version, supportedVersion); channel.Send(new Message() { MessageType = "ProtocolVersion", Payload = JToken.FromObject(new ProtocolVersionMessage() { Version = supportedVersion, }), }); } private static void HandleTestDiscoveryStartMessage(string testRunner, ReportingChannel channel, ProjectContext projectContext, string configuration) { TestHostTracing.Source.TraceInformation("Starting Discovery"); var commandArgs = new List<string> { projectContext.GetOutputPaths(configuration).CompilationFiles.Assembly }; commandArgs.AddRange(new[] { "--list", "--designtime" }); ExecuteRunnerCommand(testRunner, channel, commandArgs); channel.Send(new Message() { MessageType = "TestDiscovery.Response", }); TestHostTracing.Source.TraceInformation("Completed Discovery"); } private static void HandleTestExecutionStartMessage(string testRunner, Message message, ReportingChannel channel, ProjectContext projectContext, string configuration) { TestHostTracing.Source.TraceInformation("Starting Execution"); var commandArgs = new List<string> { projectContext.GetOutputPaths(configuration).CompilationFiles.Assembly }; commandArgs.AddRange(new[] { "--designtime" }); var tests = message.Payload?.ToObject<RunTestsMessage>().Tests; if (tests != null) { foreach (var test in tests) { commandArgs.Add("--test"); commandArgs.Add(test); } } ExecuteRunnerCommand(testRunner, channel, commandArgs); channel.Send(new Message() { MessageType = "TestExecution.Response", }); TestHostTracing.Source.TraceInformation("Completed Execution"); } private static void HandleUnknownMessage(Message message, ReportingChannel channel) { var error = string.Format("Unexpected message type: '{0}'.", message.MessageType); TestHostTracing.Source.TraceEvent(TraceEventType.Error, 0, error); channel.SendError(error); throw new InvalidOperationException(error); } private static void ExecuteRunnerCommand(string testRunner, ReportingChannel channel, List<string> commandArgs) { var result = Command.CreateDotNet(GetCommandName(testRunner), commandArgs, new NuGetFramework("DNXCore", Version.Parse("5.0"))) .OnOutputLine(line => { try { channel.Send(JsonConvert.DeserializeObject<Message>(line)); } catch { TestHostTracing.Source.TraceInformation(line); } }) .Execute(); if (result.ExitCode != 0) { channel.SendError($"{GetCommandName(testRunner)} returned '{result.ExitCode}'."); } } private static string GetCommandName(string testRunner) { return $"test-{testRunner}"; } private static void RegisterForParentProcessExit(int id) { var parentProcess = Process.GetProcesses().FirstOrDefault(p => p.Id == id); if (parentProcess != null) { parentProcess.EnableRaisingEvents = true; parentProcess.Exited += (sender, eventArgs) => { TestHostTracing.Source.TraceEvent( TraceEventType.Information, 0, "Killing the current process as parent process has exited."); Process.GetCurrentProcess().Kill(); }; } else { TestHostTracing.Source.TraceEvent( TraceEventType.Information, 0, "Failed to register for parent process's exit event. " + $"Parent process with id '{id}' was not found."); } } private static IEnumerable<ProjectContext> CreateProjectContexts(string projectPath) { projectPath = projectPath ?? Directory.GetCurrentDirectory(); if (!projectPath.EndsWith(Project.FileName)) { projectPath = Path.Combine(projectPath, Project.FileName); } if (!File.Exists(projectPath)) { throw new InvalidOperationException($"{projectPath} does not exist."); } return ProjectContext.CreateContextForEachFramework(projectPath); } } }
//------------------------------------------------------------------------------ // <copyright file="XmlSchemaSet.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ using System.Diagnostics; using System.Collections; using System.Threading; using System.Collections.Generic; using System.Runtime.Versioning; namespace System.Xml.Schema { #if SILVERLIGHT public class XmlSchemaSet { //Empty XmlSchemaSet class to enable backward compatibility of XmlSchemaProvideAttribute //Add private ctor to prevent constructing of this class XmlSchemaSet() { } } #else /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet"]/*' /> /// <devdoc> /// <para>The XmlSchemaSet contains a set of namespace URI's. /// Each namespace also have an associated private data cache /// corresponding to the XML-Data Schema or W3C XML Schema. /// The XmlSchemaSet will able to load only XSD schemas, /// and compile them into an internal "cooked schema representation". /// The Validate method then uses this internal representation for /// efficient runtime validation of any given subtree.</para> /// </devdoc> public class XmlSchemaSet { XmlNameTable nameTable; SchemaNames schemaNames; SortedList schemas; // List of source schemas //Event handling ValidationEventHandler internalEventHandler; ValidationEventHandler eventHandler; bool isCompiled = false; //Dictionary<Uri, XmlSchema> schemaLocations; //Dictionary<ChameleonKey, XmlSchema> chameleonSchemas; Hashtable schemaLocations; Hashtable chameleonSchemas; Hashtable targetNamespaces; bool compileAll; //Cached Compiled Info SchemaInfo cachedCompiledInfo; //Reader settings to parse schema XmlReaderSettings readerSettings; XmlSchema schemaForSchema; //Only one schema for schema per set //Schema compilation settings XmlSchemaCompilationSettings compilationSettings; internal XmlSchemaObjectTable elements; internal XmlSchemaObjectTable attributes; internal XmlSchemaObjectTable schemaTypes; internal XmlSchemaObjectTable substitutionGroups; private XmlSchemaObjectTable typeExtensions; //Thread safety private Object internalSyncObject; internal Object InternalSyncObject { get { if (internalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref internalSyncObject, o, null); } return internalSyncObject; } } //Constructors /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.XmlSchemaSet"]/*' /> /// <devdoc> /// <para>Construct a new empty schema schemas.</para> /// </devdoc> public XmlSchemaSet() : this(new NameTable()) { } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.XmlSchemaSet1"]/*' /> /// <devdoc> /// <para>Construct a new empty schema schemas with associated XmlNameTable. /// The XmlNameTable is used when loading schemas</para> /// </devdoc> public XmlSchemaSet(XmlNameTable nameTable) { if (nameTable == null) { throw new ArgumentNullException("nameTable"); } this.nameTable = nameTable; schemas = new SortedList(); /*schemaLocations = new Dictionary<Uri, XmlSchema>(); chameleonSchemas = new Dictionary<ChameleonKey, XmlSchema>();*/ schemaLocations = new Hashtable(); chameleonSchemas = new Hashtable(); targetNamespaces = new Hashtable(); internalEventHandler = new ValidationEventHandler(InternalValidationCallback); eventHandler = internalEventHandler; readerSettings = new XmlReaderSettings(); // we don't have to check XmlReaderSettings.EnableLegacyXmlSettings() here because the following // code will return same result either we are running on v4.5 or later if (readerSettings.GetXmlResolver() == null) { // The created resolver will be used in the schema validation only readerSettings.XmlResolver = new XmlUrlResolver(); readerSettings.IsXmlResolverSet = false; } readerSettings.NameTable = nameTable; readerSettings.DtdProcessing = DtdProcessing.Prohibit; compilationSettings = new XmlSchemaCompilationSettings(); cachedCompiledInfo = new SchemaInfo(); compileAll = true; } //Public Properties /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.NameTable"]/*' /> /// <devdoc> /// <para>The default XmlNameTable used by the XmlSchemaSet when loading new schemas.</para> /// </devdoc> public XmlNameTable NameTable { get { return nameTable;} } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.ValidationEventHandler"]/*' /> public event ValidationEventHandler ValidationEventHandler { add { eventHandler -= internalEventHandler; eventHandler += value; if (eventHandler == null) { eventHandler = internalEventHandler; } } remove { eventHandler -= value; if (eventHandler == null) { eventHandler = internalEventHandler; } } } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.IsCompiled"]/*' /> /// <devdoc> /// <para>IsCompiled is true when the schema set is in compiled state</para> /// </devdoc> public bool IsCompiled { get { return isCompiled; } } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.XmlResolver"]/*' /> /// <devdoc> /// <para></para> /// </devdoc> public XmlResolver XmlResolver { set { readerSettings.XmlResolver = value; } } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.CompilationSettings"]/*' /> /// <devdoc> /// <para></para> /// </devdoc> public XmlSchemaCompilationSettings CompilationSettings { get { return compilationSettings; } set { compilationSettings = value; } } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Count"]/*' /> /// <devdoc> /// <para>Returns the count of schemas in the set</para> /// </devdoc> public int Count { get { return schemas.Count; } } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.GlobalElements"]/*' /> /// <devdoc> /// <para></para> /// </devdoc> public XmlSchemaObjectTable GlobalElements { get { if (elements == null) { elements = new XmlSchemaObjectTable(); } return elements; } } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.GlobalAttributes"]/*' /> /// <devdoc> /// <para></para> /// </devdoc> public XmlSchemaObjectTable GlobalAttributes { get { if (attributes == null) { attributes = new XmlSchemaObjectTable(); } return attributes; } } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.GlobalTypes"]/*' /> /// <devdoc> /// <para></para> /// </devdoc> public XmlSchemaObjectTable GlobalTypes { get { if (schemaTypes == null) { schemaTypes = new XmlSchemaObjectTable(); } return schemaTypes; } } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.SubstitutionGroups"]/*' /> /// <devdoc> /// <para></para> /// </devdoc> /// internal XmlSchemaObjectTable SubstitutionGroups { get { if (substitutionGroups == null) { substitutionGroups = new XmlSchemaObjectTable(); } return substitutionGroups; } } /// <summary> /// Table of all types extensions /// </summary> internal Hashtable SchemaLocations { get { return schemaLocations; } } /// <summary> /// Table of all types extensions /// </summary> internal XmlSchemaObjectTable TypeExtensions { get { if (typeExtensions == null) { typeExtensions = new XmlSchemaObjectTable(); } return typeExtensions; } } //Public Methods /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Add1"]/*' /> /// <devdoc> /// <para>Add the schema located by the given URL into the schema schemas. /// If the given schema references other namespaces, the schemas for those other /// namespaces are NOT automatically loaded.</para> /// </devdoc> [ResourceConsumption(ResourceScope.Machine)] [ResourceExposure(ResourceScope.Machine)] public XmlSchema Add(String targetNamespace, String schemaUri) { if (schemaUri == null || schemaUri.Length == 0) { throw new ArgumentNullException("schemaUri"); } if (targetNamespace != null) { targetNamespace = XmlComplianceUtil.CDataNormalize(targetNamespace); } XmlSchema schema = null; lock (InternalSyncObject) { //Check if schema from url has already been added XmlResolver tempResolver = readerSettings.GetXmlResolver(); if ( tempResolver == null ) { tempResolver = new XmlUrlResolver(); } Uri tempSchemaUri = tempResolver.ResolveUri(null, schemaUri); if (IsSchemaLoaded(tempSchemaUri, targetNamespace, out schema)) { return schema; } else { //Url already not processed; Load SOM from url XmlReader reader = XmlReader.Create(schemaUri, readerSettings); try { schema = Add(targetNamespace, ParseSchema(targetNamespace, reader)); // while(reader.Read());// wellformness check; } finally { reader.Close(); } } } return schema; } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Add4"]/*' /> /// <devdoc> /// <para>Add the given schema into the schema schemas. /// If the given schema references other namespaces, the schemas for those /// other namespaces are NOT automatically loaded.</para> /// </devdoc> public XmlSchema Add(String targetNamespace, XmlReader schemaDocument) { if (schemaDocument == null) { throw new ArgumentNullException("schemaDocument"); } if (targetNamespace != null) { targetNamespace = XmlComplianceUtil.CDataNormalize(targetNamespace); } lock (InternalSyncObject) { XmlSchema schema = null; Uri schemaUri = new Uri(schemaDocument.BaseURI, UriKind.RelativeOrAbsolute); if (IsSchemaLoaded(schemaUri, targetNamespace, out schema)) { return schema; } else { DtdProcessing dtdProcessing = this.readerSettings.DtdProcessing; SetDtdProcessing(schemaDocument); schema = Add(targetNamespace, ParseSchema(targetNamespace, schemaDocument)); this.readerSettings.DtdProcessing = dtdProcessing; //reset dtdProcessing setting return schema; } } } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Add5"]/*' /> /// <devdoc> /// <para>Adds all the namespaces defined in the given schemas /// (including their associated schemas) to this schemas.</para> /// </devdoc> public void Add(XmlSchemaSet schemas) { if (schemas == null) { throw new ArgumentNullException("schemas"); } if (this == schemas) { return; } bool thisLockObtained = false; bool schemasLockObtained = false; try { while(true) { Monitor.TryEnter(InternalSyncObject, ref thisLockObtained); if (thisLockObtained) { Monitor.TryEnter(schemas.InternalSyncObject, ref schemasLockObtained); if (schemasLockObtained) { break; } else { Monitor.Exit(InternalSyncObject); //Give up this lock and try both again thisLockObtained = false; Thread.Yield(); //Let the thread that holds the lock run continue; } } } XmlSchema currentSchema; // if (schemas.IsCompiled) { CopyFromCompiledSet(schemas); } else { bool remove = false; string tns = null; foreach(XmlSchema schema in schemas.SortedSchemas.Values) { tns = schema.TargetNamespace; if (tns == null) { tns = string.Empty; } if (this.schemas.ContainsKey(schema.SchemaId) || FindSchemaByNSAndUrl(schema.BaseUri, tns, null) != null) { //Do not already existing url continue; } currentSchema = Add(schema.TargetNamespace, schema); if(currentSchema == null) { remove = true; break; } } //Remove all from the set if even one schema in the passed in set is not preprocessed. if (remove) { foreach(XmlSchema schema in schemas.SortedSchemas.Values) { //Remove all previously added schemas from the set this.schemas.Remove(schema.SchemaId); //Might remove schema that was already there and was not added thru this operation schemaLocations.Remove(schema.BaseUri); } } } } finally { //release locks on sets if (thisLockObtained) { Monitor.Exit(InternalSyncObject); } if (schemasLockObtained) { Monitor.Exit(schemas.InternalSyncObject); } } } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Add6"]/*' /> public XmlSchema Add(XmlSchema schema) { if (schema == null) { throw new ArgumentNullException("schema"); } lock (InternalSyncObject) { if (schemas.ContainsKey(schema.SchemaId)) { return schema; } return Add(schema.TargetNamespace, schema); } } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Remove"]/*' /> public XmlSchema Remove(XmlSchema schema) { return Remove(schema, true); } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.RemoveRecursive"]/*' /> public bool RemoveRecursive(XmlSchema schemaToRemove) { if (schemaToRemove == null) { throw new ArgumentNullException("schemaToRemove"); } if (!schemas.ContainsKey(schemaToRemove.SchemaId)) { return false; } lock (InternalSyncObject) { //Need to lock here so that remove cannot be called while the set is being compiled if (schemas.ContainsKey(schemaToRemove.SchemaId)) { //Need to check again //Build disallowedNamespaces list Hashtable disallowedNamespaces = new Hashtable(); disallowedNamespaces.Add(GetTargetNamespace(schemaToRemove), schemaToRemove); string importedNS; for (int i = 0; i < schemaToRemove.ImportedNamespaces.Count; i++) { importedNS = (string)schemaToRemove.ImportedNamespaces[i]; if (disallowedNamespaces[importedNS] == null) { disallowedNamespaces.Add(importedNS, importedNS); } } //Removal list is all schemas imported by this schema directly or indirectly //Need to check if other schemas in the set import schemaToRemove / any of its imports ArrayList needToCheckSchemaList = new ArrayList(); XmlSchema mainSchema; for (int i =0; i < schemas.Count; i++) { mainSchema = (XmlSchema)schemas.GetByIndex(i); if (mainSchema == schemaToRemove || schemaToRemove.ImportedSchemas.Contains(mainSchema)) { continue; } needToCheckSchemaList.Add(mainSchema); } mainSchema = null; for (int i = 0; i < needToCheckSchemaList.Count; i++) { //Perf: Not using nested foreach here mainSchema = (XmlSchema)needToCheckSchemaList[i]; if (mainSchema.ImportedNamespaces.Count > 0) { foreach(string tns in disallowedNamespaces.Keys) { if (mainSchema.ImportedNamespaces.Contains(tns)) { SendValidationEvent(new XmlSchemaException(Res.Sch_SchemaNotRemoved, string.Empty), XmlSeverityType.Warning); return false; } } } } Remove(schemaToRemove, true); for (int i = 0; i < schemaToRemove.ImportedSchemas.Count; ++i) { XmlSchema impSchema = (XmlSchema)schemaToRemove.ImportedSchemas[i]; Remove(impSchema, true); } return true; } } return false; } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Contains1"]/*' /> public bool Contains(String targetNamespace) { if (targetNamespace == null) { targetNamespace = string.Empty; } return targetNamespaces[targetNamespace] != null; } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Contains2"]/*' /> public bool Contains(XmlSchema schema) { if (schema == null) { throw new ArgumentNullException("schema"); } return schemas.ContainsValue(schema); } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Compile"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Compile() { if (isCompiled) { return; } if (schemas.Count == 0) { ClearTables(); //Clear any previously present compiled state left by calling just Remove() on the set cachedCompiledInfo = new SchemaInfo(); isCompiled = true; compileAll = false; return; } lock (InternalSyncObject) { if (!isCompiled) { //Locking before checking isCompiled to avoid problems with double locking Compiler compiler = new Compiler(nameTable, eventHandler, schemaForSchema, compilationSettings); SchemaInfo newCompiledInfo = new SchemaInfo(); int schemaIndex = 0; if (!compileAll) { //if we are not compiling everything again, Move the pre-compiled schemas to the compiler's tables compiler.ImportAllCompiledSchemas(this); } try { //First thing to do in the try block is to acquire locks since finally will try to release them. //If we dont accuire the locks first, and an exception occurs in the code before the locking code, then Threading.SynchronizationLockException will be thrown //when attempting to release it in the finally block XmlSchema currentSchema; XmlSchema xmlNSSchema = Preprocessor.GetBuildInSchema(); for (schemaIndex = 0; schemaIndex < schemas.Count; schemaIndex++) { currentSchema = (XmlSchema)schemas.GetByIndex(schemaIndex); //Lock schema to be compiled #pragma warning disable 0618 //@ Monitor.Enter(currentSchema); #pragma warning restore 0618 if (!currentSchema.IsPreprocessed) { SendValidationEvent(new XmlSchemaException(Res.Sch_SchemaNotPreprocessed, string.Empty), XmlSeverityType.Error); isCompiled = false; return; } if (currentSchema.IsCompiledBySet) { if (!compileAll) { continue; } else if ((object)currentSchema == (object)xmlNSSchema) { // prepare for xml namespace schema without cleanup compiler.Prepare(currentSchema, false); continue; } } compiler.Prepare(currentSchema, true); } isCompiled = compiler.Execute(this, newCompiledInfo); if (isCompiled) { if (!compileAll) { newCompiledInfo.Add(cachedCompiledInfo, eventHandler); //Add all the items from the old to the new compiled object } compileAll = false; cachedCompiledInfo = newCompiledInfo; //Replace the compiled info in the set after successful compilation } } finally { //Release locks on all schemas XmlSchema currentSchema; if (schemaIndex == schemas.Count) { schemaIndex--; } for (int i = schemaIndex; i >= 0; i--) { currentSchema = (XmlSchema)schemas.GetByIndex(i); if (currentSchema == Preprocessor.GetBuildInSchema()) { //dont re-set compiled flags for xml namespace schema Monitor.Exit(currentSchema); continue; } currentSchema.IsCompiledBySet = isCompiled; Monitor.Exit(currentSchema); } } } } return; } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Reprocess"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSchema Reprocess(XmlSchema schema) { // Due to bug 644477 - this method is tightly coupled (THE CODE IS BASICALLY COPIED) to Remove, Add and AddSchemaToSet // methods. If you change anything here *make sure* to update Remove/Add/AddSchemaToSet method(s) accordingly. // The only difference is that we don't touch .schemas collection here to not break a code like this: // foreach(XmlSchema s in schemaset.schemas) { schemaset.Reprocess(s); } // This is by purpose. if (schema == null) { throw new ArgumentNullException("schema"); } if (!schemas.ContainsKey(schema.SchemaId)) { throw new ArgumentException(Res.GetString(Res.Sch_SchemaDoesNotExist), "schema"); } XmlSchema originalSchema = schema; lock (InternalSyncObject) { //Lock set so that set cannot be compiled in another thread // This code is copied from method: // Remove(XmlSchema schema, bool forceCompile) // If you changed anything here go and change the same in Remove(XmlSchema schema, bool forceCompile) method #region Copied from Remove(XmlSchema schema, bool forceCompile) RemoveSchemaFromGlobalTables(schema); RemoveSchemaFromCaches(schema); if (schema.BaseUri != null) { schemaLocations.Remove(schema.BaseUri); } string tns = GetTargetNamespace(schema); if (Schemas(tns).Count == 0) { //This is the only schema for that namespace targetNamespaces.Remove(tns); } isCompiled = false; compileAll = true; //Force compilation of the whole set; This is when the set is not completely thread-safe #endregion //Copied from Remove(XmlSchema schema, bool forceCompile) // This code is copied from method: // Add(string targetNamespace, XmlSchema schema) // If you changed anything here go and change the same in Add(string targetNamespace, XmlSchema schema) method #region Copied from Add(string targetNamespace, XmlSchema schema) if (schema.ErrorCount != 0) { //Schema with parsing errors cannot be loaded return originalSchema; } if (PreprocessSchema(ref schema, schema.TargetNamespace)) { //No perf opt for already compiled schemas // This code is copied from method: // AddSchemaToSet(XmlSchema schema) // If you changed anything here go and change the same in AddSchemaToSet(XmlSchema schema) method #region Copied from AddSchemaToSet(XmlSchema schema) //Add to targetNamespaces table if (targetNamespaces[tns] == null) { targetNamespaces.Add(tns, tns); } if (schemaForSchema == null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] != null) { //it has xs:anyType schemaForSchema = schema; } for (int i = 0; i < schema.ImportedSchemas.Count; ++i) { //Once preprocessed external schemas property is set XmlSchema s = (XmlSchema)schema.ImportedSchemas[i]; if (!schemas.ContainsKey(s.SchemaId)) { schemas.Add(s.SchemaId, s); } tns = GetTargetNamespace(s); if (targetNamespaces[tns] == null) { targetNamespaces.Add(tns, tns); } if (schemaForSchema == null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] != null) { //it has xs:anyType schemaForSchema = schema; } } #endregion //Copied from AddSchemaToSet(XmlSchema schema) return schema; } #endregion // Copied from Add(string targetNamespace, XmlSchema schema) return originalSchema; } } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.CopyTo"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void CopyTo(XmlSchema[] schemas, int index) { if (schemas == null) throw new ArgumentNullException("schemas"); if (index < 0 || index > schemas.Length -1 ) throw new ArgumentOutOfRangeException("index"); this.schemas.Values.CopyTo(schemas, index); } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Schemas1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public ICollection Schemas() { return schemas.Values; } /// <include file='doc\XmlSchemaSet.uex' path='docs/doc[@for="XmlSchemaSet.Schemas1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public ICollection Schemas(String targetNamespace) { ArrayList tnsSchemas = new ArrayList(); XmlSchema currentSchema; if (targetNamespace == null) { targetNamespace = string.Empty; } for (int i=0; i < schemas.Count; i++) { currentSchema = (XmlSchema)schemas.GetByIndex(i); if (GetTargetNamespace(currentSchema) == targetNamespace) { tnsSchemas.Add(currentSchema); } } return tnsSchemas; } //Internal Methods private XmlSchema Add(string targetNamespace, XmlSchema schema) { // Due to bug 644477 - this method is tightly coupled (THE CODE IS BASICALLY COPIED) to Reprocess // method. If you change anything here *make sure* to update Reprocess method accordingly. if (schema == null || schema.ErrorCount != 0) { //Schema with parsing errors cannot be loaded return null; } // This code is copied to method: // Reprocess(XmlSchema schema) // If you changed anything here go and change the same in Reprocess(XmlSchema schema) method if (PreprocessSchema(ref schema, targetNamespace)) { //No perf opt for already compiled schemas AddSchemaToSet(schema); isCompiled = false; return schema; } return null; } #if TRUST_COMPILE_STATE private void AddCompiledSchema(XmlSchema schema) { if (schema.IsCompiledBySet ) { //trust compiled state always if it is not a chameleon schema VerifyTables(); SchemaInfo newCompiledInfo = new SchemaInfo(); XmlSchemaObjectTable substitutionGroupsTable = null; if (!AddToCompiledInfo(schema, newCompiledInfo, ref substitutionGroupsTable)) { //Error while adding main schema return null; } foreach (XmlSchema impSchema in schema.ImportedSchemas) { if (!AddToCompiledInfo(impSchema, newCompiledInfo, ref substitutionGroupsTable)) { //Error while adding imports return null; } } newCompiledInfo.Add(cachedCompiledInfo, eventHandler); //Add existing compiled info cachedCompiledInfo = newCompiledInfo; if (substitutionGroupsTable != null) { ProcessNewSubstitutionGroups(substitutionGroupsTable, true); } if (schemas.Count == 0) { //If its the first compiled schema being added, then set doesnt need to be compiled isCompiled = true; compileAll = false; } AddSchemaToSet(schema); return schema; } } private bool AddToCompiledInfo(XmlSchema schema, SchemaInfo newCompiledInfo, ref XmlSchemaObjectTable substTable) { //Add schema's compiled tables to the set if (schema.BaseUri != null && schemaLocations[schema.BaseUri] == null) { //Update schemaLocations table schemaLocations.Add(schema.BaseUri, schema); } foreach (XmlSchemaElement element in schema.Elements.Values) { if(!AddToTable(elements, element.QualifiedName, element)) { RemoveSchemaFromGlobalTables(schema); return false; } XmlQualifiedName head = element.SubstitutionGroup; if (!head.IsEmpty) { if (substTable == null) { substTable = new XmlSchemaObjectTable(); } XmlSchemaSubstitutionGroup substitutionGroup = (XmlSchemaSubstitutionGroup)substTable[head]; if (substitutionGroup == null) { substitutionGroup = new XmlSchemaSubstitutionGroup(); substitutionGroup.Examplar = head; substTable.Add(head, substitutionGroup); } ArrayList members = substitutionGroup.Members; if (!members.Contains(element)) { //Members might contain element if the same schema is included and imported through different paths. Imp, hence will be added to set directly members.Add(element); } } } foreach (XmlSchemaAttribute attribute in schema.Attributes.Values) { if (!AddToTable(attributes, attribute.QualifiedName, attribute)) { RemoveSchemaFromGlobalTables(schema); return false; } } foreach (XmlSchemaType schemaType in schema.SchemaTypes.Values) { if (!AddToTable(schemaTypes, schemaType.QualifiedName, schemaType)) { RemoveSchemaFromGlobalTables(schema); return false; } } schema.AddCompiledInfo(newCompiledInfo); return true; } #endif //For use by the validator when loading schemaLocations in the instance internal void Add(String targetNamespace, XmlReader reader, Hashtable validatedNamespaces) { if (reader == null) { throw new ArgumentNullException("reader"); } if (targetNamespace == null) { targetNamespace = string.Empty; } if (validatedNamespaces[targetNamespace] != null) { if (FindSchemaByNSAndUrl(new Uri(reader.BaseURI, UriKind.RelativeOrAbsolute), targetNamespace, null) != null) { return; } else { throw new XmlSchemaException(Res.Sch_ComponentAlreadySeenForNS, targetNamespace); } } //Not locking set as this will not be accessible outside the validator XmlSchema schema; if (IsSchemaLoaded(new Uri(reader.BaseURI, UriKind.RelativeOrAbsolute), targetNamespace, out schema)) { return; } else { //top-level schema not present for same url schema = ParseSchema(targetNamespace, reader); //Store the previous locations DictionaryEntry[] oldLocations = new DictionaryEntry[schemaLocations.Count]; schemaLocations.CopyTo(oldLocations, 0); //Add to set Add(targetNamespace, schema); if (schema.ImportedSchemas.Count > 0) { //Check imports string tns; for (int i = 0; i < schema.ImportedSchemas.Count; ++i) { XmlSchema impSchema = (XmlSchema)schema.ImportedSchemas[i]; tns = impSchema.TargetNamespace; if (tns == null) { tns = string.Empty; } if (validatedNamespaces[tns] != null && (FindSchemaByNSAndUrl(impSchema.BaseUri, tns, oldLocations) == null) ) { RemoveRecursive(schema); throw new XmlSchemaException(Res.Sch_ComponentAlreadySeenForNS, tns); } } } } } internal XmlSchema FindSchemaByNSAndUrl(Uri schemaUri, string ns, DictionaryEntry[] locationsTable) { if (schemaUri == null || schemaUri.OriginalString.Length == 0) { return null; } XmlSchema schema = null; if (locationsTable == null) { schema = (XmlSchema)schemaLocations[schemaUri]; } else { for (int i = 0; i < locationsTable.Length; i++) { if (schemaUri.Equals(locationsTable[i].Key)) { schema = (XmlSchema)locationsTable[i].Value; break; } } } if (schema != null) { Debug.Assert(ns != null); string tns = schema.TargetNamespace == null ? string.Empty : schema.TargetNamespace; if (tns == ns) { return schema; } else if (tns == string.Empty) { //There could be a chameleon for same ns // It is OK to pass in the schema we have found so far, since it must have the schemaUri we're looking for // (we found it that way above) and it must be the original chameleon schema (the one without target ns) // as we don't add the chameleon copies into the locations tables above. Debug.Assert(schema.BaseUri.Equals(schemaUri)); ChameleonKey cKey = new ChameleonKey(ns, schema); schema = (XmlSchema)chameleonSchemas[cKey]; //Need not clone if a schema for that namespace already exists } else { schema = null; } } return schema; } private void SetDtdProcessing(XmlReader reader) { if (reader.Settings != null) { this.readerSettings.DtdProcessing = reader.Settings.DtdProcessing; } else { XmlTextReader v1Reader = reader as XmlTextReader; if (v1Reader != null) { this.readerSettings.DtdProcessing = v1Reader.DtdProcessing; } } } private void AddSchemaToSet(XmlSchema schema) { // Due to bug 644477 - this method is tightly coupled (THE CODE IS BASICALLY COPIED) to Reprocess // method. If you change anything here *make sure* to update Reprocess method accordingly. schemas.Add(schema.SchemaId, schema); //Add to targetNamespaces table // This code is copied to method: // Reprocess(XmlSchema schema) // If you changed anything here go and change the same in Reprocess(XmlSchema schema) method #region This code is copied to Reprocess(XmlSchema schema) method string tns = GetTargetNamespace(schema); if (targetNamespaces[tns] == null) { targetNamespaces.Add(tns, tns); } if (schemaForSchema == null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] != null) { //it has xs:anyType schemaForSchema = schema; } for (int i = 0; i < schema.ImportedSchemas.Count; ++i) { //Once preprocessed external schemas property is set XmlSchema s = (XmlSchema)schema.ImportedSchemas[i]; if (!schemas.ContainsKey(s.SchemaId)) { schemas.Add(s.SchemaId, s); } tns = GetTargetNamespace(s); if (targetNamespaces[tns] == null) { targetNamespaces.Add(tns, tns); } if (schemaForSchema == null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] != null) { //it has xs:anyType schemaForSchema = schema; } } #endregion // This code is copied to Reprocess(XmlSchema schema) method } private void ProcessNewSubstitutionGroups(XmlSchemaObjectTable substitutionGroupsTable, bool resolve) { foreach(XmlSchemaSubstitutionGroup substGroup in substitutionGroupsTable.Values) { if (resolve) { //Resolve substitutionGroups within this schema ResolveSubstitutionGroup(substGroup, substitutionGroupsTable); } //Add or Merge new substitutionGroups with those that already exist in the set XmlQualifiedName head = substGroup.Examplar; XmlSchemaSubstitutionGroup oldSubstGroup = (XmlSchemaSubstitutionGroup)substitutionGroups[head]; if (oldSubstGroup != null) { for (int i = 0; i < substGroup.Members.Count; ++i) { if (!oldSubstGroup.Members.Contains(substGroup.Members[i])) { oldSubstGroup.Members.Add(substGroup.Members[i]); } } } else { AddToTable(substitutionGroups, head, substGroup); } } } private void ResolveSubstitutionGroup(XmlSchemaSubstitutionGroup substitutionGroup, XmlSchemaObjectTable substTable) { List<XmlSchemaElement> newMembers = null; XmlSchemaElement headElement = (XmlSchemaElement)elements[substitutionGroup.Examplar]; if (substitutionGroup.Members.Contains(headElement)) {// already checked return; } for (int i = 0; i < substitutionGroup.Members.Count; ++i) { XmlSchemaElement element = (XmlSchemaElement)substitutionGroup.Members[i]; //Chain to other head's that are members of this head's substGroup XmlSchemaSubstitutionGroup g = (XmlSchemaSubstitutionGroup)substTable[element.QualifiedName]; if (g != null) { ResolveSubstitutionGroup(g, substTable); for (int j = 0; j < g.Members.Count; ++j) { XmlSchemaElement element1 = (XmlSchemaElement)g.Members[j]; if (element1 != element) { //Exclude the head if (newMembers == null) { newMembers = new List<XmlSchemaElement>(); } newMembers.Add(element1); } } } } if (newMembers != null) { for (int i = 0; i < newMembers.Count; ++i) { substitutionGroup.Members.Add(newMembers[i]); } } substitutionGroup.Members.Add(headElement); } internal XmlSchema Remove(XmlSchema schema, bool forceCompile) { // Due to bug 644477 - this method is tightly coupled (THE CODE IS BASICALLY COPIED) to Reprocess // method. If you change anything here *make sure* to update Reprocess method accordingly. if (schema == null) { throw new ArgumentNullException("schema"); } lock (InternalSyncObject) { //Need to lock here so that remove cannot be called while the set is being compiled if (schemas.ContainsKey(schema.SchemaId)) { // This code is copied to method: // Reprocess(XmlSchema schema) // If you changed anything here go and change the same in Reprocess(XmlSchema schema) method #region This code is copied to Reprocess(XmlSchema schema) method if (forceCompile) { RemoveSchemaFromGlobalTables(schema); RemoveSchemaFromCaches(schema); } schemas.Remove(schema.SchemaId); if (schema.BaseUri != null) { schemaLocations.Remove(schema.BaseUri); } string tns = GetTargetNamespace(schema); if (Schemas(tns).Count == 0) { //This is the only schema for that namespace targetNamespaces.Remove(tns); } if (forceCompile) { isCompiled = false; compileAll = true; //Force compilation of the whole set; This is when the set is not completely thread-safe } return schema; #endregion // This code is copied to Reprocess(XmlSchema schema) method } } return null; } private void ClearTables() { GlobalElements.Clear(); GlobalAttributes.Clear(); GlobalTypes.Clear(); SubstitutionGroups.Clear(); TypeExtensions.Clear(); } internal bool PreprocessSchema(ref XmlSchema schema, string targetNamespace) { Preprocessor prep = new Preprocessor(nameTable, GetSchemaNames(nameTable), eventHandler, compilationSettings); prep.XmlResolver = readerSettings.GetXmlResolver_CheckConfig(); prep.ReaderSettings = readerSettings; prep.SchemaLocations = schemaLocations; prep.ChameleonSchemas = chameleonSchemas; bool hasErrors = prep.Execute(schema, targetNamespace, true); schema = prep.RootSchema; //For any root level chameleon cloned return hasErrors; } internal XmlSchema ParseSchema(string targetNamespace, XmlReader reader) { XmlNameTable readerNameTable = reader.NameTable; SchemaNames schemaNames = GetSchemaNames(readerNameTable); Parser parser = new Parser(SchemaType.XSD, readerNameTable, schemaNames, eventHandler); parser.XmlResolver = readerSettings.GetXmlResolver_CheckConfig(); SchemaType schemaType; try { schemaType = parser.Parse(reader, targetNamespace); } catch(XmlSchemaException e) { SendValidationEvent(e, XmlSeverityType.Error); return null; } return parser.XmlSchema; } internal void CopyFromCompiledSet(XmlSchemaSet otherSet) { XmlSchema currentSchema; SortedList copyFromList = otherSet.SortedSchemas; bool setIsCompiled = schemas.Count == 0 ? true : false; ArrayList existingSchemas = new ArrayList(); SchemaInfo newCompiledInfo = new SchemaInfo(); Uri baseUri; for(int i=0; i < copyFromList.Count; i++) { currentSchema = (XmlSchema)copyFromList.GetByIndex(i); baseUri = currentSchema.BaseUri; if (schemas.ContainsKey(currentSchema.SchemaId) || (baseUri != null && baseUri.OriginalString.Length != 0 && schemaLocations[baseUri] != null)) { existingSchemas.Add(currentSchema); continue; } schemas.Add(currentSchema.SchemaId, currentSchema); if (baseUri != null && baseUri.OriginalString.Length != 0) { schemaLocations.Add(baseUri, currentSchema); } string tns = GetTargetNamespace(currentSchema); if (targetNamespaces[tns] == null) { targetNamespaces.Add(tns, tns); } } VerifyTables(); foreach (XmlSchemaElement element in otherSet.GlobalElements.Values) { if(!AddToTable(elements, element.QualifiedName, element)) { goto RemoveAll; } } foreach (XmlSchemaAttribute attribute in otherSet.GlobalAttributes.Values) { if (!AddToTable(attributes, attribute.QualifiedName, attribute)) { goto RemoveAll; } } foreach (XmlSchemaType schemaType in otherSet.GlobalTypes.Values) { if (!AddToTable(schemaTypes, schemaType.QualifiedName, schemaType)) { goto RemoveAll; } } // ProcessNewSubstitutionGroups(otherSet.SubstitutionGroups, false); newCompiledInfo.Add(cachedCompiledInfo, eventHandler); //Add all the items from the old to the new compiled object newCompiledInfo.Add(otherSet.CompiledInfo,eventHandler); // cachedCompiledInfo = newCompiledInfo; //Replace the compiled info in the set after successful compilation if (setIsCompiled) { isCompiled = true; compileAll = false; } return; RemoveAll: foreach (XmlSchema schemaToRemove in copyFromList.Values) { if (!existingSchemas.Contains(schemaToRemove)) { Remove(schemaToRemove, false); } } foreach (XmlSchemaElement elementToRemove in otherSet.GlobalElements.Values) { if(!existingSchemas.Contains((XmlSchema)elementToRemove.Parent)) { elements.Remove(elementToRemove.QualifiedName); } } foreach (XmlSchemaAttribute attributeToRemove in otherSet.GlobalAttributes.Values) { if(!existingSchemas.Contains((XmlSchema)attributeToRemove.Parent)) { attributes.Remove(attributeToRemove.QualifiedName); } } foreach (XmlSchemaType schemaTypeToRemove in otherSet.GlobalTypes.Values) { if(!existingSchemas.Contains((XmlSchema)schemaTypeToRemove.Parent)) { schemaTypes.Remove(schemaTypeToRemove.QualifiedName); } } } internal SchemaInfo CompiledInfo { get { return cachedCompiledInfo; } } internal XmlReaderSettings ReaderSettings { get { return readerSettings; } } internal XmlResolver GetResolver() { return readerSettings.GetXmlResolver_CheckConfig(); } internal ValidationEventHandler GetEventHandler() { return eventHandler; } internal SchemaNames GetSchemaNames(XmlNameTable nt) { if (nameTable != nt) { return new SchemaNames(nt); } else { if (schemaNames == null) { schemaNames = new SchemaNames( nameTable ); } return schemaNames; } } internal bool IsSchemaLoaded(Uri schemaUri, string targetNamespace, out XmlSchema schema) { schema = null; if (targetNamespace == null) { targetNamespace = string.Empty; } if (GetSchemaByUri(schemaUri, out schema)) { if (schemas.ContainsKey(schema.SchemaId) && (targetNamespace.Length == 0 || targetNamespace == schema.TargetNamespace)) { //schema is present in set //Schema found } else if (schema.TargetNamespace == null) { //If schema not in set or namespace doesnt match, then it might be a chameleon XmlSchema chameleonSchema = FindSchemaByNSAndUrl(schemaUri, targetNamespace, null); if (chameleonSchema != null && schemas.ContainsKey(chameleonSchema.SchemaId)) { schema = chameleonSchema; } else { schema = Add(targetNamespace, schema); } } else if (targetNamespace.Length != 0 && targetNamespace != schema.TargetNamespace) { SendValidationEvent(new XmlSchemaException(Res.Sch_MismatchTargetNamespaceEx, new string[] { targetNamespace, schema.TargetNamespace }), XmlSeverityType.Error); schema = null; } else { //If here, schema not present in set but in loc and might be added in loc through an earlier include //S.TNS != null && ( tns == null or tns == s.TNS) AddSchemaToSet(schema); } return true; //Schema Found } return false; } internal bool GetSchemaByUri(Uri schemaUri, out XmlSchema schema) { schema = null; if (schemaUri == null || schemaUri.OriginalString.Length == 0) { return false; } schema = (XmlSchema)schemaLocations[schemaUri]; if (schema != null) { return true; } return false; } internal string GetTargetNamespace(XmlSchema schema) { return schema.TargetNamespace == null ? string.Empty : schema.TargetNamespace; } internal SortedList SortedSchemas { get { return schemas; } } internal bool CompileAll { get { return compileAll; } } //Private Methods private void RemoveSchemaFromCaches(XmlSchema schema) { //Remove From ChameleonSchemas and schemaLocations cache List<XmlSchema> reprocessList = new List<XmlSchema>(); schema.GetExternalSchemasList(reprocessList, schema); for (int i = 0; i < reprocessList.Count; ++i) { //Remove schema from schemaLocations & chameleonSchemas tables if (reprocessList[i].BaseUri != null && reprocessList[i].BaseUri.OriginalString.Length != 0) { schemaLocations.Remove(reprocessList[i].BaseUri); } //Remove from chameleon table ICollection chameleonKeys = chameleonSchemas.Keys; ArrayList removalList = new ArrayList(); foreach(ChameleonKey cKey in chameleonKeys) { if (cKey.chameleonLocation.Equals(reprocessList[i].BaseUri)) { // The key will have the originalSchema set to null if the location was not empty // otherwise we need to care about it as there may be more chameleon schemas without // a base URI and we want to remove only those which were created as a clone of the one // we're removing. if (cKey.originalSchema == null || Ref.ReferenceEquals(cKey.originalSchema, reprocessList[i])) { removalList.Add(cKey); } } } for (int j = 0; j < removalList.Count; ++j) { chameleonSchemas.Remove(removalList[j]); } } } private void RemoveSchemaFromGlobalTables(XmlSchema schema) { if (schemas.Count == 0) { return; } VerifyTables(); foreach (XmlSchemaElement elementToRemove in schema.Elements.Values) { XmlSchemaElement elem = (XmlSchemaElement)elements[elementToRemove.QualifiedName]; if (elem == elementToRemove) { elements.Remove(elementToRemove.QualifiedName); } } foreach (XmlSchemaAttribute attributeToRemove in schema.Attributes.Values) { XmlSchemaAttribute attr = (XmlSchemaAttribute)attributes[attributeToRemove.QualifiedName]; if (attr == attributeToRemove) { attributes.Remove(attributeToRemove.QualifiedName); } } foreach (XmlSchemaType schemaTypeToRemove in schema.SchemaTypes.Values) { XmlSchemaType schemaType = (XmlSchemaType)schemaTypes[schemaTypeToRemove.QualifiedName]; if (schemaType == schemaTypeToRemove) { schemaTypes.Remove(schemaTypeToRemove.QualifiedName); } } } private bool AddToTable(XmlSchemaObjectTable table, XmlQualifiedName qname, XmlSchemaObject item) { if (qname.Name.Length == 0) { return true; } XmlSchemaObject existingObject = (XmlSchemaObject)table[qname]; if (existingObject != null) { if (existingObject == item || existingObject.SourceUri == item.SourceUri) { return true; } string code = string.Empty; if (item is XmlSchemaComplexType) { code = Res.Sch_DupComplexType; } else if (item is XmlSchemaSimpleType) { code = Res.Sch_DupSimpleType; } else if (item is XmlSchemaElement) { code = Res.Sch_DupGlobalElement; } else if (item is XmlSchemaAttribute) { if (qname.Namespace == XmlReservedNs.NsXml) { XmlSchema schemaForXmlNS = Preprocessor.GetBuildInSchema(); XmlSchemaObject builtInAttribute = schemaForXmlNS.Attributes[qname]; if (existingObject == builtInAttribute) { //replace built-in one table.Insert(qname, item); return true; } else if (item == builtInAttribute) { //trying to overwrite customer's component with built-in, ignore built-in return true; } } code = Res.Sch_DupGlobalAttribute; } SendValidationEvent(new XmlSchemaException(code,qname.ToString()), XmlSeverityType.Error); return false; } else { table.Add(qname, item); return true; } } private void VerifyTables() { if (elements == null) { elements = new XmlSchemaObjectTable(); } if (attributes == null) { attributes = new XmlSchemaObjectTable(); } if (schemaTypes == null) { schemaTypes = new XmlSchemaObjectTable(); } if (substitutionGroups == null) { substitutionGroups = new XmlSchemaObjectTable(); } } private void InternalValidationCallback(object sender, ValidationEventArgs e ) { if (e.Severity == XmlSeverityType.Error) { throw e.Exception; } } private void SendValidationEvent(XmlSchemaException e, XmlSeverityType severity) { if (eventHandler != null) { eventHandler(this, new ValidationEventArgs(e, severity)); } else { throw e; } } }; #endif }
/****************************************************************************** * The MIT License * Copyright (c) 2006 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Samples.DynamicGroup.cs // // Author: // Palaniappan N ([email protected]) // // (C) 2006 Novell, Inc (http://www.novell.com) // /* The DynamicGroup.cs sample demonstrates how to: * 1) create the Dynamic Group Entry cn=myDynamicGroup * in a specified container with a specified memberQueryURL * 2) read and print the values of the "member" attribute of cn=myDynamicGroup * 3) delete the dynamic group * * Notes on Dynamic Groups: * * Dynamic groups are supported in Novell eDirectory version 8.6.1 or later. * * A dynamic group is similar to a group entry, but has a search URL * attribute. Entries satisfying the search URL are considered members of * the group. The DN of each member will be returned when reading the * "member" (or its synonym "uniqueMember") attribute. * * A dynamic group is created either with objectClass="dynamicGroup" or by * adding the auxiliary class "dynamicGroupAux" to an existing group entry. * * The search URL is specified in the "memberQueryURL" attribute. * The value of "memberQueryURL" is encoded as an "Ldap URL". * * An entry may be statically added to a dynamic group by adding its DN * to the "member" (or its synonym "uniqueMember") attribute. Similarly * an entry may be statically excluded from the group by adding its DN to the * "excludedMember" attribute. These entries will be included or excluded * from the group regardless of the search URL. * * Note: at the present time, the only way to view only the static members * of a dynamic group is to delete the memberQueryURL attribute and * then read the member attribute. * * In order to provide consistent results when processing the search URL, * the authorization identity DN used to determine group membership is based * on the following criteria: * 1) If the "dgIdentity" attribute is present, its value is the identity DN. * 2) If the above is false, and if the dynamic group entry contains a * public/private key, then the DN of the group entry is the identity DN. * 3) If neither of the above are true, then the anonymous identity is the * identity DN. * * The creator of the group cannot set the "dgIdentity" attribute to a DN * to which he or she does not already have rights. The dynamic group entry * and the DN specified by dgIdentity must be on the same server. * * The "dgAllowDuplicates" attribute enables or disables the presence * of duplicate values in the "membership" attribute. The default is false. * Setting this attribute to true results in a faster search, but some values * in the "membership" attribute may be duplicates. * * The "dgTimeout" attribute determines the number of seconds to wait to get * results from another server during dynamic group member search, when the * search spans multiple servers. * * The format the search URL in the memberQueryUrl attribute is: * Ldap:///<base dn>??<scope>?<filter>[?[!]x-chain] * * The optional extension "x-chain" causes the server to chain to other * servers if necessary to complete the search. When present, the search * will NOT be limited to the host server. This extension should be used * carefully. The exclamation indicates it is a critical extension, and if set * the server will return an error if chaining is not supported or enabled. * * For example, to create a dynamic group consisting of all entries in the * "ou=sales,o=acme" subtree with the title "Manager", set memberQueryURL to: * "Ldap:///ou=sales,o=acme??sub?(title=Manager)" */ using Novell.Directory.Ldap; using System; using System.Collections; public class DynamicGroup { public static void Main( String[] args ) { if (args.Length != 6) { Console.Error.WriteLine("Usage: mono DynamicGroup <host name>" + " <port number> <login dn> <password> <container name>" + " <queryURL>"); Console.Error.WriteLine("Example: mono DynamicGroup Acme.com" + " 389 \"cn=admin, o=Acme\" secret \"o=Acme\" \n " + " Ldap:///ou=Sales,o=Acme??sub?(title=*Manager*)\n"); Environment.Exit(1); } // Set Ldap version to 3 */ int LdapVersion = LdapConnection.Ldap_V3; String ldapHost = args[0]; int ldapPort = Convert.ToInt32(args[1]); String loginDN = args[2]; String password = args[3]; String containerName = args[4]; String queryURL = args[5]; /* Construct the entry's dn using the container name from the * command line and the name of the new dynamic group entry to create. */ String dn = "cn=myDynamicGroup," + containerName; LdapConnection lc = new LdapConnection(); try { if(ldapPort == LdapConnection.DEFAULT_SSL_PORT) lc.SecureSocketLayer = true; // connect to the server lc.Connect( ldapHost, ldapPort ); // bind to the server lc.Bind( LdapVersion, loginDN, password ); // Adding dynamic group entry to the tree Console.WriteLine( "\tAdding dynamic group entry..."); /* add a dynamic group entry to the directory tree in the * specified container */ addDynamicGroupEntry( lc, loginDN, dn, queryURL); /* Reading the member attribute of dynamic group entry and * printing the values */ Console.WriteLine("\n\tReading the \"member\" " + " attribute of dynamic group ojbect ..."); searchDynamicGroupEntry ( lc, dn ); // Removing the dynamic group entry from the specified container Console.WriteLine("\n\tDeleting dynamic group entry..."); deleteDynamicGroupEntry( lc, dn ); // disconnect with the server lc.Disconnect(); } catch( LdapException e ) { Console.WriteLine( "Error: " + e.ToString() ); } catch( Exception e ) { Console.WriteLine( "Error: " + e.ToString() ); } Environment.Exit(0); } // add dynamic group entry public static bool addDynamicGroupEntry ( LdapConnection lc, String loginDN, String entryDN, String queryURL) { bool status = true; LdapAttributeSet attributeSet = new LdapAttributeSet(); //The objectclass "dynamicGroup is used to create dynamic group entries attributeSet.Add( new LdapAttribute( "objectclass", "dynamicGroup" )); /* The memberQueryURL attribute describes the membership of the list * using an LdapURL, which is defined in RFC2255 */ attributeSet.Add( new LdapAttribute( "memberQueryURL", queryURL ) ); /* Set the identity to use for the implied search. loginDN is used * as the dgIdentity in this sample. */ attributeSet.Add( new LdapAttribute( "dgIdentity", loginDN ) ); LdapEntry newEntry = new LdapEntry( entryDN, attributeSet ); try { lc.Add( newEntry ); Console.WriteLine("\tEntry: " + entryDN + " added successfully." ); } catch( LdapException e ) { Console.WriteLine( "\t\tFailed to add dynamic group entry " + entryDN); Console.WriteLine( "Error: " + e.ToString() ); status = false; } return status; } // read and print search results public static bool searchDynamicGroupEntry ( LdapConnection lc, String searchBase ) { bool status = true; int searchScope = LdapConnection.SCOPE_BASE; String[] attrList = new String[]{"member"}; String searchFilter = "(objectclass=*)"; /* Since reading members of a dynamic group could potentially involve * a significant directory search, we use a timeout. Setting * time out to 10 seconds */ LdapSearchConstraints cons = new LdapSearchConstraints(); cons.TimeLimit = 10000 ; try { LdapSearchResults searchResults = lc.Search( searchBase, searchScope, searchFilter, attrList, // return only "member" attr false, // return attrs and values cons ); // time out value LdapEntry nextEntry = null ; // Read and print search results. We expect only one entry */ if (( nextEntry = searchResults.next()) != null ) { LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); IEnumerator allAttributes = attributeSet.GetEnumerator(); if ( allAttributes.MoveNext() ) { // found member(s) in this group LdapAttribute attribute = (LdapAttribute)allAttributes.Current; String attributeName = attribute.Name; IEnumerator allValues = attribute.StringValues; if( allValues != null) { while(allValues.MoveNext()) { String Value = (String) allValues.Current; Console.WriteLine(" " + attributeName + " : " + Value); } } } else { // no member(s) found in this group Console.WriteLine(" No objects matched the " + " memberQueryURL filter.\n "); } } } catch( LdapException e ) { Console.WriteLine( "Error: " + e.ToString() ); status = false; } return status; } // delete the dynamic group entry public static bool deleteDynamicGroupEntry( LdapConnection lc, String deleteDN ) { bool status = true; try { // Deletes the entry from the directory lc.Delete( deleteDN ); Console.WriteLine("\tEntry: " + deleteDN + " was deleted." ); } catch( LdapException e ) { Console.WriteLine( "\t\tFailed to remove dynamic group entry." ); Console.WriteLine( "Error: " + e.ToString() ); status = false; } return status; } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using LucidSightTools; using UnityEngine; // ReSharper disable InconsistentNaming namespace Colyseus { /// <summary> /// Colyseus.Client /// </summary> /// <remarks> /// Provides integration between Colyseus Game Server through WebSocket protocol ( /// <see href="http://tools.ietf.org/html/rfc6455">RFC 6455</see>). /// </remarks> public class ColyseusClient { /// <summary> /// Delegate function for when the <see cref="ColyseusClient" /> successfully connects to the /// <see cref="ColyseusRoom{T}" />. /// </summary> public delegate void ColyseusAddRoomEventHandler(IColyseusRoom room); /// <summary> /// Reference to the client's <see cref="UriBuilder" /> /// </summary> public UriBuilder Endpoint; /// <summary> /// The <see cref="ColyseusSettings"/> currently assigned to this client object /// </summary> private ColyseusSettings _colyseusSettings; /// <summary> /// Occurs when the <see cref="ColyseusClient" /> successfully connects to the <see cref="ColyseusRoom{T}" />. /// </summary> public static event ColyseusAddRoomEventHandler onAddRoom; /// <summary> /// The getter for the <see cref="ColyseusSettings"/> currently assigned to this client object /// </summary> public ColyseusSettings Settings { get { return _colyseusSettings; } private set { _colyseusSettings = value; // Instantiate our ColyseusRequest object with the settings object colyseusRequest = new ColyseusRequest(_colyseusSettings); } } /// <summary> /// Object to perform <see cref="UnityEngine.Networking.UnityWebRequest"/>s to the server. /// </summary> public ColyseusRequest colyseusRequest; /// <summary> /// Initializes a new instance of the <see cref="ColyseusClient" /> class with /// the specified Colyseus Game Server endpoint. /// </summary> /// <param name="endpoint"> /// A <see cref="string" /> that represents the WebSocket URL to connect. /// </param> public ColyseusClient(string endpoint) { Endpoint = new UriBuilder(new Uri(endpoint)); // Create ColyseusSettings object to pass to the ColyseusRequest object ColyseusSettings settings = ScriptableObject.CreateInstance<ColyseusSettings>(); settings.colyseusServerAddress = Endpoint.Host; settings.colyseusServerPort = Endpoint.Port.ToString(); settings.useSecureProtocol = Endpoint.ToString().StartsWith("wss") || Endpoint.ToString().StartsWith("https"); Settings = settings; } /// <summary> /// Initializes a new instance of the <see cref="ColyseusClient"/> class with /// the specified Colyseus Settings object. /// </summary> /// <param name="settings">The settings you wish to use</param> /// <param name="useWebSocketEndpoint">Determines whether the connection endpoint should use either web socket or http protocols.</param> public ColyseusClient(ColyseusSettings settings, bool useWebSocketEndpoint) { SetSettings(settings, useWebSocketEndpoint); } public void SetSettings(ColyseusSettings settings, bool useWebSocketEndpoint) { Endpoint = new UriBuilder(new Uri(useWebSocketEndpoint ? settings.WebSocketEndpoint : settings.WebRequestEndpoint)); Settings = settings; } /// <summary> /// Join or Create a <see cref="ColyseusRoom{T}" /> /// </summary> /// <param name="roomName">Name of the room</param> /// <param name="options">Dictionary of options to pass to the room upon creation/joining</param> /// <param name="headers">Dictionary of headers to pass to the server when we create/join the room</param> /// <typeparam name="T">Type of <see cref="ColyseusRoom{T}" /> we want to join or create</typeparam> /// <returns><see cref="ColyseusRoom{T}" /> via async task</returns> public async Task<ColyseusRoom<T>> JoinOrCreate<T>(string roomName, Dictionary<string, object> options = null, Dictionary<string, string> headers = null) { return await CreateMatchMakeRequest<T>("joinOrCreate", roomName, options, headers); } /// <summary> /// Create a <see cref="ColyseusRoom{T}" /> /// </summary> /// <param name="roomName">Name of the room</param> /// <param name="options">Dictionary of options to pass to the room upon creation</param> /// <param name="headers">Dictionary of headers to pass to the server when we create the room</param> /// <typeparam name="T">Type of <see cref="ColyseusRoom{T}" /> we want to create</typeparam> /// <returns><see cref="ColyseusRoom{T}" /> via async task</returns> public async Task<ColyseusRoom<T>> Create<T>(string roomName, Dictionary<string, object> options = null, Dictionary<string, string> headers = null) { return await CreateMatchMakeRequest<T>("create", roomName, options, headers); } /// <summary> /// Join a <see cref="ColyseusRoom{T}" /> /// </summary> /// <param name="roomName">Name of the room</param> /// <param name="options">Dictionary of options to pass to the room upon joining</param> /// <param name="headers">Dictionary of headers to pass to the server when we join the room</param> /// <typeparam name="T">Type of <see cref="ColyseusRoom{T}" /> we want to join</typeparam> /// <returns><see cref="ColyseusRoom{T}" /> via async task</returns> public async Task<ColyseusRoom<T>> Join<T>(string roomName, Dictionary<string, object> options = null, Dictionary<string, string> headers = null) { return await CreateMatchMakeRequest<T>("join", roomName, options, headers); } /// <summary> /// Join a <see cref="ColyseusRoom{T}" /> by ID /// </summary> /// <param name="roomId">ID of the room</param> /// <param name="options">Dictionary of options to pass to the room upon joining</param> /// <param name="headers">Dictionary of headers to pass to the server when we join the room</param> /// <typeparam name="T">Type of <see cref="ColyseusRoom{T}" /> we want to join</typeparam> /// <returns><see cref="ColyseusRoom{T}" /> via async task</returns> public async Task<ColyseusRoom<T>> JoinById<T>(string roomId, Dictionary<string, object> options = null, Dictionary<string, string> headers = null) { return await CreateMatchMakeRequest<T>("joinById", roomId, options, headers); } /// <summary> /// Reconnect to a <see cref="ColyseusRoom{T}" /> /// </summary> /// <param name="roomId">ID of the room</param> /// <param name="sessionId">Previously connected sessionId</param> /// <param name="headers">Dictionary of headers to pass to the server when we reconnect to the room</param> /// <typeparam name="T">Type of <see cref="ColyseusRoom{T}" /> we want to reconnect with</typeparam> /// <returns><see cref="ColyseusRoom{T}" /> via async task</returns> public async Task<ColyseusRoom<T>> Reconnect<T>(string roomId, string sessionId, Dictionary<string, string> headers = null) { Dictionary<string, object> options = new Dictionary<string, object>(); options.Add("sessionId", sessionId); return await CreateMatchMakeRequest<T>("joinById", roomId, options, headers); } // // FossilDelta/None serializer versions for joining the state // /// <summary> /// Join or Create a <see cref="ColyseusRoom{T}" /> /// </summary> /// <param name="roomName">Name of the room</param> /// <param name="options">Dictionary of options to pass to the room upon creation/joining</param> /// <param name="headers">Dictionary of headers to pass to the server when we create/join the room</param> /// <returns><see cref="ColyseusRoom{T}" /> via async task</returns> public async Task<ColyseusRoom<dynamic>> JoinOrCreate(string roomName, Dictionary<string, object> options = null, Dictionary<string, string> headers = null) { return await CreateMatchMakeRequest<dynamic>("joinOrCreate", roomName, options, headers); } /// <summary> /// Create a <see cref="ColyseusRoom{T}" /> /// </summary> /// <param name="roomName">Name of the room</param> /// <param name="options">Dictionary of options to pass to the room upon creation</param> /// <param name="headers">Dictionary of headers to pass to the server when we create the room</param> /// <returns><see cref="ColyseusRoom{T}" /> via async task</returns> public async Task<ColyseusRoom<dynamic>> Create(string roomName, Dictionary<string, object> options = null, Dictionary<string, string> headers = null) { return await CreateMatchMakeRequest<dynamic>("create", roomName, options, headers); } /// <summary> /// Join a <see cref="ColyseusRoom{T}" /> /// </summary> /// <param name="roomName">Name of the room</param> /// <param name="options">Dictionary of options to pass to the room upon joining</param> /// <param name="headers">Dictionary of headers to pass to the server when we join the room</param> /// <returns><see cref="ColyseusRoom{T}" /> via async task</returns> public async Task<ColyseusRoom<dynamic>> Join(string roomName, Dictionary<string, object> options = null, Dictionary<string, string> headers = null) { return await CreateMatchMakeRequest<dynamic>("join", roomName, options, headers); } /// <summary> /// Join a <see cref="ColyseusRoom{T}" /> by ID /// </summary> /// <param name="roomId">ID of the room</param> /// <param name="options">Dictionary of options to pass to the room upon joining</param> /// <param name="headers">Dictionary of headers to pass to the server when we join the room</param> /// <returns><see cref="ColyseusRoom{T}" /> via async task</returns> public async Task<ColyseusRoom<dynamic>> JoinById(string roomId, Dictionary<string, object> options = null, Dictionary<string, string> headers = null) { return await CreateMatchMakeRequest<dynamic>("joinById", roomId, options, headers); } /// <summary> /// Reconnect to a <see cref="ColyseusRoom{T}" /> /// </summary> /// <param name="roomId">ID of the room</param> /// <param name="sessionId">Previously connected sessionId</param> /// <param name="headers">Dictionary of headers to pass to the server when we reconnect to the room</param> /// <returns><see cref="ColyseusRoom{T}" /> via async task</returns> public async Task<ColyseusRoom<dynamic>> Reconnect(string roomId, string sessionId, Dictionary<string, string> headers = null) { Dictionary<string, object> options = new Dictionary<string, object>(); options.Add("sessionId", sessionId); return await CreateMatchMakeRequest<dynamic>("joinById", roomId, options, headers); } /// <summary> /// Get all available rooms /// </summary> /// <param name="roomName">Name of the room</param> /// <param name="headers">Dictionary of headers to pass to the server</param> /// <returns><see cref="ColyseusRoomAvailable" /> array via async task</returns> public async Task<ColyseusRoomAvailable[]> GetAvailableRooms(string roomName = "", Dictionary<string, string> headers = null) { return await GetAvailableRooms<ColyseusRoomAvailable>(roomName, headers); } /// <summary> /// Get all available rooms of type <typeparamref name="T" /> /// </summary> /// <param name="roomName">Name of the room</param> /// <param name="headers">Dictionary of headers to pass to the server</param> /// <returns><see cref="CSACSARoomAvailableCollection{T}" /> array via async task</returns> public async Task<T[]> GetAvailableRooms<T>(string roomName = "", Dictionary<string, string> headers = null) { if (headers == null) { headers = new Dictionary<string, string>(); } string json = await colyseusRequest.Request("GET", $"matchmake/{roomName}", null, headers); //req.downloadHandler.text; if (json.StartsWith("[", StringComparison.CurrentCulture)) { json = "{\"rooms\":" + json + "}"; } CSARoomAvailableCollection<T> response = JsonUtility.FromJson<CSARoomAvailableCollection<T>>(json); return response.rooms; } /// <summary> /// Consume the seat reservation /// </summary> /// <param name="response">The response from the matchmaking attempt</param> /// <param name="headers">Dictionary of headers to pass to the server</param> /// <typeparam name="T">Type of <see cref="ColyseusRoom{T}" /> we're consuming the seat from</typeparam> /// <returns><see cref="ColyseusRoom{T}" /> in which we now have a seat via async task</returns> public async Task<ColyseusRoom<T>> ConsumeSeatReservation<T>(ColyseusMatchMakeResponse response, Dictionary<string, string> headers = null) { ColyseusRoom<T> room = new ColyseusRoom<T>(response.room.name) { Id = response.room.roomId, SessionId = response.sessionId }; Dictionary<string, object> queryString = new Dictionary<string, object>(); queryString.Add("sessionId", room.SessionId); room.SetConnection(CreateConnection(response.room.processId + "/" + room.Id, queryString, headers)); TaskCompletionSource<ColyseusRoom<T>> tcs = new TaskCompletionSource<ColyseusRoom<T>>(); void OnError(int code, string message) { room.OnError -= OnError; tcs.SetException(new CSAMatchMakeException(code, message)); } void OnJoin() { room.OnError -= OnError; tcs.TrySetResult(room); } room.OnError += OnError; room.OnJoin += OnJoin; onAddRoom?.Invoke(room); #pragma warning disable 4014 room.Connect(); #pragma warning restore 4014 return await tcs.Task; } /// <summary> /// Create a match making request /// </summary> /// <param name="method">The type of request we're making (join, create, etc)</param> /// <param name="roomName">The name of the room we're trying to match</param> /// <param name="options">Dictionary of options to use in the match making process</param> /// <param name="headers">Dictionary of headers to pass to the server</param> /// <typeparam name="T">Type of <see cref="ColyseusRoom{T}" /> we want to match with</typeparam> /// <returns><see cref="ColyseusRoom{T}" /> we have matched with via async task</returns> /// <exception cref="Exception">Thrown if there is a network related error</exception> /// <exception cref="CSAMatchMakeException">Thrown if there is an error in the match making process on the server side</exception> protected async Task<ColyseusRoom<T>> CreateMatchMakeRequest<T>(string method, string roomName, Dictionary<string, object> options, Dictionary<string, string> headers) { if (options == null) { options = new Dictionary<string, object>(); } if (headers == null) { headers = new Dictionary<string, string>(); } string json = await colyseusRequest.Request("POST", $"matchmake/{method}/{roomName}", options, headers); LSLog.Log($"Server Response: {json}"); ColyseusMatchMakeResponse response = JsonUtility.FromJson<ColyseusMatchMakeResponse>(json); if (response == null) { throw new Exception($"Error with request: {json}"); } if (!string.IsNullOrEmpty(response.error)) { throw new CSAMatchMakeException(response.code, response.error); } return await ConsumeSeatReservation<T>(response, headers); } /// <summary> /// Create a connection with a room /// </summary> /// <param name="path">Additional info used as the <see cref="UriBuilder.Path" /></param> /// <param name="options">Dictionary of options to use when connecting</param> /// <param name="headers">Dictionary of headers to pass when connecting</param> /// <returns></returns> protected ColyseusConnection CreateConnection(string path = "", Dictionary<string, object> options = null, Dictionary<string, string> headers = null) { if (options == null) { options = new Dictionary<string, object>(); } List<string> list = new List<string>(); foreach (KeyValuePair<string, object> item in options) { list.Add(item.Key + "=" + (item.Value != null ? Convert.ToString(item.Value) : "null")); } UriBuilder uriBuilder = new UriBuilder(Endpoint.Uri) { Path = path, Query = string.Join("&", list.ToArray()) }; return new ColyseusConnection(uriBuilder.ToString(), headers); } } }
using System; using UnityEngine; using UnityStandardAssets.Vehicles.Car; internal enum CarDriveType { FrontWheelDrive, RearWheelDrive, FourWheelDrive } internal enum SpeedType { MPH, KPH } public class CarController : MonoBehaviour { [SerializeField] private CarDriveType m_CarDriveType = CarDriveType.FourWheelDrive; [SerializeField] private WheelCollider[] m_WheelColliders = new WheelCollider[4]; [SerializeField] private GameObject[] m_WheelMeshes = new GameObject[4]; [SerializeField] private WheelEffects[] m_WheelEffects = new WheelEffects[4]; [SerializeField] private Vector3 m_CentreOfMassOffset; [SerializeField] private float m_MaximumSteerAngle; [Range(0, 1)] [SerializeField] private float m_SteerHelper; // 0 is raw physics , 1 the car will grip in the direction it is facing [Range(0, 1)] [SerializeField] private float m_TractionControl; // 0 is no traction control, 1 is full interference [SerializeField] private float m_FullTorqueOverAllWheels; [SerializeField] private float m_ReverseTorque; [SerializeField] private float m_MaxHandbrakeTorque; [SerializeField] private float m_Downforce = 100f; [SerializeField] private SpeedType m_SpeedType; [SerializeField] private float m_Topspeed = 200; [SerializeField] private static int NoOfGears = 5; [SerializeField] private float m_RevRangeBoundary = 1f; [SerializeField] private float m_SlipLimit; [SerializeField] private float m_BrakeTorque; private Quaternion[] m_WheelMeshLocalRotations; private Vector3 m_Prevpos, m_Pos; private float m_SteerAngle; private int m_GearNum; private float m_GearFactor; private float m_OldRotation; private float m_CurrentTorque; private Rigidbody m_Rigidbody; private const float k_ReversingThreshold = 0.01f; public bool Skidding { get; private set; } public float BrakeInput { get; private set; } public float CurrentSteerAngle{ get { return m_SteerAngle; }} public float CurrentSpeed{ get { return m_Rigidbody.velocity.magnitude*2.23693629f; }} public float MaxSpeed{get { return m_Topspeed; }} public float Revs { get; private set; } public float AccelInput { get; private set; } // Use this for initialization private void Start() { m_WheelMeshLocalRotations = new Quaternion[4]; for (int i = 0; i < 4; i++) { m_WheelMeshLocalRotations[i] = m_WheelMeshes[i].transform.localRotation; } m_WheelColliders[0].attachedRigidbody.centerOfMass = m_CentreOfMassOffset; m_MaxHandbrakeTorque = float.MaxValue; m_Rigidbody = GetComponent<Rigidbody>(); m_CurrentTorque = m_FullTorqueOverAllWheels - (m_TractionControl*m_FullTorqueOverAllWheels); } private void GearChanging() { float f = Mathf.Abs(CurrentSpeed/MaxSpeed); float upgearlimit = (1/(float) NoOfGears)*(m_GearNum + 1); float downgearlimit = (1/(float) NoOfGears)*m_GearNum; if (m_GearNum > 0 && f < downgearlimit) { m_GearNum--; } if (f > upgearlimit && (m_GearNum < (NoOfGears - 1))) { m_GearNum++; } } // simple function to add a curved bias towards 1 for a value in the 0-1 range private static float CurveFactor(float factor) { return 1 - (1 - factor)*(1 - factor); } // unclamped version of Lerp, to allow value to exceed the from-to range private static float ULerp(float from, float to, float value) { return (1.0f - value)*from + value*to; } private void CalculateGearFactor() { float f = (1/(float) NoOfGears); // gear factor is a normalised representation of the current speed within the current gear's range of speeds. // We smooth towards the 'target' gear factor, so that revs don't instantly snap up or down when changing gear. var targetGearFactor = Mathf.InverseLerp(f*m_GearNum, f*(m_GearNum + 1), Mathf.Abs(CurrentSpeed/MaxSpeed)); m_GearFactor = Mathf.Lerp(m_GearFactor, targetGearFactor, Time.deltaTime*5f); } private void CalculateRevs() { // calculate engine revs (for display / sound) // (this is done in retrospect - revs are not used in force/power calculations) CalculateGearFactor(); var gearNumFactor = m_GearNum/(float) NoOfGears; var revsRangeMin = ULerp(0f, m_RevRangeBoundary, CurveFactor(gearNumFactor)); var revsRangeMax = ULerp(m_RevRangeBoundary, 1f, gearNumFactor); Revs = ULerp(revsRangeMin, revsRangeMax, m_GearFactor); } public void Move(float steering, float accel, float footbrake, float handbrake) { for (int i = 0; i < 4; i++) { Quaternion quat; Vector3 position; m_WheelColliders[i].GetWorldPose(out position, out quat); m_WheelMeshes[i].transform.position = position; m_WheelMeshes[i].transform.rotation = quat; } //clamp input values steering = Mathf.Clamp(steering, -1, 1); AccelInput = accel = Mathf.Clamp(accel, 0, 1); BrakeInput = footbrake = -1*Mathf.Clamp(footbrake, -1, 0); handbrake = Mathf.Clamp(handbrake, 0, 1); //Set the steer on the front wheels. //Assuming that wheels 0 and 1 are the front wheels. m_SteerAngle = steering*m_MaximumSteerAngle; m_WheelColliders[0].steerAngle = m_SteerAngle; m_WheelColliders[1].steerAngle = m_SteerAngle; SteerHelper(); ApplyDrive(accel, footbrake); CapSpeed(); //Set the handbrake. //Assuming that wheels 2 and 3 are the rear wheels. if (handbrake > 0f) { var hbTorque = handbrake*m_MaxHandbrakeTorque; m_WheelColliders[2].brakeTorque = hbTorque; m_WheelColliders[3].brakeTorque = hbTorque; } CalculateRevs(); GearChanging(); AddDownForce(); CheckForWheelSpin(); TractionControl(); } private void CapSpeed() { float speed = m_Rigidbody.velocity.magnitude; switch (m_SpeedType) { case SpeedType.MPH: speed *= 2.23693629f; if (speed > m_Topspeed) m_Rigidbody.velocity = (m_Topspeed/2.23693629f) * m_Rigidbody.velocity.normalized; break; case SpeedType.KPH: speed *= 3.6f; if (speed > m_Topspeed) m_Rigidbody.velocity = (m_Topspeed/3.6f) * m_Rigidbody.velocity.normalized; break; } } private void ApplyDrive(float accel, float footbrake) { float thrustTorque; switch (m_CarDriveType) { case CarDriveType.FourWheelDrive: thrustTorque = accel * (m_CurrentTorque / 4f); for (int i = 0; i < 4; i++) { m_WheelColliders[i].motorTorque = thrustTorque; } break; case CarDriveType.FrontWheelDrive: thrustTorque = accel * (m_CurrentTorque / 2f); m_WheelColliders[0].motorTorque = m_WheelColliders[1].motorTorque = thrustTorque; break; case CarDriveType.RearWheelDrive: thrustTorque = accel * (m_CurrentTorque / 2f); m_WheelColliders[2].motorTorque = m_WheelColliders[3].motorTorque = thrustTorque; break; } for (int i = 0; i < 4; i++) { if (CurrentSpeed > 5 && Vector3.Angle(transform.forward, m_Rigidbody.velocity) < 50f) { m_WheelColliders[i].brakeTorque = m_BrakeTorque*footbrake; } else if (footbrake > 0) { m_WheelColliders[i].brakeTorque = 0f; m_WheelColliders[i].motorTorque = -m_ReverseTorque*footbrake; } } } private void SteerHelper() { for (int i = 0; i < 4; i++) { WheelHit wheelhit; m_WheelColliders[i].GetGroundHit(out wheelhit); if (wheelhit.normal == Vector3.zero) return; // wheels arent on the ground so dont realign the rigidbody velocity } // this if is needed to avoid gimbal lock problems that will make the car suddenly shift direction if (Mathf.Abs(m_OldRotation - transform.eulerAngles.y) < 10f) { var turnadjust = (transform.eulerAngles.y - m_OldRotation) * m_SteerHelper; Quaternion velRotation = Quaternion.AngleAxis(turnadjust, Vector3.up); m_Rigidbody.velocity = velRotation * m_Rigidbody.velocity; } m_OldRotation = transform.eulerAngles.y; } // this is used to add more grip in relation to speed private void AddDownForce() { m_WheelColliders[0].attachedRigidbody.AddForce(-transform.up*m_Downforce* m_WheelColliders[0].attachedRigidbody.velocity.magnitude); } // checks if the wheels are spinning and is so does three things // 1) emits particles // 2) plays tiure skidding sounds // 3) leaves skidmarks on the ground // these effects are controlled through the WheelEffects class private void CheckForWheelSpin() { // loop through all wheels for (int i = 0; i < 4; i++) { WheelHit wheelHit; m_WheelColliders[i].GetGroundHit(out wheelHit); // is the tire slipping above the given threshhold if (Mathf.Abs(wheelHit.forwardSlip) >= m_SlipLimit || Mathf.Abs(wheelHit.sidewaysSlip) >= m_SlipLimit) { m_WheelEffects[i].EmitTyreSmoke(); // avoiding all four tires screeching at the same time // if they do it can lead to some strange audio artefacts if (!AnySkidSoundPlaying()) { m_WheelEffects[i].PlayAudio(); } continue; } // if it wasnt slipping stop all the audio if (m_WheelEffects[i].PlayingAudio) { m_WheelEffects[i].StopAudio(); } // end the trail generation m_WheelEffects[i].EndSkidTrail(); } } // crude traction control that reduces the power to wheel if the car is wheel spinning too much private void TractionControl() { WheelHit wheelHit; switch (m_CarDriveType) { case CarDriveType.FourWheelDrive: // loop through all wheels for (int i = 0; i < 4; i++) { m_WheelColliders[i].GetGroundHit(out wheelHit); AdjustTorque(wheelHit.forwardSlip); } break; case CarDriveType.RearWheelDrive: m_WheelColliders[2].GetGroundHit(out wheelHit); AdjustTorque(wheelHit.forwardSlip); m_WheelColliders[3].GetGroundHit(out wheelHit); AdjustTorque(wheelHit.forwardSlip); break; case CarDriveType.FrontWheelDrive: m_WheelColliders[0].GetGroundHit(out wheelHit); AdjustTorque(wheelHit.forwardSlip); m_WheelColliders[1].GetGroundHit(out wheelHit); AdjustTorque(wheelHit.forwardSlip); break; } } private void AdjustTorque(float forwardSlip) { if (forwardSlip >= m_SlipLimit && m_CurrentTorque >= 0) { m_CurrentTorque -= 10 * m_TractionControl; } else { m_CurrentTorque += 10 * m_TractionControl; if (m_CurrentTorque > m_FullTorqueOverAllWheels) { m_CurrentTorque = m_FullTorqueOverAllWheels; } } } private bool AnySkidSoundPlaying() { for (int i = 0; i < 4; i++) { if (m_WheelEffects[i].PlayingAudio) { return true; } } return false; } }