context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Data; using Csla; using Csla.Data; using SelfLoad.DataAccess; using SelfLoad.DataAccess.ERCLevel; namespace SelfLoad.Business.ERCLevel { /// <summary> /// D05_CountryColl (editable child list).<br/> /// This is a generated base class of <see cref="D05_CountryColl"/> business object. /// </summary> /// <remarks> /// This class is child of <see cref="D04_SubContinent"/> editable child object.<br/> /// The items of the collection are <see cref="D06_Country"/> objects. /// </remarks> [Serializable] public partial class D05_CountryColl : BusinessListBase<D05_CountryColl, D06_Country> { #region Collection Business Methods /// <summary> /// Removes a <see cref="D06_Country"/> item from the collection. /// </summary> /// <param name="country_ID">The Country_ID of the item to be removed.</param> public void Remove(int country_ID) { foreach (var d06_Country in this) { if (d06_Country.Country_ID == country_ID) { Remove(d06_Country); break; } } } /// <summary> /// Determines whether a <see cref="D06_Country"/> item is in the collection. /// </summary> /// <param name="country_ID">The Country_ID of the item to search for.</param> /// <returns><c>true</c> if the D06_Country is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int country_ID) { foreach (var d06_Country in this) { if (d06_Country.Country_ID == country_ID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="D06_Country"/> item is in the collection's DeletedList. /// </summary> /// <param name="country_ID">The Country_ID of the item to search for.</param> /// <returns><c>true</c> if the D06_Country is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int country_ID) { foreach (var d06_Country in DeletedList) { if (d06_Country.Country_ID == country_ID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="D06_Country"/> item of the <see cref="D05_CountryColl"/> collection, based on a given Country_ID. /// </summary> /// <param name="country_ID">The Country_ID.</param> /// <returns>A <see cref="D06_Country"/> object.</returns> public D06_Country FindD06_CountryByCountry_ID(int country_ID) { for (var i = 0; i < this.Count; i++) { if (this[i].Country_ID.Equals(country_ID)) { return this[i]; } } return null; } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="D05_CountryColl"/> collection. /// </summary> /// <returns>A reference to the created <see cref="D05_CountryColl"/> collection.</returns> internal static D05_CountryColl NewD05_CountryColl() { return DataPortal.CreateChild<D05_CountryColl>(); } /// <summary> /// Factory method. Loads a <see cref="D05_CountryColl"/> collection, based on given parameters. /// </summary> /// <param name="parent_SubContinent_ID">The Parent_SubContinent_ID parameter of the D05_CountryColl to fetch.</param> /// <returns>A reference to the fetched <see cref="D05_CountryColl"/> collection.</returns> internal static D05_CountryColl GetD05_CountryColl(int parent_SubContinent_ID) { return DataPortal.FetchChild<D05_CountryColl>(parent_SubContinent_ID); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="D05_CountryColl"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public D05_CountryColl() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = true; AllowEdit = true; AllowRemove = true; RaiseListChangedEvents = rlce; } #endregion #region Data Access /// <summary> /// Loads a <see cref="D05_CountryColl"/> collection from the database, based on given criteria. /// </summary> /// <param name="parent_SubContinent_ID">The Parent Sub Continent ID.</param> protected void Child_Fetch(int parent_SubContinent_ID) { var args = new DataPortalHookArgs(parent_SubContinent_ID); OnFetchPre(args); using (var dalManager = DalFactorySelfLoad.GetManager()) { var dal = dalManager.GetProvider<ID05_CountryCollDal>(); var data = dal.Fetch(parent_SubContinent_ID); LoadCollection(data); } OnFetchPost(args); foreach (var item in this) { item.FetchChildren(); } } private void LoadCollection(IDataReader data) { using (var dr = new SafeDataReader(data)) { Fetch(dr); } } /// <summary> /// Loads all <see cref="D05_CountryColl"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; while (dr.Read()) { Add(D06_Country.GetD06_Country(dr)); } RaiseListChangedEvents = rlce; } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); #endregion } }
using System.Collections.Generic; using System.Security.Cryptography; using Core.Interfaces; using Core.Model; using Core.SystemWrappers; using Crypto.Generators; using Crypto.Mappers; using Crypto.Providers; using Crypto.Wrappers; using Moq; using NUnit.Framework; using Ui.Console; using Ui.Console.Provider; using Container = SimpleInjector.Container; namespace Integration.VerifySignature.Test { [TestFixture] public abstract class VerifySignatureTest { private Mock<FileWrapper> file; private Mock<ConsoleWrapper> console; private Dictionary<string, byte[]> files; private string base64FileSignature; private string base64InputSignature; private Base64Wrapper base64; private EncodingWrapper encoding; private RsaKeyProvider rsaKeyProvider; private DsaKeyProvider dsaKeyProvider; private EcKeyProvider ecKeyProvider; private ElGamalKeyProvider elGamalKeyProvider; private SignatureProvider signatureProvider; private Pkcs8PemFormattingProvider pkcs8PemFormatter; private SecureRandomGenerator random; [SetUp] public void VerifySignatureTestSetup() { file = new Mock<FileWrapper>(); file.Setup(f => f.ReadAllBytes(It.IsAny<string>())) .Returns<string>(givenFile => files[givenFile]); console = new Mock<ConsoleWrapper>(); Container container = ContainerProvider.GetContainer(); container.Register<FileWrapper>(() => file.Object); container.Register<ConsoleWrapper>(() => console.Object); var asymmetricKeyPairGenerator = new AsymmetricKeyPairGenerator(new SecureRandomGenerator()); var primeMapper = new Rfc3526PrimeMapper(); var curveNameMapper = new FieldToCurveNameMapper(); rsaKeyProvider = new RsaKeyProvider(asymmetricKeyPairGenerator); dsaKeyProvider = new DsaKeyProvider(asymmetricKeyPairGenerator); ecKeyProvider = new EcKeyProvider(asymmetricKeyPairGenerator, curveNameMapper); elGamalKeyProvider = new ElGamalKeyProvider(asymmetricKeyPairGenerator, primeMapper); signatureProvider = new SignatureProvider(new SignatureAlgorithmIdentifierMapper(), new SecureRandomGenerator(), new SignerUtilitiesWrapper()); pkcs8PemFormatter = new Pkcs8PemFormattingProvider(new AsymmetricKeyProvider(new OidToCipherTypeMapper(), new KeyInfoWrapper(), rsaKeyProvider, dsaKeyProvider, ecKeyProvider, elGamalKeyProvider)); base64 = new Base64Wrapper(); encoding = new EncodingWrapper(); random = new SecureRandomGenerator(); } private void SetupWithRsaSignature() { byte[] fileContent = random.NextBytes(1500); IAsymmetricKeyPair keyPair = rsaKeyProvider.CreateKeyPair(2048); SetFileContent(keyPair, fileContent); } private void SetupWithDsaSignature() { byte[] fileContent = random.NextBytes(1500); IAsymmetricKeyPair keyPair = dsaKeyProvider.CreateKeyPair(2048); SetFileContent(keyPair, fileContent); } private void SetupWithEcdsaSignature() { byte[] fileContent = random.NextBytes(1500); IAsymmetricKeyPair keyPair = ecKeyProvider.CreateKeyPair("curve25519"); SetFileContent(keyPair, fileContent); } private void SetFileContent(IAsymmetricKeyPair keyPair, byte[] fileContent) { Signature fileSignature = signatureProvider.CreateSignature(keyPair.PrivateKey, fileContent); base64FileSignature = base64.ToBase64String(fileSignature.Content); Signature inputSignature = signatureProvider.CreateSignature(keyPair.PrivateKey, encoding.GetBytes("FooBarBaz")); base64InputSignature = base64.ToBase64String(inputSignature.Content); string pemFormattedPublicKey = pkcs8PemFormatter.GetAsPem(keyPair.PublicKey); var tamperedFileContent = (byte[]) fileContent.Clone(); tamperedFileContent[10] = (byte) (tamperedFileContent[10] >> 1); files = new Dictionary<string, byte[]> { {"content.file", fileContent}, {"tamperedContent.file", tamperedFileContent}, {"signature.file", encoding.GetBytes(base64FileSignature)}, {"signature.input", encoding.GetBytes(base64InputSignature)}, {"public.pem", encoding.GetBytes(pemFormattedPublicKey)} }; } public static string[][] invalidFileSignatures = { new[]{"-v", "signature", "--publickey", "public.pem", "-f", "content.file", "-s", "signature.input"}, new[]{"-v", "signature", "--publickey", "public.pem", "-f", "tamperedContent.file", "-s", "signature.file"}, new[]{"-v", "signature", "--publickey", "public.pem", "-i", "FooBarBaz", "-s", "signature.file"}, new[]{"-v", "signature", "--publickey", "public.pem", "-i", "FooBarBaz.", "-s", "signature.input"} }; [Test, TestCaseSource("invalidFileSignatures")] public void ShouldThrowExceptionForInvalidFileSignature(string[] applicationParameters) { Assert.Throws<CryptographicException>(() => Certifier.Main(applicationParameters)); } [Test] public void ShouldThrowExceptionWhenInvalidSignatureIsGivenAsParameterForFileContent() { string tamperedBase64FileSignature = TamperBase64Signature(base64FileSignature); Assert.Throws<CryptographicException>(() => Certifier.Main(new[] { "-v", "signature", "--publickey", "public.pem", "-f", "content.file", "-s", tamperedBase64FileSignature })); } [Test] public void ShouldThrowExceptionWhenInvalidSignatureIsGivenAsParameterForUserInput() { string tamperedBase64InputSignature = TamperBase64Signature(base64InputSignature); Assert.Throws<CryptographicException>(() => Certifier.Main(new[] { "-v", "signature", "--publickey", "public.pem", "-i", "FooBarBaz", "-s", tamperedBase64InputSignature })); } public static string[][] validFileSignatures = { new[]{"-v", "signature", "--publickey", "public.pem", "-f", "content.file", "-s", "signature.file"}, new[]{"-v", "signature", "--publickey", "public.pem", "-i", "FooBarBaz", "-s", "signature.input"} }; [Test, TestCaseSource("validFileSignatures")] public void ShouldNotThrowExceptionForValidFileSignature(string[] applicationParameters) { Assert.DoesNotThrow(() => Certifier.Main(applicationParameters)); console.Verify(c => c.WriteLine(It.IsAny<string>()), Times.Never); } [Test] public void ShouldNotThrowExceptionWhenValidSignatureIsGivenAsParameterForFileContent() { Assert.DoesNotThrow(() => Certifier.Main(new[] { "-v", "signature", "--publickey", "public.pem", "-f", "content.file", "-s", base64FileSignature })); console.Verify(c => c.WriteLine(It.IsAny<string>()), Times.Never); } [Test] public void ShouldNotThrowExceptionWhenValidSignatureIsGivenAsParameterForUserInput() { Assert.DoesNotThrow(() => Certifier.Main(new[] { "-v", "signature", "--publickey", "public.pem", "-i", "FooBarBaz", "-s", base64InputSignature })); console.Verify(c => c.WriteLine(It.IsAny<string>()), Times.Never); } private string TamperBase64Signature(string base64Signature) { char[] signatureCharacters = base64Signature.ToCharArray(); signatureCharacters[15] = signatureCharacters[15] == 'A' ? 'a' : 'A'; return new string(signatureCharacters); } [TearDown] public void TeardownVerifySignatureTest() { ContainerProvider.ClearContainer(); } [TestFixture] public class VerifyRsaSignature : VerifySignatureTest { [SetUp] public void Setup() { SetupWithRsaSignature(); } } [TestFixture] public class VerifyDsaSignature : VerifySignatureTest { [SetUp] public void Setup() { SetupWithDsaSignature(); } } [TestFixture] public class VerifyEcdsaSignature : VerifySignatureTest { [SetUp] public void Setup() { SetupWithEcdsaSignature(); } } } }
// 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.Management.ApiManagement { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// PolicyOperations operations. /// </summary> internal partial class PolicyOperations : IServiceOperations<ApiManagementClient>, IPolicyOperations { /// <summary> /// Initializes a new instance of the PolicyOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal PolicyOperations(ApiManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ApiManagementClient /// </summary> public ApiManagementClient Client { get; private set; } /// <summary> /// Lists all the Global Policy definitions of the Api Management service. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='scope'> /// Policy scope. Possible values include: 'Tenant', 'Product', 'Api', /// 'Operation', 'All' /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PolicyCollection>> ListByServiceWithHttpMessagesAsync(string resourceGroupName, string serviceName, PolicyScopeContract? scope = default(PolicyScopeContract?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("scope", scope); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByService", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/policies").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (scope != null) { _queryParameters.Add(string.Format("scope={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(scope, Client.SerializationSettings).Trim('"')))); } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PolicyCollection>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PolicyCollection>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get the Global policy definition of the Api Management service. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PolicyContract,PolicyGetHeaders>> GetWithHttpMessagesAsync(string resourceGroupName, string serviceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string policyId = "policy"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("policyId", policyId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/policies/{policyId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{policyId}", System.Uri.EscapeDataString(policyId)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PolicyContract,PolicyGetHeaders>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PolicyContract>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PolicyGetHeaders>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates the global policy configuration of the Api Management /// service. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// The policy contents to apply. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PolicyContract>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, PolicyContract parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string policyId = "policy"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("policyId", policyId); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/policies/{policyId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{policyId}", System.Uri.EscapeDataString(policyId)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PolicyContract>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PolicyContract>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PolicyContract>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the global policy configuration of the Api Management Service. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='ifMatch'> /// The entity state (Etag) version of the policy to be deleted. A value of "*" /// can be used for If-Match to unconditionally apply the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serviceName, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (ifMatch == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ifMatch"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string policyId = "policy"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("policyId", policyId); tracingParameters.Add("ifMatch", ifMatch); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/policies/{policyId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{policyId}", System.Uri.EscapeDataString(policyId)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (ifMatch != null) { if (_httpRequest.Headers.Contains("If-Match")) { _httpRequest.Headers.Remove("If-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // Copyright (c) 2007 Novell, Inc // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.IO; using System.Xml; using System.Xml.Serialization; using Xunit; namespace System.Data.Tests { public class DataTableTest5 : IDisposable { private string _tempFile; private DataSet _dataSet; private DataTable _dummyTable; private DataTable _parentTable1; private DataTable _childTable; private DataTable _secondChildTable; public DataTableTest5() { _tempFile = Path.GetTempFileName(); } public void Dispose() { if (_tempFile != null) File.Delete(_tempFile); } private void WriteXmlSerializable(Stream s, DataTable dt) { XmlWriterSettings ws = new XmlWriterSettings(); using (XmlWriter xw = XmlWriter.Create(s, ws)) { IXmlSerializable idt = dt; xw.WriteStartElement("start"); idt.WriteXml(xw); xw.WriteEndElement(); xw.Close(); } } private void ReadXmlSerializable(Stream s, DataTable dt) { using (XmlReader xr = XmlReader.Create(s)) { ReadXmlSerializable(dt, xr); } } private static void ReadXmlSerializable(DataTable dt, XmlReader xr) { XmlSerializer serializer = new XmlSerializer(dt.GetType()); IXmlSerializable idt = dt; idt.ReadXml(xr); xr.Close(); } private void ReadXmlSerializable(string fileName, DataTable dt) { using (XmlReader xr = XmlReader.Create(fileName)) { ReadXmlSerializable(dt, xr); } } private void MakeParentTable1() { // Create a new Table _parentTable1 = new DataTable("ParentTable"); _dataSet = new DataSet("XmlDataSet"); DataColumn column; DataRow row; // Create new DataColumn, set DataType, // ColumnName and add to Table. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "id"; column.Unique = true; // Add the Column to the DataColumnCollection. _parentTable1.Columns.Add(column); // Create second column column = new DataColumn(); column.DataType = typeof(string); column.ColumnName = "ParentItem"; column.AutoIncrement = false; column.Caption = "ParentItem"; column.Unique = false; // Add the column to the table _parentTable1.Columns.Add(column); // Create third column. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "DepartmentID"; column.Caption = "DepartmentID"; // Add the column to the table. _parentTable1.Columns.Add(column); // Make the ID column the primary key column. DataColumn[] PrimaryKeyColumns = new DataColumn[2]; PrimaryKeyColumns[0] = _parentTable1.Columns["id"]; PrimaryKeyColumns[1] = _parentTable1.Columns["DepartmentID"]; _parentTable1.PrimaryKey = PrimaryKeyColumns; _dataSet.Tables.Add(_parentTable1); // Create three new DataRow objects and add // them to the DataTable for (int i = 0; i <= 2; i++) { row = _parentTable1.NewRow(); row["id"] = i + 1; row["ParentItem"] = "ParentItem " + (i + 1); row["DepartmentID"] = i + 1; _parentTable1.Rows.Add(row); } } private void MakeDummyTable() { // Create a new Table _dataSet = new DataSet(); _dummyTable = new DataTable("DummyTable"); DataColumn column; DataRow row; // Create new DataColumn, set DataType, // ColumnName and add to Table. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "id"; column.Unique = true; // Add the Column to the DataColumnCollection. _dummyTable.Columns.Add(column); // Create second column column = new DataColumn(); column.DataType = typeof(string); column.ColumnName = "DummyItem"; column.AutoIncrement = false; column.Caption = "DummyItem"; column.Unique = false; // Add the column to the table _dummyTable.Columns.Add(column); _dataSet.Tables.Add(_dummyTable); // Create three new DataRow objects and add // them to the DataTable for (int i = 0; i <= 2; i++) { row = _dummyTable.NewRow(); row["id"] = i + 1; row["DummyItem"] = "DummyItem " + (i + 1); _dummyTable.Rows.Add(row); } DataRow row1 = _dummyTable.Rows[1]; _dummyTable.AcceptChanges(); row1.BeginEdit(); row1[1] = "Changed_DummyItem " + 2; row1.EndEdit(); } private void MakeChildTable() { // Create a new Table _childTable = new DataTable("ChildTable"); DataColumn column; DataRow row; // Create first column and add to the DataTable. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "ChildID"; column.AutoIncrement = true; column.Caption = "ID"; column.Unique = true; // Add the column to the DataColumnCollection _childTable.Columns.Add(column); // Create second column column = new DataColumn(); column.DataType = typeof(string); column.ColumnName = "ChildItem"; column.AutoIncrement = false; column.Caption = "ChildItem"; column.Unique = false; _childTable.Columns.Add(column); //Create third column column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "ParentID"; column.AutoIncrement = false; column.Caption = "ParentID"; column.Unique = false; _childTable.Columns.Add(column); _dataSet.Tables.Add(_childTable); // Create three sets of DataRow objects, // five rows each, and add to DataTable. for (int i = 0; i <= 1; i++) { row = _childTable.NewRow(); row["childID"] = i + 1; row["ChildItem"] = "ChildItem " + (i + 1); row["ParentID"] = 1; _childTable.Rows.Add(row); } for (int i = 0; i <= 1; i++) { row = _childTable.NewRow(); row["childID"] = i + 5; row["ChildItem"] = "ChildItem " + (i + 1); row["ParentID"] = 2; _childTable.Rows.Add(row); } for (int i = 0; i <= 1; i++) { row = _childTable.NewRow(); row["childID"] = i + 10; row["ChildItem"] = "ChildItem " + (i + 1); row["ParentID"] = 3; _childTable.Rows.Add(row); } } private void MakeSecondChildTable() { // Create a new Table _secondChildTable = new DataTable("SecondChildTable"); DataColumn column; DataRow row; // Create first column and add to the DataTable. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "ChildID"; column.AutoIncrement = true; column.Caption = "ID"; column.ReadOnly = true; column.Unique = true; // Add the column to the DataColumnCollection. _secondChildTable.Columns.Add(column); // Create second column. column = new DataColumn(); column.DataType = typeof(string); column.ColumnName = "ChildItem"; column.AutoIncrement = false; column.Caption = "ChildItem"; column.ReadOnly = false; column.Unique = false; _secondChildTable.Columns.Add(column); //Create third column. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "ParentID"; column.AutoIncrement = false; column.Caption = "ParentID"; column.ReadOnly = false; column.Unique = false; _secondChildTable.Columns.Add(column); //Create fourth column. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "DepartmentID"; column.Caption = "DepartmentID"; column.Unique = false; _secondChildTable.Columns.Add(column); _dataSet.Tables.Add(_secondChildTable); // Create three sets of DataRow objects, // five rows each, and add to DataTable. for (int i = 0; i <= 1; i++) { row = _secondChildTable.NewRow(); row["childID"] = i + 1; row["ChildItem"] = "SecondChildItem " + (i + 1); row["ParentID"] = 1; row["DepartmentID"] = 1; _secondChildTable.Rows.Add(row); } for (int i = 0; i <= 1; i++) { row = _secondChildTable.NewRow(); row["childID"] = i + 5; row["ChildItem"] = "SecondChildItem " + (i + 1); row["ParentID"] = 2; row["DepartmentID"] = 2; _secondChildTable.Rows.Add(row); } for (int i = 0; i <= 1; i++) { row = _secondChildTable.NewRow(); row["childID"] = i + 10; row["ChildItem"] = "SecondChildItem " + (i + 1); row["ParentID"] = 3; row["DepartmentID"] = 3; _secondChildTable.Rows.Add(row); } } private void MakeDataRelation() { DataColumn parentColumn = _dataSet.Tables["ParentTable"].Columns["id"]; DataColumn childColumn = _dataSet.Tables["ChildTable"].Columns["ParentID"]; DataRelation relation = new DataRelation("ParentChild_Relation1", parentColumn, childColumn); _dataSet.Tables["ChildTable"].ParentRelations.Add(relation); DataColumn[] parentColumn1 = new DataColumn[2]; DataColumn[] childColumn1 = new DataColumn[2]; parentColumn1[0] = _dataSet.Tables["ParentTable"].Columns["id"]; parentColumn1[1] = _dataSet.Tables["ParentTable"].Columns["DepartmentID"]; childColumn1[0] = _dataSet.Tables["SecondChildTable"].Columns["ParentID"]; childColumn1[1] = _dataSet.Tables["SecondChildTable"].Columns["DepartmentID"]; DataRelation secondRelation = new DataRelation("ParentChild_Relation2", parentColumn1, childColumn1); _dataSet.Tables["SecondChildTable"].ParentRelations.Add(secondRelation); } private void MakeDataRelation(DataTable dt) { DataColumn parentColumn = dt.Columns["id"]; DataColumn childColumn = _dataSet.Tables["ChildTable"].Columns["ParentID"]; DataRelation relation = new DataRelation("ParentChild_Relation1", parentColumn, childColumn); _dataSet.Tables["ChildTable"].ParentRelations.Add(relation); DataColumn[] parentColumn1 = new DataColumn[2]; DataColumn[] childColumn1 = new DataColumn[2]; parentColumn1[0] = dt.Columns["id"]; parentColumn1[1] = dt.Columns["DepartmentID"]; childColumn1[0] = _dataSet.Tables["SecondChildTable"].Columns["ParentID"]; childColumn1[1] = _dataSet.Tables["SecondChildTable"].Columns["DepartmentID"]; DataRelation secondRelation = new DataRelation("ParentChild_Relation2", parentColumn1, childColumn1); _dataSet.Tables["SecondChildTable"].ParentRelations.Add(secondRelation); } //Test properties of a table which does not belongs to a DataSet private void VerifyTableSchema(DataTable table, string tableName, DataSet ds) { //Test Schema //Check Properties of Table Assert.Equal(string.Empty, table.Namespace); Assert.Equal(ds, table.DataSet); Assert.Equal(3, table.Columns.Count); Assert.Equal(false, table.CaseSensitive); Assert.Equal(tableName, table.TableName); Assert.Equal(2, table.Constraints.Count); Assert.Equal(string.Empty, table.Prefix); Assert.Equal(2, table.Constraints.Count); Assert.Equal(typeof(UniqueConstraint), table.Constraints[0].GetType()); Assert.Equal(typeof(UniqueConstraint), table.Constraints[1].GetType()); Assert.Equal(2, table.PrimaryKey.Length); Assert.Equal("id", table.PrimaryKey[0].ToString()); Assert.Equal("DepartmentID", table.PrimaryKey[1].ToString()); Assert.Equal(0, table.ParentRelations.Count); Assert.Equal(0, table.ChildRelations.Count); //Check properties of each column //First Column DataColumn col = table.Columns[0]; Assert.Equal(false, col.AllowDBNull); Assert.Equal(false, col.AutoIncrement); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("id", col.Caption); Assert.Equal("id", col.ColumnName); Assert.Equal(typeof(int), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.Equal(false, col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(0, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ParentTable", col.Table.ToString()); Assert.Equal(true, col.Unique); //Second Column col = table.Columns[1]; Assert.Equal(true, col.AllowDBNull); Assert.Equal(false, col.AutoIncrement); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("ParentItem", col.Caption); Assert.Equal("ParentItem", col.ColumnName); Assert.Equal(typeof(string), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.Equal(false, col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(1, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ParentTable", col.Table.ToString()); Assert.Equal(false, col.Unique); //Third Column col = table.Columns[2]; Assert.Equal(false, col.AllowDBNull); Assert.Equal(false, col.AutoIncrement); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("DepartmentID", col.Caption); Assert.Equal("DepartmentID", col.ColumnName); Assert.Equal(typeof(int), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.Equal(false, col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(2, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ParentTable", col.Table.ToString()); Assert.Equal(false, col.Unique); //Test the Xml Assert.Equal(3, table.Rows.Count); //Test values of each row DataRow row = table.Rows[0]; Assert.Equal(1, row["id"]); Assert.Equal("ParentItem 1", row["ParentItem"]); Assert.Equal(1, row["DepartmentID"]); row = table.Rows[1]; Assert.Equal(2, row["id"]); Assert.Equal("ParentItem 2", row["ParentItem"]); Assert.Equal(2, row["DepartmentID"]); row = table.Rows[2]; Assert.Equal(3, row["id"]); Assert.Equal("ParentItem 3", row["ParentItem"]); Assert.Equal(3, row["DepartmentID"]); } [Fact] public void XmlTest1() { //Make a table without any relations MakeParentTable1(); _dataSet.Tables.Remove(_parentTable1); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table = new DataTable("ParentTable"); //Read the Xml and the Schema into a table which does not belongs to any DataSet ReadXmlSerializable(_tempFile, table); VerifyTableSchema(table, _parentTable1.TableName, null);//parentTable1.DataSet); } [Fact] public void XmlTest2() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table = new DataTable("ParentTable"); DataSet ds = new DataSet("XmlDataSet"); ds.Tables.Add(table); //Read the Xml and the Schema into a table which already belongs to a DataSet //and the table name matches with the table in the source XML ReadXmlSerializable(_tempFile, table); VerifyTableSchema(table, _parentTable1.TableName, ds); } [Fact] public void XmlTest3() { //Create a parent table and create child tables MakeParentTable1(); MakeChildTable(); MakeSecondChildTable(); //Relate the parent and the children MakeDataRelation(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table = new DataTable(); ReadXmlSerializable(_tempFile, table); VerifyTableSchema(table, _parentTable1.TableName, null); } [Fact] public void XmlTest4() { //Create a parent table and create child tables MakeParentTable1(); MakeChildTable(); MakeSecondChildTable(); //Relate the parent and the children MakeDataRelation(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { //WriteXml on any of the children WriteXmlSerializable(stream, _childTable); } DataTable table = new DataTable(); ReadXmlSerializable(_tempFile, table); //Test Schema //Check Properties of Table Assert.Equal(string.Empty, table.Namespace); Assert.Null(table.DataSet); Assert.Equal(3, table.Columns.Count); Assert.Equal(false, table.CaseSensitive); Assert.Equal("ChildTable", table.TableName); Assert.Equal(string.Empty, table.Prefix); Assert.Equal(1, table.Constraints.Count); Assert.Equal("Constraint1", table.Constraints[0].ToString()); Assert.Equal(typeof(UniqueConstraint), table.Constraints[0].GetType()); Assert.Equal(0, table.PrimaryKey.Length); Assert.Equal(0, table.ParentRelations.Count); Assert.Equal(0, table.ChildRelations.Count); //Check properties of each column //First Column DataColumn col = table.Columns[0]; Assert.Equal(true, col.AllowDBNull); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("ChildID", col.ColumnName); Assert.Equal(typeof(int), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.Equal(false, col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(0, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ChildTable", col.Table.ToString()); Assert.Equal(true, col.Unique); //Second Column col = table.Columns[1]; Assert.Equal(true, col.AllowDBNull); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("ChildItem", col.Caption); Assert.Equal("ChildItem", col.ColumnName); Assert.Equal(typeof(string), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.Equal(false, col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(1, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ChildTable", col.Table.ToString()); Assert.Equal(false, col.Unique); //Third Column col = table.Columns[2]; Assert.Equal(true, col.AllowDBNull); Assert.Equal(false, col.AutoIncrement); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("ParentID", col.Caption); Assert.Equal("ParentID", col.ColumnName); Assert.Equal(typeof(int), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.Equal(false, col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(2, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ChildTable", col.Table.ToString()); Assert.Equal(false, col.Unique); //Test the Xml Assert.Equal(6, table.Rows.Count); //Test values of each row DataRow row = table.Rows[0]; Assert.Equal(1, row["ChildID"]); Assert.Equal("ChildItem 1", row["ChildItem"]); Assert.Equal(1, row["ParentID"]); row = table.Rows[1]; Assert.Equal(2, row["ChildID"]); Assert.Equal("ChildItem 2", row["ChildItem"]); Assert.Equal(1, row["ParentID"]); row = table.Rows[2]; Assert.Equal(5, row["ChildID"]); Assert.Equal("ChildItem 1", row["ChildItem"]); Assert.Equal(2, row["ParentID"]); row = table.Rows[3]; Assert.Equal(6, row["ChildID"]); Assert.Equal("ChildItem 2", row["ChildItem"]); Assert.Equal(2, row["ParentID"]); row = table.Rows[4]; Assert.Equal(10, row["ChildID"]); Assert.Equal("ChildItem 1", row["ChildItem"]); Assert.Equal(3, row["ParentID"]); row = table.Rows[5]; Assert.Equal(11, row["ChildID"]); Assert.Equal("ChildItem 2", row["ChildItem"]); Assert.Equal(3, row["ParentID"]); } [Fact] public void XmlTest5() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); stream.Close(); } DataTable table = new DataTable("ParentTable"); DataSet dataSet = new DataSet("XmlDataSet"); dataSet.Tables.Add(table); table.Columns.Add(new DataColumn("id", typeof(string))); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(1, table.Columns.Count); Assert.Equal(typeof(string), table.Columns[0].DataType); Assert.NotNull(table.DataSet); //Check Rows DataRow row = table.Rows[0]; Assert.Equal("1", row[0]); row = table.Rows[1]; Assert.Equal("2", row[0]); row = table.Rows[2]; Assert.Equal("3", row[0]); } [Fact] public void XmlTest6() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); stream.Close(); } //Create a target table which has nomatching column(s) names DataTable table = new DataTable("ParentTable"); DataSet dataSet = new DataSet("XmlDataSet"); dataSet.Tables.Add(table); table.Columns.Add(new DataColumn("sid", typeof(string))); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { // ReadXml does not read anything as the column // names are not matching ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(1, table.Columns.Count); Assert.Equal("sid", table.Columns[0].ColumnName); Assert.Equal(typeof(string), table.Columns[0].DataType); Assert.NotNull(table.DataSet); } [Fact] public void XmlTest7() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); stream.Close(); } //Create a target table which has matching // column(s) name and an extra column DataTable table = new DataTable("ParentTable"); table.Columns.Add(new DataColumn("id", typeof(int))); table.Columns.Add(new DataColumn("ParentItem", typeof(string))); table.Columns.Add(new DataColumn("DepartmentID", typeof(int))); table.Columns.Add(new DataColumn("DummyColumn", typeof(string))); DataSet dataSet = new DataSet("XmlDataSet"); dataSet.Tables.Add(table); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(4, table.Columns.Count); Assert.NotNull(table.DataSet); //Check the Columns Assert.Equal("id", table.Columns[0].ColumnName); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal("ParentItem", table.Columns[1].ColumnName); Assert.Equal(typeof(string), table.Columns[1].DataType); Assert.Equal("DepartmentID", table.Columns[2].ColumnName); Assert.Equal(typeof(int), table.Columns[2].DataType); Assert.Equal("DummyColumn", table.Columns[3].ColumnName); Assert.Equal(typeof(string), table.Columns[3].DataType); //Check the rows DataRow row = table.Rows[0]; Assert.Equal(1, row["id"]); Assert.Equal("ParentItem 1", row["ParentItem"]); Assert.Equal(1, row["DepartmentID"]); row = table.Rows[1]; Assert.Equal(2, row["id"]); Assert.Equal("ParentItem 2", row["ParentItem"]); Assert.Equal(2, row["DepartmentID"]); row = table.Rows[2]; Assert.Equal(3, row["id"]); Assert.Equal("ParentItem 3", row["ParentItem"]); Assert.Equal(3, row["DepartmentID"]); } [Fact] public void XmlTest8() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table = new DataTable("ParentTable"); DataSet dataSet = new DataSet("XmlDataSet"); dataSet.Tables.Add(table); table.Columns.Add(new DataColumn("id", typeof(int))); table.Columns.Add(new DataColumn("DepartmentID", typeof(int))); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(2, table.Columns.Count); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal(typeof(int), table.Columns[1].DataType); Assert.NotNull(table.DataSet); //Check rows DataRow row = table.Rows[0]; Assert.Equal(1, row[0]); Assert.Equal(1, row[1]); row = table.Rows[1]; Assert.Equal(2, row[0]); Assert.Equal(2, row[1]); row = table.Rows[2]; Assert.Equal(3, row[0]); Assert.Equal(3, row[1]); } [Fact] public void XmlTest9() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataSet ds = new DataSet(); DataTable table = new DataTable("ParentTable"); table.Columns.Add(new DataColumn("id", typeof(int))); ds.Tables.Add(table); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(1, table.Columns.Count); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal("System.Data.DataSet", table.DataSet.ToString()); Assert.Equal("NewDataSet", table.DataSet.DataSetName); //Check the rows DataRow row = table.Rows[0]; Assert.Equal(1, row[0]); row = table.Rows[1]; Assert.Equal(2, row[0]); row = table.Rows[2]; Assert.Equal(3, row[0]); } [Fact] public void XmlTest10() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataSet ds = new DataSet(); DataTable table = new DataTable("ParentTable"); table.Columns.Add(new DataColumn("id", typeof(int))); table.Columns.Add(new DataColumn("DepartmentID", typeof(string))); ds.Tables.Add(table); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal("NewDataSet", table.DataSet.DataSetName); Assert.Equal(3, table.Rows.Count); Assert.Equal(2, table.Columns.Count); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal(typeof(string), table.Columns[1].DataType); //Check rows DataRow row = table.Rows[0]; Assert.Equal(1, row[0]); Assert.Equal("1", row[1]); row = table.Rows[1]; Assert.Equal(2, row[0]); Assert.Equal("2", row[1]); row = table.Rows[2]; Assert.Equal(3, row[0]); Assert.Equal("3", row[1]); } [Fact] public void XmlTest11() { MakeDummyTable(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _dummyTable); } //Create a table and set the table name DataTable table = new DataTable("DummyTable"); //define the table schame partially table.Columns.Add(new DataColumn("DummyItem", typeof(string))); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Null(table.DataSet); Assert.Equal(1, table.Columns.Count); Assert.Equal(typeof(string), table.Columns[0].DataType); Assert.Equal(3, table.Rows.Count); //Check Rows DataRow row = table.Rows[0]; Assert.Equal("DummyItem 1", row[0]); Assert.Equal(DataRowState.Unchanged, row.RowState); row = table.Rows[1]; Assert.Equal("Changed_DummyItem 2", row[0]); Assert.Equal(DataRowState.Modified, row.RowState); row = table.Rows[2]; Assert.Equal("DummyItem 3", row[0]); Assert.Equal(DataRowState.Unchanged, row.RowState); } [Fact] public void XmlTest14() { MakeParentTable1(); MakeChildTable(); MakeSecondChildTable(); MakeDataRelation(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table1 = new DataTable("ParentTable"); table1.Columns.Add(new DataColumn(_parentTable1.Columns[0].ColumnName, typeof(int))); table1.Columns.Add(new DataColumn(_parentTable1.Columns[1].ColumnName, typeof(string))); table1.Columns.Add(new DataColumn(_parentTable1.Columns[2].ColumnName, typeof(int))); ReadXmlSerializable(_tempFile, table1); Assert.Null(table1.DataSet); Assert.Equal("ParentTable", table1.TableName); Assert.Equal(3, table1.Columns.Count); Assert.Equal(typeof(int), table1.Columns[0].DataType); Assert.Equal(typeof(string), table1.Columns[1].DataType); Assert.Equal(typeof(int), table1.Columns[2].DataType); Assert.Equal(0, table1.ChildRelations.Count); Assert.Equal(3, table1.Rows.Count); //Check the row DataRow row = table1.Rows[0]; Assert.Equal(1, row[0]); Assert.Equal("ParentItem 1", row[1]); Assert.Equal(1, row[2]); row = table1.Rows[1]; Assert.Equal(2, row[0]); Assert.Equal("ParentItem 2", row[1]); Assert.Equal(2, row[2]); row = table1.Rows[2]; Assert.Equal(3, row[0]); Assert.Equal("ParentItem 3", row[1]); Assert.Equal(3, row[2]); } [Fact] public void XmlTest15() { MakeDummyTable(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _dummyTable); } Assert.Equal(3, _dummyTable.Rows.Count); DataSet dataSet = new DataSet("HelloWorldDataSet"); DataTable table = new DataTable("DummyTable"); table.Columns.Add(new DataColumn("DummyItem", typeof(string))); dataSet.Tables.Add(table); //Call ReadXml on a table which belong to a DataSet ReadXmlSerializable(_tempFile, table); Assert.Equal("HelloWorldDataSet", table.DataSet.DataSetName); Assert.Equal(1, table.Columns.Count); Assert.Equal(typeof(string), table.Columns[0].DataType); Assert.Equal(3, table.Rows.Count); //Check Rows DataRow row = table.Rows[0]; Assert.Equal("DummyItem 1", row[0]); Assert.Equal(DataRowState.Unchanged, row.RowState); row = table.Rows[1]; Assert.Equal("Changed_DummyItem 2", row[0]); Assert.Equal(DataRowState.Modified, row.RowState); row = table.Rows[2]; Assert.Equal("DummyItem 3", row[0]); Assert.Equal(DataRowState.Unchanged, row.RowState); } [Fact] public void XmlTest16() { DataSet ds = new DataSet(); DataTable parent = new DataTable("Parent"); parent.Columns.Add(new DataColumn("col1", typeof(int))); parent.Columns.Add(new DataColumn("col2", typeof(string))); parent.Columns[0].Unique = true; DataTable child1 = new DataTable("Child1"); child1.Columns.Add(new DataColumn("col3", typeof(int))); child1.Columns.Add(new DataColumn("col4", typeof(string))); child1.Columns.Add(new DataColumn("col5", typeof(int))); child1.Columns[2].Unique = true; DataTable child2 = new DataTable("Child2"); child2.Columns.Add(new DataColumn("col6", typeof(int))); child2.Columns.Add(new DataColumn("col7")); parent.Rows.Add(new object[] { 1, "P_" }); parent.Rows.Add(new object[] { 2, "P_" }); child1.Rows.Add(new object[] { 1, "C1_", 3 }); child1.Rows.Add(new object[] { 1, "C1_", 4 }); child1.Rows.Add(new object[] { 2, "C1_", 5 }); child1.Rows.Add(new object[] { 2, "C1_", 6 }); child2.Rows.Add(new object[] { 3, "C2_" }); child2.Rows.Add(new object[] { 3, "C2_" }); child2.Rows.Add(new object[] { 4, "C2_" }); child2.Rows.Add(new object[] { 4, "C2_" }); child2.Rows.Add(new object[] { 5, "C2_" }); child2.Rows.Add(new object[] { 5, "C2_" }); child2.Rows.Add(new object[] { 6, "C2_" }); child2.Rows.Add(new object[] { 6, "C2_" }); ds.Tables.Add(parent); ds.Tables.Add(child1); ds.Tables.Add(child2); DataRelation relation = new DataRelation("Relation1", parent.Columns[0], child1.Columns[0]); parent.ChildRelations.Add(relation); relation = new DataRelation("Relation2", child1.Columns[2], child2.Columns[0]); child1.ChildRelations.Add(relation); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, parent); } DataTable table = new DataTable(); ReadXmlSerializable(_tempFile, table); Assert.Equal("Parent", table.TableName); Assert.Equal(2, table.Columns.Count); Assert.Equal(2, table.Rows.Count); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal(typeof(string), table.Columns[1].DataType); Assert.Equal(1, table.Constraints.Count); Assert.Equal(typeof(UniqueConstraint), table.Constraints[0].GetType()); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Microsoft.NodejsTools.Jade { [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Tokenizer")] internal abstract class Tokenizer<T> : ITokenizer<T> where T : ITextRange { protected bool CComments { get; set; } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cpp")] protected bool CppComments { get; set; } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cpp")] protected bool MultilineCppComments { get; set; } protected bool SingleQuotedStrings { get; set; } protected bool DoubleQuotedStrings { get; set; } [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores")] protected CharacterStream _cs { get; set; } protected TextRangeCollection<T> Tokens { get; set; } protected Tokenizer() { this.CComments = true; this.CppComments = true; this.MultilineCppComments = false; this.SingleQuotedStrings = true; this.DoubleQuotedStrings = true; } public ReadOnlyTextRangeCollection<T> Tokenize(ITextProvider textProvider, int start, int length) { return Tokenize(textProvider, start, length, false); } public virtual ReadOnlyTextRangeCollection<T> Tokenize(ITextProvider textProvider, int start, int length, bool excludePartialTokens) { Debug.Assert(start >= 0 && length >= 0 && start + length <= textProvider.Length); this._cs = new CharacterStream(textProvider); this._cs.Position = start; this.Tokens = new TextRangeCollection<T>(); while (!this._cs.IsEndOfStream()) { // Keep on adding tokens... AddNextToken(); if (this._cs.Position >= start + length) break; } if (excludePartialTokens) { var end = start + length; // Exclude tokens that are beyond the specified range int i; for (i = this.Tokens.Count - 1; i >= 0; i--) { if (this.Tokens[i].End <= end) break; } i++; if (i < this.Tokens.Count) this.Tokens.RemoveRange(i, this.Tokens.Count - i); } var collection = new ReadOnlyTextRangeCollection<T>(this.Tokens); this.Tokens = null; return collection; } protected abstract T GetCommentToken(int start, int length); protected abstract T GetStringToken(int start, int length); protected virtual bool AddNextToken() { SkipWhiteSpace(); if (this._cs.IsEndOfStream()) return true; switch (this._cs.CurrentChar) { case '\'': if (this.SingleQuotedStrings) { HandleString(); return true; } break; case '\"': if (this.DoubleQuotedStrings) { HandleString(); return true; } break; case '/': if (this._cs.NextChar == '/' && this.CppComments) { HandleCppComment(); return true; } else if (this._cs.NextChar == '*' && this.CComments) { HandleCComment(); return true; } break; } return false; } /// <summary> /// Processes comments (// or /*) /// </summary> /// <returns>True if comment included new line characters</returns> protected virtual bool HandleComment(bool multiline) { if (this._cs.CurrentChar == '/') { if (this.CComments && this._cs.NextChar == '*') { HandleCComment(); return false; } else if (this.CppComments && this._cs.NextChar == '/') { return HandleCppComment(multiline); } } return false; } /// <summary> /// Processes C++ style comments (//) /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cpp")] protected bool HandleCppComment() { return HandleCppComment(false); } /// <summary> /// Processes C++ style comments (//) /// </summary> /// <returns>True if comment included new line characters</returns> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cpp")] protected bool HandleCppComment(bool multiline = false) { // SaSS version can span more than one line like this (indented): // // // This comment will not appear in the CSS output. // This is nested beneath the comment as well, // so it also won't appear. var start = this._cs.Position; var baseIndent = 0; if (this.MultilineCppComments) { baseIndent = CalculateLineIndent(); multiline = true; // only standalone // comments can span more than one line for (var i = this._cs.Position - 1; i >= 0; i--) { var ch = this._cs[i]; if (ch == '\r' || ch == '\n') break; if (!Char.IsWhiteSpace(ch)) { multiline = false; break; } } } else { multiline = false; } this._cs.Advance(2); // skip over // while (!this._cs.IsEndOfStream()) { var eolPosition = this._cs.Position; if (this._cs.IsAtNewLine()) { if (multiline) { // skip '\r' this._cs.MoveToNextChar(); // Skip '\n' if (this._cs.IsAtNewLine()) this._cs.MoveToNextChar(); SkipToNonWhiteSpaceOrEndOfLine(); if (this._cs.IsEndOfStream()) { this._cs.Position = eolPosition; break; } var lineIndent = CalculateLineIndent(); if (lineIndent <= baseIndent) { // Ignore empty lines, they do not break current block if (lineIndent == 0 && this._cs.IsAtNewLine()) { continue; } else { this._cs.Position = eolPosition; break; } } } else { break; } } this._cs.MoveToNextChar(); } var length = this._cs.Position - start; if (length > 0) this.Tokens.Add(GetCommentToken(start, length)); return true; } /// <summary> /// Processes C-style comments (/* */) /// </summary> /// <returns>True if comment includes new line characters</returns> protected virtual void HandleCComment() { var start = this._cs.Position; this._cs.Advance(2); while (!this._cs.IsEndOfStream()) { if (this._cs.CurrentChar == '*' && this._cs.NextChar == '/') { this._cs.Advance(2); break; } this._cs.MoveToNextChar(); } var length = this._cs.Position - start; if (length > 0) this.Tokens.Add(GetCommentToken(start, length)); } /// <summary> /// Handles single or double quoted strings /// </summary> protected virtual ITextRange HandleString(bool addToken = true) { var start = this._cs.Position; var quote = this._cs.CurrentChar; // since the escape char is exactly the string openning char we say we start in escaped mode // it will get reset by the first char regardless what it is, but it will keep the '' case honest this._cs.MoveToNextChar(); while (!this._cs.IsEndOfStream() && !this._cs.IsAtNewLine()) { if (this._cs.CurrentChar == '\\' && this._cs.NextChar == quote) { this._cs.Advance(2); } if (this._cs.CurrentChar == quote) { this._cs.MoveToNextChar(); break; } this._cs.MoveToNextChar(); } var range = TextRange.FromBounds(start, this._cs.Position); if (range.Length > 0) this.Tokens.Add(GetStringToken(start, range.Length)); return range; } /// <summary> /// Collects all characters up to the next whitespace /// </summary> /// <returns>Sequence range</returns> protected ITextRange GetNonWSSequence() { return GetNonWSSequence('\0', inclusive: false); } /// <summary> /// Collects all characters up to the next whitespace /// </summary> /// <param name="terminator">Terminator character</param> /// <param name="inclusive">True if sequence includes the terminator, /// false if advance should stop at the terminator character</param> /// <returns>Sequence range</returns> protected virtual ITextRange GetNonWSSequence(char terminator, bool inclusive) { var start = this._cs.Position; while (!this._cs.IsEndOfStream() && !this._cs.IsWhiteSpace()) { if (this._cs.CurrentChar == terminator && terminator != '\0') { if (inclusive) this._cs.MoveToNextChar(); break; } this._cs.MoveToNextChar(); } return TextRange.FromBounds(start, this._cs.Position); } /// <summary> /// Collects all characters up to the next whitespace always /// including the current character /// </summary> /// <returns>Sequence range</returns> protected ITextRange GetNonWSSequence(string terminators) { var start = this._cs.Position; this._cs.MoveToNextChar(); while (!this._cs.IsEndOfStream() && !this._cs.IsWhiteSpace()) { if (terminators.IndexOf(this._cs.CurrentChar) != -1) return TextRange.FromBounds(start, this._cs.Position); this._cs.MoveToNextChar(); } return TextRange.FromBounds(start, this._cs.Position); } /// <summary> /// Collects 'identifier' sequence. Identifier consists of ANSI characters and decimal digits. /// </summary> /// <returns>Identifier range</returns> protected virtual ITextRange ParseIdentifier() { var start = this._cs.Position; while (!this._cs.IsEndOfStream() && !this._cs.IsWhiteSpace() && (this._cs.IsAnsiLetter() || this._cs.IsDecimal() || this._cs.CurrentChar == '_')) { this._cs.MoveToNextChar(); } return TextRange.FromBounds(start, this._cs.Position); } /// <summary> /// Determines amount of leading whitespace in the current line /// </summary> protected int CalculateLineIndent() { var baseIndent = -1; // Find base tag indent for (var pos = this._cs.Position - 1; pos >= 0 && baseIndent < 0; pos--) { if (this._cs[pos] == '\n' || this._cs[pos] == '\r') { pos++; for (var j = pos; j < this._cs.Position + 1; j++) { if (j == this._cs.Position || !Char.IsWhiteSpace(this._cs[j])) { baseIndent = j - pos; break; } } break; } } return baseIndent >= 0 ? baseIndent : 0; } /// <summary> /// Skips over all whitespace. Stops at non-whitespace character or end of file. /// </summary> /// <returns>True if whitespace included newline characters</returns> protected virtual bool SkipWhiteSpace() { var newLine = false; while (!this._cs.IsEndOfStream()) { if (!this._cs.IsWhiteSpace()) break; if (this._cs.IsAtNewLine()) newLine = true; this._cs.MoveToNextChar(); } return newLine; } /// <summary> /// Advances character stream to the next end of line. /// </summary> protected virtual void SkipToEndOfLine() { while (!this._cs.IsEndOfStream() && !this._cs.IsAtNewLine()) { this._cs.MoveToNextChar(); } } /// <summary> /// Advances character stream to the next end of line, comment or end of file. /// </summary> protected virtual void SkipToEndOfLineOrComment() { while (!this._cs.IsEndOfStream() && !this._cs.IsAtNewLine() && !IsAtComment()) { this._cs.MoveToNextChar(); } } /// <summary> /// Advances character stream to the next whitespace, comment or end of file. /// </summary> protected virtual void SkipToWhiteSpaceOrComment() { while (!this._cs.IsEndOfStream()) { if (this._cs.IsWhiteSpace() || IsAtComment()) break; this._cs.MoveToNextChar(); } } /// <summary> /// Advances character stream to the next whitespace /// </summary> protected virtual void SkipToWhiteSpace() { while (!this._cs.IsEndOfStream()) { if (this._cs.IsWhiteSpace()) break; this._cs.MoveToNextChar(); } } /// <summary> /// Advances character stream to the next non-whitespace character /// </summary> protected virtual void SkipToNonWhiteSpaceOrEndOfLine() { while (!this._cs.IsEndOfStream()) { if (!this._cs.IsWhiteSpace() || this._cs.IsAtNewLine()) break; this._cs.MoveToNextChar(); } } /// <summary> /// Checks if character stream is at a comment sequence (// or /*) /// </summary> protected virtual bool IsAtComment() { return (this._cs.CurrentChar == '/' && ((this._cs.NextChar == '/' && this.CppComments) || (this._cs.NextChar == '*' && this.CComments))); } /// <summary> /// Checks if character stream is at a string (' or ") /// </summary> protected virtual bool IsAtString() { return ((this._cs.CurrentChar == '\'' && this.SingleQuotedStrings) || (this._cs.CurrentChar == '\"' && this.DoubleQuotedStrings)); } /// <summary> /// Determines if remaning part of the line is all whitespace /// </summary> protected virtual bool IsAllWhiteSpaceBeforeEndOfLine(int position) { var allWS = true; for (var i = position; i < this._cs.Length; i++) { var ch = this._cs[i]; if (ch == '\r' || ch == '\n') break; if (!Char.IsWhiteSpace(ch)) { allWS = false; break; } } return allWS; } } }
// 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.Globalization; using Xunit; namespace System.Collections.HashtableTests { public class CopyToTests { [Fact] public void TestCopyToBasic() { Hashtable hash = null; // the hashtable object which will be used in the tests object[] objArr = null; // the object array corresponding to arr object[] objArr2 = null; // helper object array object[,] objArrRMDim = null; // multi dimensional object array // these are the keys and values which will be added to the hashtable in the tests object[] keys = new object[] { new object(), "Hello" , "my array" , new DateTime(), new SortedList(), typeof( System.Environment ), 5 }; object[] values = new object[] { "Somestring" , new object(), new int [] { 1, 2, 3, 4, 5 }, new Hashtable(), new Exception(), new CopyToTests(), null }; //[]test normal conditions, array is large enough to hold all elements // make new hashtable hash = new Hashtable(); // put in values and keys for (int i = 0; i < values.Length; i++) { hash.Add(keys[i], values[i]); } // now try getting out the values using CopyTo method objArr = new object[values.Length + 2]; // put a sentinal in first position, and make sure it is not overriden objArr[0] = "startstring"; // put a sentinal in last position, and make sure it is not overriden objArr[values.Length + 1] = "endstring"; hash.Values.CopyTo((Array)objArr, 1); // make sure sentinal character is still there Assert.Equal("startstring", objArr[0]); Assert.Equal("endstring", objArr[values.Length + 1]); // check to make sure arr is filled up with the correct elements objArr2 = new object[values.Length]; Array.Copy(objArr, 1, objArr2, 0, values.Length); objArr = objArr2; Assert.True(CompareArrays(objArr, values)); //[] This is the same test as before but now we are going to used Hashtable.CopyTo instead of Hasthabe.Values.CopyTo // now try getting out the values using CopyTo method objArr = new object[values.Length + 2]; // put a sentinal in first position, and make sure it is not overriden objArr[0] = "startstring"; // put a sentinal in last position, and make sure it is not overriden objArr[values.Length + 1] = "endstring"; hash.CopyTo((Array)objArr, 1); // make sure sentinal character is still there Assert.Equal("startstring", objArr[0]); Assert.Equal("endstring", objArr[values.Length + 1]); // check to make sure arr is filled up with the correct elements BitArray bitArray = new BitArray(values.Length); for (int i = 0; i < values.Length; i++) { DictionaryEntry entry = (DictionaryEntry)objArr[i + 1]; int valueIndex = Array.IndexOf(values, entry.Value); int keyIndex = Array.IndexOf(keys, entry.Key); Assert.NotEqual(-1, valueIndex); Assert.NotEqual(-1, keyIndex); Assert.Equal(valueIndex, keyIndex); bitArray[i] = true; } for (int i = 0; i < ((ICollection)bitArray).Count; i++) { Assert.True(bitArray[i]); } //[] Parameter validation //[] Null array Assert.Throws<ArgumentNullException>(() => { hash = new Hashtable(); objArr = new object[0]; hash.CopyTo(null, 0); } ); //[] Multidimentional array Assert.Throws<ArgumentException>(() => { hash = new Hashtable(); objArrRMDim = new object[16, 16]; hash.CopyTo(objArrRMDim, 0); } ); //[] Array not large enough Assert.Throws<ArgumentException>(() => { hash = new Hashtable(); for (int i = 0; i < 256; i++) { hash.Add(i.ToString(), i); } objArr = new object[hash.Count + 8]; hash.CopyTo(objArr, 9); } ); Assert.Throws<ArgumentException>(() => { hash = new Hashtable(); objArr = new object[0]; hash.CopyTo(objArr, Int32.MaxValue); } ); Assert.Throws<ArgumentOutOfRangeException>(() => { hash = new Hashtable(); objArr = new object[0]; hash.CopyTo(objArr, Int32.MinValue); } ); //[]copy should throw because of outofrange Random random = new Random(-55); for (int iii = 0; iii < 20; iii++) { Assert.Throws<ArgumentOutOfRangeException>(() => { hash = new Hashtable(); objArr = new object[0]; hash.CopyTo(objArr, random.Next(-1000, 0)); } ); } //[]test when array is to small to hold all values hashtable has more values then array can hold hash = new Hashtable(); // put in values and keys for (int i = 0; i < values.Length; i++) { hash.Add(keys[i], values[i]); } // now try getting out the values using CopyTo method into a small array objArr = new object[values.Length - 1]; Assert.Throws<ArgumentException>(() => { hash.Values.CopyTo((Array)objArr, 0); } ); //[]test when array is size 0 // now try getting out the values using CopyTo method into a 0 sized array objArr = new object[0]; Assert.Throws<ArgumentException>(() => { hash.Values.CopyTo((Array)objArr, 0); } ); //[]test when array is null Assert.Throws<ArgumentNullException>(() => { hash.Values.CopyTo(null, 0); } ); } [Fact] public void TestCopyToWithValidIndex() { //[]test when hashtable has no elements in it var hash = new Hashtable(); // make an array of 100 size to hold elements var objArr = new object[100]; hash.Values.CopyTo(objArr, 0); objArr = new object[100]; hash.Values.CopyTo(objArr, 99); objArr = new object[100]; // valid now hash.Values.CopyTo(objArr, 100); // make an array of 0 size to hold elements objArr = new object[0]; hash.Values.CopyTo(objArr, 0); int key = 123; int val = 456; hash.Add(key, val); objArr = new object[100]; objArr[0] = 0; hash.Values.CopyTo(objArr, 0); Assert.Equal(val, objArr[0]); hash.Values.CopyTo(objArr, 99); Assert.Equal(val, objArr[99]); } [Fact] public void TestCopyToWithInvalidIndex() { object[] objArr = null; object[][] objArrMDim = null; // multi dimensional object array object[,] objArrRMDim = null; // multi dimensional object array //[]test when hashtable has no elements in it and index is out of range (negative) var hash = new Hashtable(); // put no elements in hashtable Assert.Throws<ArgumentOutOfRangeException>(() => { // make an array of 100 size to hold elements objArr = new object[0]; hash.Values.CopyTo(objArr, -1); } ); //[]test when array is multi dimensional and array is large enough hash = new Hashtable(); // put elements into hashtable for (int i = 0; i < 100; i++) { hash.Add(i.ToString(), i.ToString()); } Assert.Throws<InvalidCastException>(() => { // make an array of 100 size to hold elements objArrMDim = new object[100][]; for (int i = 0; i < 100; i++) { objArrMDim[i] = new object[i + 1]; } hash.Values.CopyTo(objArrMDim, 0); } ); Assert.Throws<ArgumentException>(() => { // make an array of 100 size to hold elements objArrRMDim = new object[100, 100]; hash.Values.CopyTo(objArrRMDim, 0); } ); //[]test when array is multi dimensional and array is small hash = new Hashtable(); // put elements into hashtable for (int i = 0; i < 100; i++) { hash.Add(i.ToString(), i.ToString()); } Assert.Throws<ArgumentException>(() => { // make an array of 100 size to hold elements objArrMDim = new object[99][]; for (int i = 0; i < 99; i++) { objArrMDim[i] = new object[i + 1]; } hash.Values.CopyTo(objArrMDim, 0); } ); //[]test to see if CopyTo throws correct exception hash = new Hashtable(); Assert.Throws<ArgumentException>(() => { string[] str = new string[100]; // i will be calling CopyTo with the str array and index 101 it should throw an exception // since the array index 101 is not valid hash.Values.CopyTo(str, 101); } ); } /////////////////////////// HELPER FUNCTIONS // this is pretty slow algorithm but it works // returns true if arr1 has the same elements as arr2 // arrays can have nulls in them, but arr1 and arr2 should not be null public static bool CompareArrays(object[] arr1, object[] arr2) { if (arr1.Length != arr2.Length) { return false; } int i, j; bool fPresent = false; for (i = 0; i < arr1.Length; i++) { fPresent = false; for (j = 0; j < arr2.Length && (fPresent == false); j++) { if ((arr1[i] == null && arr2[j] == null) || (arr1[i] != null && arr1[i].Equals(arr2[j]))) { fPresent = true; } } if (fPresent == false) { return false; } } // now do the same thing but the other way around for (i = 0; i < arr2.Length; i++) { fPresent = false; for (j = 0; j < arr1.Length && (fPresent == false); j++) { if ((arr2[i] == null && arr1[j] == null) || (arr2[i] != null && arr2[i].Equals(arr1[j]))) { fPresent = true; } } if (fPresent == false) { return false; } } return true; } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; namespace FileHelpers.Options { using System.Collections.Generic; /// <summary> /// This class allows you to set some options of the records at runtime. /// With these options the library is now more flexible than ever. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public abstract class RecordOptions { [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal IRecordInfo mRecordInfo; /// <summary> /// This class allows you to set some options of the records at runtime. /// With these options the library is now more flexible than ever. /// </summary> /// <param name="info">Record information</param> internal RecordOptions(IRecordInfo info) { mRecordInfo = info; mRecordConditionInfo = new RecordConditionInfo(info); mIgnoreCommentInfo = new IgnoreCommentInfo(info); } public FieldBaseCollection Fields { get { return new FieldBaseCollection(mRecordInfo.Fields); } } public void RemoveField(string fieldname) { mRecordInfo.RemoveField(fieldname); //for (int i = 0; i < Fields.Count; i++) //{ // var field = Fields[i]; // field.ParentIndex = i; //} } /// <summary> /// The number of fields of the record type. /// </summary> public int FieldCount { get { return mRecordInfo.FieldCount; } } // <summary>The number of fields of the record type.</summary> //[System.Runtime.CompilerServices.IndexerName("FieldNames")] //public string this[int index] //{ // get // { // return mRecordInfo.mFields[index].mFieldInfo.Name; // } //} [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string[] mFieldNames; /// <summary> /// Returns an string array with the fields names. /// Note : Do NOT change the values of the array, clone it first if needed /// </summary> /// <returns>An string array with the fields names.</returns> public string[] FieldsNames { get { if (mFieldNames == null) { mFieldNames = new string[mRecordInfo.FieldCount]; for (int i = 0; i < mFieldNames.Length; i++) mFieldNames[i] = mRecordInfo.Fields[i].FieldFriendlyName; } return mFieldNames; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private Type[] mFieldTypes; /// <summary> /// Returns a Type[] array with the fields types. /// Note : Do NOT change the values of the array, clone it first if /// needed /// </summary> /// <returns>An Type[] array with the fields types.</returns> public Type[] FieldsTypes { get { if (mFieldTypes == null) { mFieldTypes = new Type[mRecordInfo.FieldCount]; for (int i = 0; i < mFieldTypes.Length; i++) mFieldTypes[i] = mRecordInfo.Fields[i].FieldInfo.FieldType; } return mFieldTypes; } } // /// <summary>Returns the type of the field at the specified index</summary> // /// <returns>The type of the field.</returns> // /// <param name="index">The index of the field</param> // public Type GetFieldType(int index) // { // return mRecordInfo.mFields[index].mFieldInfo.FieldType; // } /// <summary> /// Indicates the number of first lines to be discarded. /// </summary> public int IgnoreFirstLines { get { return mRecordInfo.IgnoreFirst; } set { ExHelper.PositiveValue(value); mRecordInfo.IgnoreFirst = value; } } /// <summary> /// Indicates the number of lines at the end of file to be discarded. /// </summary> public int IgnoreLastLines { get { return mRecordInfo.IgnoreLast; } set { ExHelper.PositiveValue(value); mRecordInfo.IgnoreLast = value; } } /// <summary> /// Indicates that the engine must ignore the empty lines while /// reading. /// </summary> public bool IgnoreEmptyLines { get { return mRecordInfo.IgnoreEmptyLines; } set { mRecordInfo.IgnoreEmptyLines = value; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly RecordConditionInfo mRecordConditionInfo; /// <summary> /// Used to tell the engine which records must be included or excluded /// while reading. /// </summary> public RecordConditionInfo RecordCondition { get { return mRecordConditionInfo; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly IgnoreCommentInfo mIgnoreCommentInfo; /// <summary> /// Indicates that the engine must ignore the lines with this comment /// marker. /// </summary> public IgnoreCommentInfo IgnoreCommentedLines { get { return mIgnoreCommentInfo; } } /// <summary> /// Gets or sets a value indicating whether we should attempt to infer column order from the file/stream header. /// </summary> public bool ShouldInferColumnOrderFromHeader { get; set; } /// <summary> /// Used to tell the engine which records must be included or excluded /// while reading. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public sealed class RecordConditionInfo { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly IRecordInfo mRecordInfo; /// <summary> /// Used to tell the engine which records must be included or /// excluded while reading. /// </summary> /// <param name="ri">Record information</param> internal RecordConditionInfo(IRecordInfo ri) { mRecordInfo = ri; } /// <summary> /// The condition used to include or exclude records. /// </summary> public RecordCondition Condition { get { return mRecordInfo.RecordCondition; } set { mRecordInfo.RecordCondition = value; } } /// <summary> /// The selector used by the <see cref="RecordCondition"/>. /// </summary> public string Selector { get { return mRecordInfo.RecordConditionSelector; } set { mRecordInfo.RecordConditionSelector = value; } } } /// <summary> /// Indicates that the engine must ignore the lines with this comment /// marker. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public sealed class IgnoreCommentInfo { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly IRecordInfo mRecordInfo; /// <summary> /// Indicates that the engine must ignore the lines with this /// comment marker. /// </summary> /// <param name="ri">Record information</param> internal IgnoreCommentInfo(IRecordInfo ri) { mRecordInfo = ri; } /// <summary> /// <para>Indicates that the engine must ignore the lines with this /// comment marker.</para> /// <para>An empty string or null indicates that the engine doesn't /// look for comments</para> /// </summary> public string CommentMarker { get { return mRecordInfo.CommentMarker; } set { if (value != null) value = value.Trim(); mRecordInfo.CommentMarker = value; } } /// <summary> /// Indicates if the comment can have spaces or tabs at left (true /// by default) /// </summary> public bool InAnyPlace { get { return mRecordInfo.CommentAnyPlace; } set { mRecordInfo.CommentAnyPlace = value; } } } /// <summary> /// Allows the creating of a record string of the given record. Is /// useful when your want to log errors to a plan text file or database /// </summary> /// <param name="record"> /// The record that will be transformed to string /// </param> /// <returns>The string representation of the current record</returns> public string RecordToString(object record) { return mRecordInfo.Operations.RecordToString(record); } /// <summary> /// Allows to get an object[] with the values of the fields in the <param name="record"></param> /// </summary> /// <param name="record">The record that will be transformed to object[]</param> /// <returns>The object[] with the values of the fields in the current record</returns> public object[] RecordToValues(object record) { return mRecordInfo.Operations.RecordToValues(record); } } public sealed class FieldBaseCollection : List<FieldBase> { internal FieldBaseCollection(FieldBase[] fields) : base(fields) {} } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Threading; using System.Collections.Generic; using System.Runtime.Diagnostics; namespace System.ServiceModel.Diagnostics { internal class ServiceModelActivity : IDisposable { [ThreadStatic] private static ServiceModelActivity s_currentActivity; private static string[] s_ActivityTypeNames = new string[(int)ActivityType.NumItems]; private ServiceModelActivity _previousActivity = null; private static string s_activityBoundaryDescription = null; private ActivityState _lastState = ActivityState.Unknown; private string _name = null; private bool _autoStop = false; private bool _autoResume = false; private Guid _activityId; private bool _disposed = false; private bool _isAsync = false; private int _stopCount = 0; private const int AsyncStopCount = 2; private TransferActivity _activity = null; private ActivityType _activityType = ActivityType.Unknown; static ServiceModelActivity() { s_ActivityTypeNames[(int)ActivityType.Unknown] = "Unknown"; s_ActivityTypeNames[(int)ActivityType.Close] = "Close"; s_ActivityTypeNames[(int)ActivityType.Construct] = "Construct"; s_ActivityTypeNames[(int)ActivityType.ExecuteUserCode] = "ExecuteUserCode"; s_ActivityTypeNames[(int)ActivityType.ListenAt] = "ListenAt"; s_ActivityTypeNames[(int)ActivityType.Open] = "Open"; s_ActivityTypeNames[(int)ActivityType.OpenClient] = "Open"; s_ActivityTypeNames[(int)ActivityType.ProcessMessage] = "ProcessMessage"; s_ActivityTypeNames[(int)ActivityType.ProcessAction] = "ProcessAction"; s_ActivityTypeNames[(int)ActivityType.ReceiveBytes] = "ReceiveBytes"; s_ActivityTypeNames[(int)ActivityType.SecuritySetup] = "SecuritySetup"; s_ActivityTypeNames[(int)ActivityType.TransferToComPlus] = "TransferToComPlus"; s_ActivityTypeNames[(int)ActivityType.WmiGetObject] = "WmiGetObject"; s_ActivityTypeNames[(int)ActivityType.WmiPutInstance] = "WmiPutInstance"; } private ServiceModelActivity(Guid activityId) { _activityId = activityId; _previousActivity = ServiceModelActivity.Current; } private static string ActivityBoundaryDescription { get { if (ServiceModelActivity.s_activityBoundaryDescription == null) { ServiceModelActivity.s_activityBoundaryDescription = SR.ActivityBoundary; } return ServiceModelActivity.s_activityBoundaryDescription; } } internal ActivityType ActivityType { get { return _activityType; } } internal ServiceModelActivity PreviousActivity { get { return _previousActivity; } } static internal Activity BoundOperation(ServiceModelActivity activity) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } return ServiceModelActivity.BoundOperation(activity, false); } static internal Activity BoundOperation(ServiceModelActivity activity, bool addTransfer) { return activity == null ? null : ServiceModelActivity.BoundOperationCore(activity, addTransfer); } private static Activity BoundOperationCore(ServiceModelActivity activity, bool addTransfer) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } TransferActivity retval = null; if (activity != null) { retval = TransferActivity.CreateActivity(activity._activityId, addTransfer); if (retval != null) { retval.SetPreviousServiceModelActivity(ServiceModelActivity.Current); } ServiceModelActivity.Current = activity; } return retval; } internal static ServiceModelActivity CreateActivity() { if (!DiagnosticUtility.ShouldUseActivity) { return null; } return ServiceModelActivity.CreateActivity(Guid.NewGuid(), true); } internal static ServiceModelActivity CreateActivity(bool autoStop) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } ServiceModelActivity activity = ServiceModelActivity.CreateActivity(Guid.NewGuid(), true); if (activity != null) { activity._autoStop = autoStop; } return activity; } internal static ServiceModelActivity CreateActivity(bool autoStop, string activityName, ActivityType activityType) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } ServiceModelActivity activity = ServiceModelActivity.CreateActivity(autoStop); ServiceModelActivity.Start(activity, activityName, activityType); return activity; } internal static ServiceModelActivity CreateAsyncActivity() { if (!DiagnosticUtility.ShouldUseActivity) { return null; } ServiceModelActivity activity = ServiceModelActivity.CreateActivity(true); if (activity != null) { activity._isAsync = true; } return activity; } internal static ServiceModelActivity CreateBoundedActivity() { return ServiceModelActivity.CreateBoundedActivity(false); } internal static ServiceModelActivity CreateBoundedActivity(bool suspendCurrent) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } ServiceModelActivity activityToSuspend = ServiceModelActivity.Current; ServiceModelActivity retval = ServiceModelActivity.CreateActivity(true); if (retval != null) { retval._activity = (TransferActivity)ServiceModelActivity.BoundOperation(retval, true); retval._activity.SetPreviousServiceModelActivity(activityToSuspend); if (suspendCurrent) { retval._autoResume = true; } } if (suspendCurrent && activityToSuspend != null) { activityToSuspend.Suspend(); } return retval; } internal static ServiceModelActivity CreateBoundedActivity(Guid activityId) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } ServiceModelActivity retval = ServiceModelActivity.CreateActivity(activityId, true); if (retval != null) { retval._activity = (TransferActivity)ServiceModelActivity.BoundOperation(retval, true); } return retval; } internal static ServiceModelActivity CreateBoundedActivityWithTransferInOnly(Guid activityId) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } ServiceModelActivity retval = ServiceModelActivity.CreateActivity(activityId, true); if (retval != null) { if (null != FxTrace.Trace) { FxTrace.Trace.TraceTransfer(activityId); } retval._activity = (TransferActivity)ServiceModelActivity.BoundOperation(retval); } return retval; } internal static ServiceModelActivity CreateLightWeightAsyncActivity(Guid activityId) { return new ServiceModelActivity(activityId); } internal static ServiceModelActivity CreateActivity(Guid activityId) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } ServiceModelActivity retval = null; if (activityId != Guid.Empty) { retval = new ServiceModelActivity(activityId); } if (retval != null) { ServiceModelActivity.Current = retval; } return retval; } internal static ServiceModelActivity CreateActivity(Guid activityId, bool autoStop) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } ServiceModelActivity retval = ServiceModelActivity.CreateActivity(activityId); if (retval != null) { retval._autoStop = autoStop; } return retval; } internal static ServiceModelActivity Current { get { return ServiceModelActivity.s_currentActivity; } private set { ServiceModelActivity.s_currentActivity = value; } } public void Dispose() { if (!_disposed) { _disposed = true; try { if (_activity != null) { _activity.Dispose(); } if (_autoStop) { this.Stop(); } if (_autoResume && ServiceModelActivity.Current != null) { ServiceModelActivity.Current.Resume(); } } finally { ServiceModelActivity.Current = _previousActivity; GC.SuppressFinalize(this); } } } internal Guid Id { get { return _activityId; } } private ActivityState LastState { get { return _lastState; } set { _lastState = value; } } internal string Name { get { return _name; } set { _name = value; } } internal void Resume() { if (this.LastState == ActivityState.Suspend) { this.LastState = ActivityState.Resume; } } internal void Resume(string activityName) { if (string.IsNullOrEmpty(this.Name)) { _name = activityName; } this.Resume(); } static internal void Start(ServiceModelActivity activity, string activityName, ActivityType activityType) { if (activity != null && activity.LastState == ActivityState.Unknown) { activity.LastState = ActivityState.Start; activity._name = activityName; activity._activityType = activityType; } } internal void Stop() { int newStopCount = 0; if (_isAsync) { newStopCount = Interlocked.Increment(ref _stopCount); } if (this.LastState != ActivityState.Stop && (!_isAsync || (_isAsync && newStopCount >= ServiceModelActivity.AsyncStopCount))) { this.LastState = ActivityState.Stop; } } static internal void Stop(ServiceModelActivity activity) { if (activity != null) { activity.Stop(); } } internal void Suspend() { if (this.LastState != ActivityState.Stop) { this.LastState = ActivityState.Suspend; } } public override string ToString() { return this.Id.ToString(); } private enum ActivityState { Unknown, Start, Suspend, Resume, Stop, } internal class TransferActivity : Activity { private bool _addTransfer = false; private bool _changeCurrentServiceModelActivity = false; private ServiceModelActivity _previousActivity = null; private TransferActivity(Guid activityId, Guid parentId) : base(activityId, parentId) { } internal static TransferActivity CreateActivity(Guid activityId, bool addTransfer) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } TransferActivity retval = null; return retval; } internal void SetPreviousServiceModelActivity(ServiceModelActivity previous) { _previousActivity = previous; _changeCurrentServiceModelActivity = true; } public override void Dispose() { try { if (_addTransfer) { // Make sure that we are transferring from our AID to the // parent. It is possible for someone else to change the ambient // in user code (MB 49318). using (Activity.CreateActivity(this.Id)) { if (null != FxTrace.Trace) { FxTrace.Trace.TraceTransfer(this.parentId); } } } } finally { if (_changeCurrentServiceModelActivity) { ServiceModelActivity.Current = _previousActivity; } base.Dispose(); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; using DiffPlex; using DiffPlex.DiffBuilder; using DiffPlex.DiffBuilder.Model; namespace DDDLanguage { internal class TextBoxDiffRenderer { private readonly Grid leftGrid; private readonly TextBox leftBox; private readonly Grid rightGrid; private readonly TextBox rightBox; private const char ImaginaryLineCharacter = '\u202B'; private readonly SideBySideDiffBuilder differ; private readonly object mutex = new object(); private bool inDiff; private readonly List<FontInfo> fontInfos; private readonly FontInfo currentFont; public TextBoxDiffRenderer(Grid leftGrid, TextBox leftBox, Grid rightGrid, TextBox rightBox) { this.leftGrid = leftGrid; this.leftBox = leftBox; this.rightGrid = rightGrid; this.rightBox = rightBox; differ = new SideBySideDiffBuilder(new Differ()); fontInfos = new List<FontInfo> { new FontInfo("Courier New", 1.466, 6.62, 3.5) }; LinePaddingOverride = 1.593; CharacterWidthOverride = 7.2; currentFont = fontInfos.Single(x => x.FontFamily.Equals(leftBox.FontFamily.Source, StringComparison.OrdinalIgnoreCase)); } public bool ShowVisualAids { private get; set; } public double? CharacterWidthOverride { private get; set; } public double? LeftOffsetOverride { private get; set; } public double? LinePaddingOverride { private get; set; } public double? TopOffsetOverride { private get; set; } public void GenerateDiffView() { if (inDiff) return; lock (mutex) { if (inDiff) return; inDiff = true; } StripImaginaryLinesAndCharacters(leftBox); StripImaginaryLinesAndCharacters(rightBox); var leftContent = leftBox.Text; var rightContent = rightBox.Text; var diffRes = differ.BuildDiffModel(leftContent, rightContent); GenerateDiffPanes(diffRes.OldText, diffRes.NewText); inDiff = false; } private void GenerateDiffPanes(DiffPaneModel leftDiff, DiffPaneModel rightDiff) { RenderDiffLines(leftGrid, leftBox, leftDiff); RenderDiffLines(rightGrid, rightBox, rightDiff); } private static void ClearDiffLines(Grid grid) { foreach (var rect in grid.Children.OfType<Rectangle>().ToList()) grid.Children.Remove(rect); } private void RenderDiffLines(Grid grid, TextBox textBox, DiffPaneModel diffModel) { ClearDiffLines(grid); var lineNumber = 0; foreach (var line in diffModel.Lines) { var fillColor = new SolidColorBrush(Colors.Transparent); if (line.Type == ChangeType.Deleted) fillColor = new SolidColorBrush(Color.FromArgb(255, 255, 221, 221)); else if (line.Type == ChangeType.Inserted) fillColor = new SolidColorBrush(Color.FromArgb(255, 221, 255, 221)); else if (line.Type == ChangeType.Unchanged) fillColor = new SolidColorBrush(Colors.White); else if (line.Type == ChangeType.ModifiedNew) { if (currentFont.IsMonoSpaced) RenderDiffWords(grid, textBox, line, lineNumber); fillColor = new SolidColorBrush(Color.FromArgb(255, 221, 255, 221)); } else if (line.Type == ChangeType.ModifiedOld) { if (currentFont.IsMonoSpaced) RenderDiffWords(grid, textBox, line, lineNumber); fillColor = new SolidColorBrush(Color.FromArgb(255, 255, 221, 221)); } else if (line.Type == ChangeType.Imaginary) { fillColor = new SolidColorBrush(Color.FromArgb(255, 234, 242, 245)); AddImaginaryLine(textBox, lineNumber); } if (ShowVisualAids) { if (lineNumber % 2 == 0) fillColor = new SolidColorBrush(Colors.Cyan); else fillColor = new SolidColorBrush(Colors.Gray); } PlaceRectangleInGrid(textBox, grid, lineNumber, fillColor, 0, null); lineNumber++; } } private void RenderDiffWords(Grid grid, TextBox textBox, DiffPiece line, int lineNumber) { var charPos = 0; var characterWidth = CharacterWidthOverride ?? currentFont.CharacterWidth; var leftOffset = LeftOffsetOverride ?? currentFont.LeftOffset; foreach (var word in line.SubPieces) { SolidColorBrush fillColor; if (word.Type == ChangeType.Deleted) fillColor = new SolidColorBrush(Color.FromArgb(255, 255, 170, 170)); else if (word.Type == ChangeType.Inserted) fillColor = new SolidColorBrush(Color.FromArgb(255, 170, 255, 170)); else if (word.Type == ChangeType.Imaginary) continue; else fillColor = new SolidColorBrush(Colors.Transparent); var left = characterWidth * charPos + leftOffset; var wordWidth = characterWidth * word.Text.Length; PlaceRectangleInGrid(textBox, grid, lineNumber, fillColor, left, wordWidth); charPos += word.Text.Replace("\t", " ").Length; } } private void PlaceRectangleInGrid(TextBox textBox, Grid grid, int lineNumber, SolidColorBrush fillColor, double left, double? width) { var rectLineHeight = textBox.FontSize + (LinePaddingOverride ?? currentFont.LinePadding); double rectTopOffset = TopOffsetOverride ?? 3; var offset = rectLineHeight * lineNumber + rectTopOffset; var floor = Math.Floor(offset); var fraction = offset - floor; var rectangle = new Rectangle { Fill = fillColor, Width = width ?? Double.NaN, Height = rectLineHeight + fraction, VerticalAlignment = VerticalAlignment.Top, HorizontalAlignment = width.HasValue ? HorizontalAlignment.Left : HorizontalAlignment.Stretch, Margin = new Thickness(left, floor, 0, 0) }; grid.Children.Insert(0, rectangle); } private static void AddImaginaryLine(TextBox textBox, int lineNumber) { var selectionStart = textBox.SelectionStart; var lines = new List<string>(); if (!string.IsNullOrEmpty(textBox.Text)) { lines = textBox.Text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None).ToList(); var insertPosition = 0; for (var i = 0; i < lineNumber; i++) insertPosition += lines[i].Length + 1; if (selectionStart >= insertPosition) selectionStart += 2; } lines.Insert(lineNumber, ImaginaryLineCharacter.ToString()); textBox.Text = lines.Aggregate((x, y) => x + '\n' + y); textBox.SelectionStart = selectionStart; } private static void StripImaginaryLinesAndCharacters(TextBox textBox) { var selectionStart = textBox.SelectionStart; var offset = 0; for (var i = 0; i < textBox.Text.Length - 1 && i < selectionStart; i++) { if (i == 0 || textBox.Text[i] == '\n') { var nextNewLine = textBox.Text.IndexOf('\n', i + 1); var nextImaginary = textBox.Text.IndexOf(ImaginaryLineCharacter, i); if (nextImaginary != -1 && (nextNewLine == -1 || nextNewLine > nextImaginary) && nextImaginary < selectionStart) offset++; } } selectionStart -= offset; var lines = textBox.Text.Split('\n').Where(x => !x.Equals(ImaginaryLineCharacter.ToString())); var text = lines.Count() == 0 ? "" : lines.Aggregate((x, y) => x + '\n' + y); textBox.Text = text.Replace(ImaginaryLineCharacter.ToString(), ""); textBox.SelectionStart = selectionStart; } } }
// 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 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Relay { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for WCFRelaysOperations. /// </summary> public static partial class WCFRelaysOperationsExtensions { /// <summary> /// Lists the WCFRelays within the namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> public static IPage<WcfRelay> ListByNamespace(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName) { return operations.ListByNamespaceAsync(resourceGroupName, namespaceName).GetAwaiter().GetResult(); } /// <summary> /// Lists the WCFRelays within the namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<WcfRelay>> ListByNamespaceAsync(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByNamespaceWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or Updates a WCFRelay. This operation is idempotent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='parameters'> /// Parameters supplied to create a WCFRelays. /// </param> public static WcfRelay CreateOrUpdate(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, string relayName, WcfRelay parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, namespaceName, relayName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or Updates a WCFRelay. This operation is idempotent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='parameters'> /// Parameters supplied to create a WCFRelays. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<WcfRelay> CreateOrUpdateAsync(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, string relayName, WcfRelay parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, relayName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a WCFRelays . /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> public static void Delete(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, string relayName) { operations.DeleteAsync(resourceGroupName, namespaceName, relayName).GetAwaiter().GetResult(); } /// <summary> /// Deletes a WCFRelays . /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, string relayName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, relayName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Returns the description for the specified WCFRelays. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> public static WcfRelay Get(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, string relayName) { return operations.GetAsync(resourceGroupName, namespaceName, relayName).GetAwaiter().GetResult(); } /// <summary> /// Returns the description for the specified WCFRelays. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<WcfRelay> GetAsync(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, string relayName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, relayName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Authorization rules for a WCFRelays. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> public static IPage<AuthorizationRule> ListAuthorizationRules(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, string relayName) { return operations.ListAuthorizationRulesAsync(resourceGroupName, namespaceName, relayName).GetAwaiter().GetResult(); } /// <summary> /// Authorization rules for a WCFRelays. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<AuthorizationRule>> ListAuthorizationRulesAsync(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, string relayName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAuthorizationRulesWithHttpMessagesAsync(resourceGroupName, namespaceName, relayName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or Updates an authorization rule for a WCFRelays /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> /// <param name='parameters'> /// The authorization rule parameters. /// </param> public static AuthorizationRule CreateOrUpdateAuthorizationRule(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, string relayName, string authorizationRuleName, AuthorizationRule parameters) { return operations.CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, relayName, authorizationRuleName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or Updates an authorization rule for a WCFRelays /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> /// <param name='parameters'> /// The authorization rule parameters. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AuthorizationRule> CreateOrUpdateAuthorizationRuleAsync(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, string relayName, string authorizationRuleName, AuthorizationRule parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, relayName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a WCFRelays authorization rule /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> public static void DeleteAuthorizationRule(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, string relayName, string authorizationRuleName) { operations.DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, relayName, authorizationRuleName).GetAwaiter().GetResult(); } /// <summary> /// Deletes a WCFRelays authorization rule /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAuthorizationRuleAsync(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, string relayName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, relayName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get authorizationRule for a WCFRelays by name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> public static AuthorizationRule GetAuthorizationRule(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, string relayName, string authorizationRuleName) { return operations.GetAuthorizationRuleAsync(resourceGroupName, namespaceName, relayName, authorizationRuleName).GetAwaiter().GetResult(); } /// <summary> /// Get authorizationRule for a WCFRelays by name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AuthorizationRule> GetAuthorizationRuleAsync(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, string relayName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, relayName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Primary and Secondary ConnectionStrings to the WCFRelays. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> public static AccessKeys ListKeys(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, string relayName, string authorizationRuleName) { return operations.ListKeysAsync(resourceGroupName, namespaceName, relayName, authorizationRuleName).GetAwaiter().GetResult(); } /// <summary> /// Primary and Secondary ConnectionStrings to the WCFRelays. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AccessKeys> ListKeysAsync(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, string relayName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, relayName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Regenerates the Primary or Secondary ConnectionStrings to the WCFRelays /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate Auth Rule. /// </param> public static AccessKeys RegenerateKeys(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, string relayName, string authorizationRuleName, RegenerateAccessKeyParameters parameters) { return operations.RegenerateKeysAsync(resourceGroupName, namespaceName, relayName, authorizationRuleName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Regenerates the Primary or Secondary ConnectionStrings to the WCFRelays /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate Auth Rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AccessKeys> RegenerateKeysAsync(this IWCFRelaysOperations operations, string resourceGroupName, string namespaceName, string relayName, string authorizationRuleName, RegenerateAccessKeyParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RegenerateKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, relayName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the WCFRelays within the namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<WcfRelay> ListByNamespaceNext(this IWCFRelaysOperations operations, string nextPageLink) { return operations.ListByNamespaceNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists the WCFRelays within the namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<WcfRelay>> ListByNamespaceNextAsync(this IWCFRelaysOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByNamespaceNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Authorization rules for a WCFRelays. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<AuthorizationRule> ListAuthorizationRulesNext(this IWCFRelaysOperations operations, string nextPageLink) { return operations.ListAuthorizationRulesNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Authorization rules for a WCFRelays. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<AuthorizationRule>> ListAuthorizationRulesNextAsync(this IWCFRelaysOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAuthorizationRulesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Threading; namespace System.Linq.Expressions.Compiler { /// <summary> /// LambdaCompiler is responsible for compiling individual lambda (LambdaExpression). The complete tree may /// contain multiple lambdas, the Compiler class is responsible for compiling the whole tree, individual /// lambdas are then compiled by the LambdaCompiler. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] internal sealed partial class LambdaCompiler { private delegate void WriteBack(); // Information on the entire lambda tree currently being compiled private readonly AnalyzedTree _tree; private readonly ILGenerator _ilg; // The TypeBuilder backing this method, if any private readonly TypeBuilder _typeBuilder; private readonly MethodInfo _method; // Currently active LabelTargets and their mapping to IL labels private LabelScopeInfo _labelBlock = new LabelScopeInfo(null, LabelScopeKind.Lambda); // Mapping of labels used for "long" jumps (jumping out and into blocks) private readonly Dictionary<LabelTarget, LabelInfo> _labelInfo = new Dictionary<LabelTarget, LabelInfo>(); // The currently active variable scope private CompilerScope _scope; // The lambda we are compiling private readonly LambdaExpression _lambda; // True if the method's first argument is of type Closure private readonly bool _hasClosureArgument; // Runtime constants bound to the delegate private readonly BoundConstants _boundConstants; // Free list of locals, so we reuse them rather than creating new ones private readonly KeyedQueue<Type, LocalBuilder> _freeLocals = new KeyedQueue<Type, LocalBuilder>(); /// <summary> /// Creates a lambda compiler that will compile to a dynamic method /// </summary> private LambdaCompiler(AnalyzedTree tree, LambdaExpression lambda) { Type[] parameterTypes = GetParameterTypes(lambda).AddFirst(typeof(Closure)); var method = new DynamicMethod(lambda.Name ?? "lambda_method", lambda.ReturnType, parameterTypes, true); _tree = tree; _lambda = lambda; _method = method; // In a Win8 immersive process user code is not allowed to access non-W8P framework APIs through // reflection or RefEmit. Framework code, however, is given an exemption. // This is to make sure that user code cannot access non-W8P framework APIs via ExpressionTree. // TODO: This API is not available, is there an alternative way to achieve the same. // method.ProfileAPICheck = true; _ilg = method.GetILGenerator(); _hasClosureArgument = true; // These are populated by AnalyzeTree/VariableBinder _scope = tree.Scopes[lambda]; _boundConstants = tree.Constants[lambda]; InitializeMethod(); } /// <summary> /// Creates a lambda compiler that will compile into the provided MethodBuilder /// </summary> private LambdaCompiler(AnalyzedTree tree, LambdaExpression lambda, MethodBuilder method) { var scope = tree.Scopes[lambda]; var hasClosureArgument = scope.NeedsClosure; Type[] paramTypes = GetParameterTypes(lambda); if (hasClosureArgument) { paramTypes = paramTypes.AddFirst(typeof(Closure)); } method.SetReturnType(lambda.ReturnType); method.SetParameters(paramTypes); var paramNames = lambda.Parameters.Map(p => p.Name); // parameters are index from 1, with closure argument we need to skip the first arg int startIndex = hasClosureArgument ? 2 : 1; for (int i = 0; i < paramNames.Length; i++) { method.DefineParameter(i + startIndex, ParameterAttributes.None, paramNames[i]); } _tree = tree; _lambda = lambda; _typeBuilder = (TypeBuilder)method.DeclaringType.GetTypeInfo(); _method = method; _hasClosureArgument = hasClosureArgument; _ilg = method.GetILGenerator(); // These are populated by AnalyzeTree/VariableBinder _scope = scope; _boundConstants = tree.Constants[lambda]; InitializeMethod(); } /// <summary> /// Creates a lambda compiler for an inlined lambda /// </summary> private LambdaCompiler( LambdaCompiler parent, LambdaExpression lambda, InvocationExpression invocation) { _tree = parent._tree; _lambda = lambda; _method = parent._method; _ilg = parent._ilg; _hasClosureArgument = parent._hasClosureArgument; _typeBuilder = parent._typeBuilder; // inlined scopes are associated with invocation, not with the lambda _scope = _tree.Scopes[invocation]; _boundConstants = parent._boundConstants; } private void InitializeMethod() { // See if we can find a return label, so we can emit better IL AddReturnLabel(_lambda); _boundConstants.EmitCacheConstants(this); } public override string ToString() { return _method.ToString(); } internal ILGenerator IL { get { return _ilg; } } internal ReadOnlyCollection<ParameterExpression> Parameters { get { return _lambda.Parameters; } } internal bool CanEmitBoundConstants { get { return _method is DynamicMethod; } } #region Compiler entry points /// <summary> /// Compiler entry point /// </summary> /// <param name="lambda">LambdaExpression to compile.</param> /// <param name="debugInfoGenerator">Debug info generator.</param> /// <returns>The compiled delegate.</returns> internal static Delegate Compile(LambdaExpression lambda) { // 1. Bind lambda AnalyzedTree tree = AnalyzeLambda(ref lambda); // 2. Create lambda compiler LambdaCompiler c = new LambdaCompiler(tree, lambda); // 3. Emit c.EmitLambdaBody(); // 4. Return the delegate. return c.CreateDelegate(); } #endregion private static AnalyzedTree AnalyzeLambda(ref LambdaExpression lambda) { // Spill the stack for any exception handling blocks or other // constructs which require entering with an empty stack lambda = StackSpiller.AnalyzeLambda(lambda); // Bind any variable references in this lambda return VariableBinder.Bind(lambda); } internal LocalBuilder GetLocal(Type type) { Debug.Assert(type != null); LocalBuilder local; if (_freeLocals.TryDequeue(type, out local)) { Debug.Assert(type == local.LocalType); return local; } return _ilg.DeclareLocal(type); } internal void FreeLocal(LocalBuilder local) { if (local != null) { _freeLocals.Enqueue(local.LocalType, local); } } internal LocalBuilder GetNamedLocal(Type type, ParameterExpression variable) { Debug.Assert(type != null && variable != null); LocalBuilder lb = _ilg.DeclareLocal(type); return lb; } /// <summary> /// Gets the argument slot corresponding to the parameter at the given /// index. Assumes that the method takes a certain number of prefix /// arguments, followed by the real parameters stored in Parameters /// </summary> internal int GetLambdaArgument(int index) { return index + (_hasClosureArgument ? 1 : 0) + (_method.IsStatic ? 0 : 1); } /// <summary> /// Returns the index-th argument. This method provides access to the actual arguments /// defined on the lambda itself, and excludes the possible 0-th closure argument. /// </summary> internal void EmitLambdaArgument(int index) { _ilg.EmitLoadArg(GetLambdaArgument(index)); } internal void EmitClosureArgument() { Debug.Assert(_hasClosureArgument, "must have a Closure argument"); Debug.Assert(_method.IsStatic, "must be a static method"); _ilg.EmitLoadArg(0); } private Delegate CreateDelegate() { Debug.Assert(_method is DynamicMethod); return _method.CreateDelegate(_lambda.Type, new Closure(_boundConstants.ToArray(), null)); } private FieldBuilder CreateStaticField(string name, Type type) { // We are emitting into someone else's type. We don't want name // conflicts, so choose a long name that is unlikely to conflict. // Naming scheme chosen here is similar to what the C# compiler // uses. return _typeBuilder.DefineField("<ExpressionCompilerImplementationDetails>{" + Interlocked.Increment(ref s_counter) + "}" + name, type, FieldAttributes.Static | FieldAttributes.Private); } /// <summary> /// Creates an uninitialized field suitable for private implementation details /// Works with DynamicMethods or TypeBuilders. /// </summary> private MemberExpression CreateLazyInitializedField<T>(string name) { if (_method is DynamicMethod) { return Expression.Field(Expression.Constant(new StrongBox<T>(default(T))), "Value"); } else { return Expression.Field(null, CreateStaticField(name, typeof(T))); } } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Globalization; namespace ASC.Mail.Net.POP3.Client { #region usings using System; using System.Collections.Generic; using System.IO; using System.Security.Principal; using IO; using TCP; #endregion /// <summary> /// POP3 Client. Defined in RFC 1939. /// </summary> /// <example> /// <code> /// /// /* /// To make this code to work, you need to import following namespaces: /// using LumiSoft.Net.Mime; /// using LumiSoft.Net.POP3.Client; /// */ /// /// using(POP3_Client c = new POP3_Client()){ /// c.Connect("ivx",WellKnownPorts.POP3); /// c.Authenticate("test","test",true); /// /// // Get first message if there is any /// if(c.Messages.Count > 0){ /// // Do your suff /// /// // Parse message /// Mime m = Mime.Parse(c.Messages[0].MessageToByte()); /// string from = m.MainEntity.From; /// string subject = m.MainEntity.Subject; /// // ... /// } /// } /// </code> /// </example> public class POP3_Client : TCP_Client { #region Nested type: AuthenticateDelegate /// <summary> /// Internal helper method for asynchronous Authenticate method. /// </summary> private delegate void AuthenticateDelegate(string userName, string password, bool tryApop); #endregion #region Nested type: NoopDelegate /// <summary> /// Internal helper method for asynchronous Noop method. /// </summary> private delegate void NoopDelegate(); #endregion #region Nested type: ResetDelegate /// <summary> /// Internal helper method for asynchronous Reset method. /// </summary> private delegate void ResetDelegate(); #endregion #region Nested type: StartTLSDelegate /// <summary> /// Internal helper method for asynchronous StartTLS method. /// </summary> private delegate void StartTLSDelegate(); #endregion #region Members private readonly List<string> m_pExtCapabilities; private string m_ApopHashKey = ""; private string m_GreetingText = ""; private bool m_IsUidlSupported; private GenericIdentity m_pAuthdUserIdentity; private POP3_ClientMessageCollection m_pMessages; #endregion #region Properties /// <summary> /// Gets greeting text which was sent by POP3 server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and POP3 client is not connected.</exception> public string GreetingText { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } return m_GreetingText; } } /// <summary> /// Gets POP3 exteneded capabilities supported by POP3 server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and POP3 client is not connected.</exception> [Obsolete("USe ExtendedCapabilities instead !")] public string[] ExtenededCapabilities { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } return m_pExtCapabilities.ToArray(); } } /// <summary> /// Gets POP3 exteneded capabilities supported by POP3 server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and POP3 client is not connected.</exception> public string[] ExtendedCapabilities { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } return m_pExtCapabilities.ToArray(); } } /// <summary> /// Gets if POP3 server supports UIDL command. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and /// POP3 client is not connected and authenticated.</exception> public bool IsUidlSupported { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("You must authenticate first."); } return m_IsUidlSupported; } } /// <summary> /// Gets messages collection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and /// POP3 client is not connected and authenticated.</exception> public POP3_ClientMessageCollection Messages { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("You must authenticate first."); } return m_pMessages; } } /// <summary> /// Gets session authenticated user identity, returns null if not authenticated. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and POP3 client is not connected.</exception> public override GenericIdentity AuthenticatedUserIdentity { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } return m_pAuthdUserIdentity; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public POP3_Client(int default_login_delay) { m_pExtCapabilities = new List<string>(); this.default_login_delay = default_login_delay; AuthSucceed += OnAuthSucceed; } #endregion #region Methods /// <summary> /// Clean up any resources being used. /// </summary> public override void Dispose() { base.Dispose(); } /// <summary> /// Closes connection to POP3 server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected.</exception> public override void Disconnect() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("POP3 client is not connected."); } try { // Send QUIT command to server. WriteLine("QUIT"); } catch {} try { base.Disconnect(); } catch {} if (m_pMessages != null) { m_pMessages.Dispose(); m_pMessages = null; } m_ApopHashKey = ""; m_pExtCapabilities.Clear(); m_IsUidlSupported = false; } /// <summary> /// Starts switching to SSL. /// </summary> /// <returns>An IAsyncResult that references the asynchronous operation.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected or is authenticated or is already secure connection.</exception> public IAsyncResult BeginStartTLS(AsyncCallback callback, object state) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (IsAuthenticated) { throw new InvalidOperationException( "The STLS command is only valid in non-authenticated state."); } if (IsSecureConnection) { throw new InvalidOperationException("Connection is already secure."); } StartTLSDelegate asyncMethod = StartTLS; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous StartTLS request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 server returns error.</exception> public void EndStartTLS(IAsyncResult asyncResult) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginReset method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "BeginReset was previously called for the asynchronous connection."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is StartTLSDelegate) { ((StartTLSDelegate) castedAsyncResult.AsyncDelegate).EndInvoke(castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginReset method."); } } /// <summary> /// Switches POP3 connection to SSL. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected or is authenticated or is already secure connection.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 server returns error.</exception> public void StartTLS() { /* RFC 2595 4. POP3 STARTTLS extension. Arguments: none Restrictions: Only permitted in AUTHORIZATION state. Possible Responses: +OK -ERR Examples: C: STLS S: +OK Begin TLS negotiation <TLS negotiation, further commands are under TLS layer> ... C: STLS S: -ERR Command not permitted when TLS active */ if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (IsAuthenticated) { throw new InvalidOperationException( "The STLS command is only valid in non-authenticated state."); } if (IsSecureConnection) { throw new InvalidOperationException("Connection is already secure."); } WriteLine("STLS"); string line = ReadLine(); if (!line.ToUpper().StartsWith("+OK")) { throw new POP3_ClientException(line); } SwitchToSecure(); } /// <summary> /// Starts authentication. /// </summary> /// <param name="userName">User login name.</param> /// <param name="password">Password.</param> /// <param name="tryApop"> If true and POP3 server supports APOP, then APOP is used, otherwise normal login used.</param> /// <param name="callback">Callback to call when the asynchronous operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous operation.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected or is already authenticated.</exception> public IAsyncResult BeginAuthenticate(string userName, string password, bool tryApop, AsyncCallback callback, object state) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (IsAuthenticated) { throw new InvalidOperationException("Session is already authenticated."); } AuthenticateDelegate asyncMethod = Authenticate; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(userName, password, tryApop, asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous authentication request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 server returns error.</exception> public void EndAuthenticate(IAsyncResult asyncResult) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginAuthenticate method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "BeginAuthenticate was previously called for the asynchronous connection."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is AuthenticateDelegate) { ((AuthenticateDelegate) castedAsyncResult.AsyncDelegate).EndInvoke( castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginAuthenticate method."); } } public delegate void AuthSucceedDelegate(); public event AuthSucceedDelegate AuthSucceed; public delegate void AuthFailedDelegate(string response_line); public event AuthFailedDelegate AuthFailed; /// <summary> /// Authenticates user. /// </summary> /// <param name="userName">User login name.</param> /// <param name="password">Password.</param> /// <param name="tryApop"> If true and POP3 server supports APOP, then APOP is used, otherwise normal login used.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected or is already authenticated.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 server returns error.</exception> public void Authenticate(string userName, string password, bool tryApop) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (IsAuthenticated) { throw new InvalidOperationException("Session is already authenticated."); } // Supports APOP, use it. if (tryApop && m_ApopHashKey.Length > 0) { string hexHash = Core.ComputeMd5(m_ApopHashKey + password, true); int countWritten = TcpStream.WriteLine("APOP " + userName + " " + hexHash); LogAddWrite(countWritten, "APOP " + userName + " " + hexHash); string line = ReadLine(); if (line.StartsWith("+OK")) { m_pAuthdUserIdentity = new GenericIdentity(userName, "apop"); } else { if (AuthFailed != null) { AuthFailed.Invoke(line); } throw new POP3_ClientException(line); } } // Use normal LOGIN, don't support APOP. else { int countWritten = TcpStream.WriteLine("USER " + userName); LogAddWrite(countWritten, "USER " + userName); string line = ReadLine(); if (line.StartsWith("+OK")) { countWritten = TcpStream.WriteLine("PASS " + password); LogAddWrite(countWritten, "PASS <***REMOVED***>"); line = ReadLine(); if (line.StartsWith("+OK")) { m_pAuthdUserIdentity = new GenericIdentity(userName, "pop3-user/pass"); } else { if (AuthFailed != null) { AuthFailed.Invoke(line); } throw new POP3_ClientException(line); } } else { if (AuthFailed != null) { AuthFailed.Invoke(line); } throw new POP3_ClientException(line); } } if (IsAuthenticated) { if (AuthSucceed != null) { AuthSucceed.Invoke(); } FillMessages(); } } private void OnAuthSucceed() { if (need_precise_login_delay) { GetCAPA_Parameters(); LoginDelay = ObtainLoginDelay(default_login_delay); } } /// <summary> /// Starts sending NOOP command to server. This method can be used for keeping connection alive(not timing out). /// </summary> /// <param name="callback">Callback to call when the asynchronous operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous operation.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected.</exception> public IAsyncResult BeginNoop(AsyncCallback callback, object state) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } NoopDelegate asyncMethod = Noop; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous Noop request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 server returns error.</exception> public void EndNoop(IAsyncResult asyncResult) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginNoop method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "BeginNoop was previously called for the asynchronous connection."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is NoopDelegate) { ((NoopDelegate) castedAsyncResult.AsyncDelegate).EndInvoke(castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginNoop method."); } } /// <summary> /// Send NOOP command to server. This method can be used for keeping connection alive(not timing out). /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 server returns error.</exception> public void Noop() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The NOOP command is only valid in TRANSACTION state."); } /* RFC 1939 5 NOOP. Arguments: none Restrictions: may only be given in the TRANSACTION state Discussion: The POP3 server does nothing, it merely replies with a positive response. Possible Responses: +OK Examples: C: NOOP S: +OK */ WriteLine("NOOP"); string line = ReadLine(); if (!line.ToUpper().StartsWith("+OK")) { throw new POP3_ClientException(line); } } /// <summary> /// Starts resetting session. Messages marked for deletion will be unmarked. /// </summary> /// <param name="callback">Callback to call when the asynchronous operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous operation.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected and authenticated.</exception> public IAsyncResult BeginReset(AsyncCallback callback, object state) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The RSET command is only valid in authenticated state."); } ResetDelegate asyncMethod = Reset; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous reset request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 server returns error.</exception> public void EndReset(IAsyncResult asyncResult) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginReset method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "BeginReset was previously called for the asynchronous connection."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is ResetDelegate) { ((ResetDelegate) castedAsyncResult.AsyncDelegate).EndInvoke(castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginReset method."); } } /// <summary> /// Resets session. Messages marked for deletion will be unmarked. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected and authenticated.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 server returns error.</exception> public void Reset() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The RSET command is only valid in TRANSACTION state."); } /* RFC 1939 5. RSET. Arguments: none Restrictions: may only be given in the TRANSACTION state Discussion: If any messages have been marked as deleted by the POP3 server, they are unmarked. The POP3 server then replies with a positive response. Possible Responses: +OK Examples: C: RSET S: +OK maildrop has 2 messages (320 octets) */ WriteLine("RSET"); // Read first line of reply, check if it's ok. string line = ReadLine(); if (!line.StartsWith("+OK")) { throw new POP3_ClientException(line); } foreach (POP3_ClientMessage message in m_pMessages) { message.SetMarkedForDeletion(false); } } #endregion #region Overrides /// <summary> /// This method is called after TCP client has sucessfully connected. /// </summary> protected override void OnConnected() { // Read first line of reply, check if it's ok. string line = ReadLine(); if (line.ToUpper().StartsWith("+OK")) { m_GreetingText = line.Substring(3).Trim(); // Try to read APOP hash key, if supports APOP. if (line.IndexOf("<") > -1 && line.IndexOf(">") > -1) { m_ApopHashKey = line.Substring(line.IndexOf("<"), line.LastIndexOf(">") - line.IndexOf("<") + 1); } } else { throw new POP3_ClientException(line); } // Try to get POP3 server supported capabilities, if command not supported, just skip tat command. GetCAPA_Parameters(); LoginDelay = ObtainLoginDelay(default_login_delay); } private static int GetIntParam(string capa, int position /* 1-based */, int unspecifiedValue) { var capaParams = capa.Split(' '); if (capaParams.Length >= position) { int param; if (int.TryParse(capaParams[position-1], NumberStyles.Integer, CultureInfo.InvariantCulture, out param)) { return param; } } return unspecifiedValue; } public int LoginDelay { get; set; } private bool need_precise_login_delay = false; private int default_login_delay; #endregion #region Utility methods /// <summary> /// Fills messages info. /// </summary> private void FillMessages() { m_pMessages = new POP3_ClientMessageCollection(this); /* First make messages info, then try to add UIDL if server supports. */ /* NOTE: If reply is +OK, this is multiline respone and is terminated with '.'. Examples: C: LIST S: +OK 2 messages (320 octets) S: 1 120 S: 2 200 S: . ... C: LIST 3 S: -ERR no such message, only 2 messages in maildrop */ WriteLine("LIST"); // Read first line of reply, check if it's ok. string line = ReadLine(); if (!string.IsNullOrEmpty(line) && line.StartsWith("+OK")) { // Read lines while get only '.' on line itshelf. while (true) { line = ReadLine(); // End of data if (line.Trim() == ".") { break; } else { string[] no_size = line.Trim().Split(new[] {' '}); m_pMessages.Add(Convert.ToInt32(no_size[1])); } } } else { throw new POP3_ClientException(line); } // Try to fill messages UIDs. /* NOTE: If reply is +OK, this is multiline respone and is terminated with '.'. Examples: C: UIDL S: +OK S: 1 whqtswO00WBw418f9t5JxYwZ S: 2 QhdPYR:00WBw1Ph7x7 S: . ... C: UIDL 3 S: -ERR no such message */ WriteLine("UIDL"); // Read first line of reply, check if it's ok line = ReadLine(); if (line.StartsWith("+OK")) { m_IsUidlSupported = true; // Read lines while get only '.' on line itshelf. while (true) { line = ReadLine(); // End of data if (line.Trim() == ".") { break; } else { string[] no_uid = line.Trim().Split(new[] {' '}); m_pMessages[Convert.ToInt32(no_uid[0]) - 1].UIDL = no_uid[1]; } } } else { m_IsUidlSupported = false; } } /// <summary> /// Executes CAPA command and reads its parameters. /// /// RFC 2449 CAPA /// Arguments: /// none /// /// Restrictions: /// none /// /// Discussion: /// An -ERR response indicates the capability command is not /// implemented and the client will have to probe for /// capabilities as before. /// /// An +OK response is followed by a list of capabilities, one /// per line. Each capability name MAY be followed by a single /// space and a space-separated list of parameters. Each /// capability line is limited to 512 octets (including the /// CRLF). The capability list is terminated by a line /// containing a termination octet (".") and a CRLF pair. /// /// Possible Responses: /// +OK -ERR /// /// Examples: /// C: CAPA /// S: +OK Capability list follows /// S: TOP /// S: USER /// S: SASL CRAM-MD5 KERBEROS_V4 /// S: RESP-CODES /// S: LOGIN-DELAY 900 /// S: PIPELINING /// S: EXPIRE 60 /// S: UIDL /// S: IMPLEMENTATION Shlemazle-Plotz-v302 /// S: . /// /// Note: beware that parameters list may be different in authentication step and in transaction step /// </summary> private void GetCAPA_Parameters() { m_pExtCapabilities.Clear(); WriteLine("CAPA"); // CAPA command supported, read capabilities. if (ReadLine().ToUpper().StartsWith("+OK")) { string line; while ((line = ReadLine()) != ".") { m_pExtCapabilities.Add(line.ToUpper()); } } } /// <summary> /// Obtains LOOGIN-DELAY tag from CAPA parameters /// </summary> /// <returns>login delay read or 'default_value' if the parameter is absent</returns> private int ObtainLoginDelay(int default_value) { need_precise_login_delay = m_pExtCapabilities.Count != 0; foreach (string capa_line in m_pExtCapabilities) { if (capa_line.StartsWith("LOGIN-DELAY")) { string[] capaParams = capa_line.Split(' '); if (capaParams.Length > 1) { int delay; if (int.TryParse(capaParams[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out delay)) { need_precise_login_delay = capaParams.Length > 2 && capaParams[2].ToUpper() == "USER"; return delay; } } } } return default_value; } #endregion #region Internal methods /// <summary> /// Marks specified message for deletion. /// </summary> /// <param name="sequenceNumber">Message sequence number.</param> internal void MarkMessageForDeletion(int sequenceNumber) { WriteLine("DELE " + sequenceNumber); // Read first line of reply, check if it's ok. string line = ReadLine(); if (!line.StartsWith("+OK")) { throw new POP3_ClientException(line); } } /// <summary> /// Stores specified message to the specified stream. /// </summary> /// <param name="sequenceNumber">Message 1 based sequence number.</param> /// <param name="stream">Stream where to store message.</param> internal void GetMessage(int sequenceNumber, Stream stream) { WriteLine("RETR " + sequenceNumber); // Read first line of reply, check if it's ok. string line = ReadLine(); if (line.StartsWith("+OK")) { SmartStream.ReadPeriodTerminatedAsyncOP readTermOP = new SmartStream.ReadPeriodTerminatedAsyncOP(stream, 999999999, SizeExceededAction.ThrowException); TcpStream.ReadPeriodTerminated(readTermOP, false); if (readTermOP.Error != null) { throw readTermOP.Error; } LogAddWrite(readTermOP.BytesStored, readTermOP.BytesStored + " bytes read."); } else { throw new POP3_ClientException(line); } } /// <summary> /// Stores specified message header + specified lines of body to the specified stream. /// </summary> /// <param name="sequenceNumber">Message 1 based sequence number.</param> /// <param name="stream">Stream where to store data.</param> /// <param name="lineCount">Number of lines of message body to get.</param> internal void GetTopOfMessage(int sequenceNumber, Stream stream, int lineCount) { TcpStream.WriteLine("TOP " + sequenceNumber + " " + lineCount); // Read first line of reply, check if it's ok. string line = ReadLine(); if (line.StartsWith("+OK")) { SmartStream.ReadPeriodTerminatedAsyncOP readTermOP = new SmartStream.ReadPeriodTerminatedAsyncOP(stream, 999999999, SizeExceededAction.ThrowException); TcpStream.ReadPeriodTerminated(readTermOP, false); if (readTermOP.Error != null) { throw readTermOP.Error; } LogAddWrite(readTermOP.BytesStored, readTermOP.BytesStored + " bytes read."); } else { throw new POP3_ClientException(line); } } #endregion } }
/* * 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 * Contact: devcenter@docusign.com * 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; namespace DocuSign.eSign.Model { /// <summary> /// RecipientEmail /// </summary> [DataContract] public partial class RecipientEmail : IEquatable<RecipientEmail>, IValidatableObject { public RecipientEmail() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="RecipientEmail" /> class. /// </summary> /// <param name="AccountId">The account ID associated with the envelope..</param> /// <param name="AccountName">.</param> /// <param name="Email">.</param> /// <param name="EnvelopeId">The envelope ID of the envelope status that failed to post..</param> /// <param name="Name">.</param> /// <param name="RecipientId">Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document..</param> /// <param name="Supported">.</param> /// <param name="UserId">.</param> public RecipientEmail(string AccountId = default(string), string AccountName = default(string), string Email = default(string), string EnvelopeId = default(string), string Name = default(string), string RecipientId = default(string), bool? Supported = default(bool?), string UserId = default(string)) { this.AccountId = AccountId; this.AccountName = AccountName; this.Email = Email; this.EnvelopeId = EnvelopeId; this.Name = Name; this.RecipientId = RecipientId; this.Supported = Supported; this.UserId = UserId; } /// <summary> /// The account ID associated with the envelope. /// </summary> /// <value>The account ID associated with the envelope.</value> [DataMember(Name="accountId", EmitDefaultValue=false)] public string AccountId { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="accountName", EmitDefaultValue=false)] public string AccountName { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="email", EmitDefaultValue=false)] public string Email { get; set; } /// <summary> /// The envelope ID of the envelope status that failed to post. /// </summary> /// <value>The envelope ID of the envelope status that failed to post.</value> [DataMember(Name="envelopeId", EmitDefaultValue=false)] public string EnvelopeId { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document. /// </summary> /// <value>Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document.</value> [DataMember(Name="recipientId", EmitDefaultValue=false)] public string RecipientId { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="supported", EmitDefaultValue=false)] public bool? Supported { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="userId", EmitDefaultValue=false)] public string UserId { 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 RecipientEmail {\n"); sb.Append(" AccountId: ").Append(AccountId).Append("\n"); sb.Append(" AccountName: ").Append(AccountName).Append("\n"); sb.Append(" Email: ").Append(Email).Append("\n"); sb.Append(" EnvelopeId: ").Append(EnvelopeId).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" RecipientId: ").Append(RecipientId).Append("\n"); sb.Append(" Supported: ").Append(Supported).Append("\n"); sb.Append(" UserId: ").Append(UserId).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 RecipientEmail); } /// <summary> /// Returns true if RecipientEmail instances are equal /// </summary> /// <param name="other">Instance of RecipientEmail to be compared</param> /// <returns>Boolean</returns> public bool Equals(RecipientEmail other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.AccountId == other.AccountId || this.AccountId != null && this.AccountId.Equals(other.AccountId) ) && ( this.AccountName == other.AccountName || this.AccountName != null && this.AccountName.Equals(other.AccountName) ) && ( this.Email == other.Email || this.Email != null && this.Email.Equals(other.Email) ) && ( this.EnvelopeId == other.EnvelopeId || this.EnvelopeId != null && this.EnvelopeId.Equals(other.EnvelopeId) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.RecipientId == other.RecipientId || this.RecipientId != null && this.RecipientId.Equals(other.RecipientId) ) && ( this.Supported == other.Supported || this.Supported != null && this.Supported.Equals(other.Supported) ) && ( this.UserId == other.UserId || this.UserId != null && this.UserId.Equals(other.UserId) ); } /// <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.AccountId != null) hash = hash * 59 + this.AccountId.GetHashCode(); if (this.AccountName != null) hash = hash * 59 + this.AccountName.GetHashCode(); if (this.Email != null) hash = hash * 59 + this.Email.GetHashCode(); if (this.EnvelopeId != null) hash = hash * 59 + this.EnvelopeId.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.RecipientId != null) hash = hash * 59 + this.RecipientId.GetHashCode(); if (this.Supported != null) hash = hash * 59 + this.Supported.GetHashCode(); if (this.UserId != null) hash = hash * 59 + this.UserId.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
#region Copyright and License // Copyright 2010..2012 Alexander Reinert // // 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 using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading; namespace ARSoft.Tools.Net.Dns { public abstract class DnsClientBase { private readonly List<IPAddress> _servers; private readonly bool _isAnyServerMulticast; private readonly int _port; internal DnsClientBase(List<IPAddress> servers, int queryTimeout, int port) { _servers = servers.OrderBy(s => s.AddressFamily == AddressFamily.InterNetworkV6 ? 0 : 1).ToList(); _isAnyServerMulticast = servers.Any(s => s.IsMulticast()); QueryTimeout = queryTimeout; _port = port; } /// <summary> /// Milliseconds after which a query times out. /// </summary> public int QueryTimeout { get; private set; } /// <summary> /// Gets or set a value indicating whether the response is validated as described in <see /// cref="!:http://tools.ietf.org/id/draft-vixie-dnsext-dns0x20-00.txt">draft-vixie-dnsext-dns0x20-00</see> /// </summary> public bool IsResponseValidationEnabled { get; set; } /// <summary> /// Gets or set a value indicating whether the query labels are used for additional validation as described in <see /// cref="!:http://tools.ietf.org/id/draft-vixie-dnsext-dns0x20-00.txt">draft-vixie-dnsext-dns0x20-00</see> /// </summary> public bool Is0x20ValidationEnabled { get; set; } protected abstract int MaximumQueryMessageSize { get; } protected abstract bool AreMultipleResponsesAllowedInParallelMode { get; } protected TMessage SendMessage<TMessage>(TMessage message) where TMessage : DnsMessageBase, new() { int messageLength; byte[] messageData; DnsServer.SelectTsigKey tsigKeySelector; byte[] tsigOriginalMac; PrepareMessage(message, out messageLength, out messageData, out tsigKeySelector, out tsigOriginalMac); bool sendByTcp = ((messageLength > MaximumQueryMessageSize) || message.IsTcpUsingRequested); var endpointInfos = GetEndpointInfos<TMessage>(); for (int i = 0; i < endpointInfos.Count; i++) { TcpClient tcpClient = null; NetworkStream tcpStream = null; try { var endpointInfo = endpointInfos[i]; IPAddress responderAddress; byte[] resultData = sendByTcp ? QueryByTcp(endpointInfo.ServerAddress, messageData, messageLength, ref tcpClient, ref tcpStream, out responderAddress) : QueryByUdp(endpointInfo, messageData, messageLength, out responderAddress); if (resultData != null) { TMessage result = new TMessage(); try { result.Parse(resultData, false, tsigKeySelector, tsigOriginalMac); } catch (Exception e) { Trace.TraceError("Error on dns query: " + e); continue; } if (!ValidateResponse(message, result)) continue; if ((result.ReturnCode == ReturnCode.ServerFailure) && (i != endpointInfos.Count - 1)) { continue; } if (result.IsTcpResendingRequested) { resultData = QueryByTcp(responderAddress, messageData, messageLength, ref tcpClient, ref tcpStream, out responderAddress); if (resultData != null) { TMessage tcpResult = new TMessage(); try { tcpResult.Parse(resultData, false, tsigKeySelector, tsigOriginalMac); } catch (Exception e) { Trace.TraceError("Error on dns query: " + e); continue; } if (tcpResult.ReturnCode == ReturnCode.ServerFailure) { if (i != endpointInfos.Count - 1) { continue; } } else { result = tcpResult; } } } bool isTcpNextMessageWaiting = result.IsTcpNextMessageWaiting; bool isSucessfullFinished = true; while (isTcpNextMessageWaiting) { resultData = QueryByTcp(responderAddress, null, 0, ref tcpClient, ref tcpStream, out responderAddress); if (resultData != null) { TMessage tcpResult = new TMessage(); try { tcpResult.Parse(resultData, false, tsigKeySelector, tsigOriginalMac); } catch (Exception e) { Trace.TraceError("Error on dns query: " + e); isSucessfullFinished = false; break; } if (tcpResult.ReturnCode == ReturnCode.ServerFailure) { isSucessfullFinished = false; break; } else { result.AnswerRecords.AddRange(tcpResult.AnswerRecords); isTcpNextMessageWaiting = tcpResult.IsTcpNextMessageWaiting; } } else { isSucessfullFinished = false; break; } } if (isSucessfullFinished) return result; } } finally { try { if (tcpStream != null) tcpStream.Dispose(); if (tcpClient != null) tcpClient.Close(); } catch {} } } return null; } protected List<TMessage> SendMessageParallel<TMessage>(TMessage message) where TMessage : DnsMessageBase, new() { IAsyncResult ar = BeginSendMessageParallel(message, null, null); ar.AsyncWaitHandle.WaitOne(); return EndSendMessageParallel<TMessage>(ar); } private bool ValidateResponse<TMessage>(TMessage message, TMessage result) where TMessage : DnsMessageBase { if (IsResponseValidationEnabled) { if ((result.ReturnCode == ReturnCode.NoError) || (result.ReturnCode == ReturnCode.NxDomain)) { if (message.TransactionID != result.TransactionID) return false; if ((message.Questions == null) || (result.Questions == null)) return false; if ((message.Questions.Count != result.Questions.Count)) return false; for (int j = 0; j < message.Questions.Count; j++) { DnsQuestion queryQuestion = message.Questions[j]; DnsQuestion responseQuestion = message.Questions[j]; if ((queryQuestion.RecordClass != responseQuestion.RecordClass) || (queryQuestion.RecordType != responseQuestion.RecordType) || (queryQuestion.Name != responseQuestion.Name)) { return false; } } } } return true; } private void PrepareMessage<TMessage>(TMessage message, out int messageLength, out byte[] messageData, out DnsServer.SelectTsigKey tsigKeySelector, out byte[] tsigOriginalMac) where TMessage : DnsMessageBase, new() { if (message.TransactionID == 0) { message.TransactionID = (ushort) new Random().Next(0xffff); } if (Is0x20ValidationEnabled) { message.Questions.ForEach(q => q.Name = Add0x20Bits(q.Name)); } messageLength = message.Encode(false, out messageData); if (message.TSigOptions != null) { tsigKeySelector = (n, a) => message.TSigOptions.KeyData; tsigOriginalMac = message.TSigOptions.Mac; } else { tsigKeySelector = null; tsigOriginalMac = null; } } private static string Add0x20Bits(string name) { char[] res = new char[name.Length]; Random random = new Random(); for (int i = 0; i < name.Length; i++) { bool isLower = random.Next(0, 1000) > 500; char current = name[i]; if (!isLower && current >= 'A' && current <= 'Z') { current = (char) (current + 0x20); } else if (isLower && current >= 'a' && current <= 'z') { current = (char) (current - 0x20); } res[i] = current; } return new string(res); } private byte[] QueryByUdp(DnsClientEndpointInfo endpointInfo, byte[] messageData, int messageLength, out IPAddress responderAddress) { using (System.Net.Sockets.Socket udpClient = new System.Net.Sockets.Socket(endpointInfo.LocalAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp)) { try { udpClient.ReceiveTimeout = QueryTimeout; PrepareAndBindUdpSocket(endpointInfo, udpClient); EndPoint serverEndpoint = new IPEndPoint(endpointInfo.ServerAddress, _port); udpClient.SendTo(messageData, messageLength, SocketFlags.None, serverEndpoint); if (endpointInfo.IsMulticast) serverEndpoint = new IPEndPoint(udpClient.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, _port); byte[] buffer = new byte[65535]; int length = udpClient.ReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref serverEndpoint); responderAddress = ((IPEndPoint) serverEndpoint).Address; byte[] res = new byte[length]; Buffer.BlockCopy(buffer, 0, res, 0, length); return res; } catch (Exception e) { Trace.TraceError("Error on dns query: " + e); responderAddress = default(IPAddress); return null; } } } private void PrepareAndBindUdpSocket(DnsClientEndpointInfo endpointInfo, System.Net.Sockets.Socket udpClient) { if (endpointInfo.IsMulticast) { udpClient.Bind(new IPEndPoint(endpointInfo.LocalAddress, 0)); } else { udpClient.Connect(endpointInfo.ServerAddress, _port); } } private byte[] QueryByTcp(IPAddress nameServer, byte[] messageData, int messageLength, ref TcpClient tcpClient, ref NetworkStream tcpStream, out IPAddress responderAddress) { responderAddress = nameServer; IPEndPoint endPoint = new IPEndPoint(nameServer, _port); try { if (tcpClient == null) { tcpClient = new TcpClient(nameServer.AddressFamily) { ReceiveTimeout = QueryTimeout, SendTimeout = QueryTimeout }; tcpClient.Connect(endPoint); tcpStream = tcpClient.GetStream(); } int tmp = 0; byte[] lengthBuffer = new byte[2]; if (messageLength > 0) { DnsMessageBase.EncodeUShort(lengthBuffer, ref tmp, (ushort) messageLength); tcpStream.Write(lengthBuffer, 0, 2); tcpStream.Write(messageData, 0, messageLength); } lengthBuffer[0] = (byte) tcpStream.ReadByte(); lengthBuffer[1] = (byte) tcpStream.ReadByte(); tmp = 0; int length = DnsMessageBase.ParseUShort(lengthBuffer, ref tmp); byte[] resultData = new byte[length]; int readBytes = 0; while (readBytes < length) { readBytes += tcpStream.Read(resultData, readBytes, length - readBytes); } return resultData; } catch (Exception e) { Trace.TraceError("Error on dns query: " + e); return null; } } protected IAsyncResult BeginSendMessage<TMessage>(TMessage message, AsyncCallback requestCallback, object state) where TMessage : DnsMessageBase, new() { return BeginSendMessage(message, GetEndpointInfos<TMessage>(), requestCallback, state); } protected IAsyncResult BeginSendMessageParallel<TMessage>(TMessage message, AsyncCallback requestCallback, object state) where TMessage : DnsMessageBase, new() { List<DnsClientEndpointInfo> endpointInfos = GetEndpointInfos<TMessage>(); DnsClientParallelAsyncState<TMessage> asyncResult = new DnsClientParallelAsyncState<TMessage> { UserCallback = requestCallback, AsyncState = state, Responses = new List<TMessage>(), ResponsesToReceive = endpointInfos.Count }; foreach (var endpointInfo in endpointInfos) { DnsClientParallelState<TMessage> parallelState = new DnsClientParallelState<TMessage> { ParallelMessageAsyncState = asyncResult }; lock (parallelState.Lock) { parallelState.SingleMessageAsyncResult = BeginSendMessage(message, new List<DnsClientEndpointInfo> { endpointInfo }, SendMessageFinished<TMessage>, parallelState); } } return asyncResult; } private void SendMessageFinished<TMessage>(IAsyncResult ar) where TMessage : DnsMessageBase, new() { DnsClientParallelState<TMessage> state = (DnsClientParallelState<TMessage>) ar.AsyncState; List<TMessage> responses; lock (state.Lock) { responses = EndSendMessage<TMessage>(state.SingleMessageAsyncResult); } lock (state.ParallelMessageAsyncState.Responses) { state.ParallelMessageAsyncState.Responses.AddRange(responses); state.ParallelMessageAsyncState.ResponsesToReceive--; if (state.ParallelMessageAsyncState.ResponsesToReceive == 0) state.ParallelMessageAsyncState.SetCompleted(); } } private IAsyncResult BeginSendMessage<TMessage>(TMessage message, List<DnsClientEndpointInfo> endpointInfos, AsyncCallback requestCallback, object state) where TMessage : DnsMessageBase, new() { DnsClientAsyncState<TMessage> asyncResult = new DnsClientAsyncState<TMessage> { Query = message, Responses = new List<TMessage>(), UserCallback = requestCallback, AsyncState = state, EndpointInfoIndex = 0 }; PrepareMessage(message, out asyncResult.QueryLength, out asyncResult.QueryData, out asyncResult.TSigKeySelector, out asyncResult.TSigOriginalMac); asyncResult.EndpointInfos = endpointInfos; if ((asyncResult.QueryLength > MaximumQueryMessageSize) || message.IsTcpUsingRequested) { TcpBeginConnect(asyncResult); } else { UdpBeginSend(asyncResult); } return asyncResult; } private List<DnsClientEndpointInfo> GetEndpointInfos<TMessage>() where TMessage : DnsMessageBase, new() { List<DnsClientEndpointInfo> endpointInfos; if (_isAnyServerMulticast) { var localIPs = NetworkInterface.GetAllNetworkInterfaces() .Where(n => n.SupportsMulticast && (n.OperationalStatus == OperationalStatus.Up) && (n.NetworkInterfaceType != NetworkInterfaceType.Loopback)) .SelectMany(n => n.GetIPProperties().UnicastAddresses.Select(a => a.Address)) .Where(a => !IPAddress.IsLoopback(a) && ((a.AddressFamily == AddressFamily.InterNetwork) || a.IsIPv6LinkLocal)) .ToList(); endpointInfos = _servers .SelectMany( s => { if (s.IsMulticast()) { return localIPs .Where(l => l.AddressFamily == s.AddressFamily) .Select( l => new DnsClientEndpointInfo { IsMulticast = true, ServerAddress = s, LocalAddress = l }); } else { return new[] { new DnsClientEndpointInfo { IsMulticast = false, ServerAddress = s, LocalAddress = s.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any } }; } }).ToList(); } else { endpointInfos = _servers .Select( s => new DnsClientEndpointInfo { IsMulticast = false, ServerAddress = s, LocalAddress = s.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any } ).ToList(); } return endpointInfos; } protected List<TMessage> EndSendMessage<TMessage>(IAsyncResult ar) where TMessage : DnsMessageBase, new() { DnsClientAsyncState<TMessage> state = (DnsClientAsyncState<TMessage>) ar; return state.Responses; } protected List<TMessage> EndSendMessageParallel<TMessage>(IAsyncResult ar) where TMessage : DnsMessageBase, new() { DnsClientParallelAsyncState<TMessage> state = (DnsClientParallelAsyncState<TMessage>) ar; return state.Responses; } private void UdpBeginSend<TMessage>(DnsClientAsyncState<TMessage> state) where TMessage : DnsMessageBase, new() { if (state.EndpointInfoIndex == state.EndpointInfos.Count) { state.UdpClient = null; state.UdpEndpoint = null; state.SetCompleted(); return; } try { DnsClientEndpointInfo endpointInfo = state.EndpointInfos[state.EndpointInfoIndex]; state.UdpEndpoint = new IPEndPoint(endpointInfo.ServerAddress, _port); state.UdpClient = new System.Net.Sockets.Socket(state.UdpEndpoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp); PrepareAndBindUdpSocket(endpointInfo, state.UdpClient); state.TimedOut = false; state.TimeRemaining = QueryTimeout; IAsyncResult asyncResult = state.UdpClient.BeginSendTo(state.QueryData, 0, state.QueryLength, SocketFlags.None, state.UdpEndpoint, UdpSendCompleted<TMessage>, state); state.Timer = new Timer(UdpTimedOut<TMessage>, asyncResult, state.TimeRemaining, Timeout.Infinite); } catch (Exception e) { Trace.TraceError("Error on dns query: " + e); try { state.UdpClient.Close(); state.Timer.Dispose(); } catch {} state.EndpointInfoIndex++; UdpBeginSend(state); } } private static void UdpTimedOut<TMessage>(object ar) where TMessage : DnsMessageBase, new() { IAsyncResult asyncResult = (IAsyncResult) ar; if (!asyncResult.IsCompleted) { DnsClientAsyncState<TMessage> state = (DnsClientAsyncState<TMessage>) asyncResult.AsyncState; state.TimedOut = true; state.UdpClient.Close(); } } private void UdpSendCompleted<TMessage>(IAsyncResult ar) where TMessage : DnsMessageBase, new() { DnsClientAsyncState<TMessage> state = (DnsClientAsyncState<TMessage>) ar.AsyncState; if (state.Timer != null) state.Timer.Dispose(); if (state.TimedOut) { state.EndpointInfoIndex++; UdpBeginSend(state); } else { try { state.UdpClient.EndSendTo(ar); state.Buffer = new byte[65535]; if (state.EndpointInfos[state.EndpointInfoIndex].IsMulticast) state.UdpEndpoint = new IPEndPoint(state.UdpClient.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, _port); IAsyncResult asyncResult = state.UdpClient.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, ref state.UdpEndpoint, UdpReceiveCompleted<TMessage>, state); state.Timer = new Timer(UdpTimedOut<TMessage>, asyncResult, state.TimeRemaining, Timeout.Infinite); } catch (Exception e) { Trace.TraceError("Error on dns query: " + e); try { state.UdpClient.Close(); state.Timer.Dispose(); } catch {} state.EndpointInfoIndex++; UdpBeginSend(state); } } } private void UdpReceiveCompleted<TMessage>(IAsyncResult ar) where TMessage : DnsMessageBase, new() { DnsClientAsyncState<TMessage> state = (DnsClientAsyncState<TMessage>) ar.AsyncState; if (state.Timer != null) state.Timer.Dispose(); if (state.TimedOut) { state.EndpointInfoIndex++; UdpBeginSend(state); } else { try { int length = state.UdpClient.EndReceiveFrom(ar, ref state.UdpEndpoint); byte[] responseData = new byte[length]; Buffer.BlockCopy(state.Buffer, 0, responseData, 0, length); TMessage response = new TMessage(); response.Parse(responseData, false, state.TSigKeySelector, state.TSigOriginalMac); if (AreMultipleResponsesAllowedInParallelMode) { if (ValidateResponse(state.Query, response)) { if (response.IsTcpResendingRequested) { TcpBeginConnect<TMessage>(state.CreateTcpCloneWithoutCallback(), ((IPEndPoint) state.UdpEndpoint).Address); } else { state.Responses.Add(response); } } state.Buffer = new byte[65535]; if (state.EndpointInfos[state.EndpointInfoIndex].IsMulticast) state.UdpEndpoint = new IPEndPoint(state.UdpClient.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, _port); IAsyncResult asyncResult = state.UdpClient.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, ref state.UdpEndpoint, UdpReceiveCompleted<TMessage>, state); state.Timer = new Timer(UdpTimedOut<TMessage>, asyncResult, state.TimeRemaining, Timeout.Infinite); } else { state.UdpClient.Close(); state.UdpClient = null; state.UdpEndpoint = null; if (!ValidateResponse(state.Query, response) || (response.ReturnCode == ReturnCode.ServerFailure)) { state.EndpointInfoIndex++; UdpBeginSend(state); } else { if (response.IsTcpResendingRequested) { TcpBeginConnect<TMessage>(state, ((IPEndPoint) state.UdpEndpoint).Address); } else { state.Responses.Add(response); state.SetCompleted(); } } } } catch (Exception e) { Trace.TraceError("Error on dns query: " + e); try { state.UdpClient.Close(); state.Timer.Dispose(); } catch {} state.EndpointInfoIndex++; UdpBeginSend(state); } } } private void TcpBeginConnect<TMessage>(DnsClientAsyncState<TMessage> state) where TMessage : DnsMessageBase, new() { if (state.EndpointInfoIndex == state.EndpointInfos.Count) { state.TcpStream = null; state.TcpClient = null; state.SetCompleted(); return; } TcpBeginConnect(state, state.EndpointInfos[state.EndpointInfoIndex].ServerAddress); } private void TcpBeginConnect<TMessage>(DnsClientAsyncState<TMessage> state, IPAddress server) where TMessage : DnsMessageBase, new() { if (state.EndpointInfoIndex == state.EndpointInfos.Count) { state.TcpStream = null; state.TcpClient = null; state.SetCompleted(); return; } try { state.TcpClient = new TcpClient(server.AddressFamily); state.TimedOut = false; state.TimeRemaining = QueryTimeout; IAsyncResult asyncResult = state.TcpClient.BeginConnect(server, _port, TcpConnectCompleted<TMessage>, state); state.Timer = new Timer(TcpTimedOut<TMessage>, asyncResult, state.TimeRemaining, Timeout.Infinite); } catch (Exception e) { Trace.TraceError("Error on dns query: " + e); try { state.TcpClient.Close(); state.Timer.Dispose(); } catch {} state.EndpointInfoIndex++; TcpBeginConnect(state); } } private static void TcpTimedOut<TMessage>(object ar) where TMessage : DnsMessageBase, new() { IAsyncResult asyncResult = (IAsyncResult) ar; if (!asyncResult.IsCompleted) { DnsClientAsyncState<TMessage> state = (DnsClientAsyncState<TMessage>) asyncResult.AsyncState; state.PartialMessage = null; state.TimedOut = true; if (state.TcpStream != null) state.TcpStream.Close(); state.TcpClient.Close(); } } private void TcpConnectCompleted<TMessage>(IAsyncResult ar) where TMessage : DnsMessageBase, new() { DnsClientAsyncState<TMessage> state = (DnsClientAsyncState<TMessage>) ar.AsyncState; if (state.Timer != null) state.Timer.Dispose(); if (state.TimedOut) { state.EndpointInfoIndex++; TcpBeginConnect(state); } else { try { state.TcpClient.EndConnect(ar); state.TcpStream = state.TcpClient.GetStream(); int tmp = 0; state.Buffer = new byte[2]; DnsMessageBase.EncodeUShort(state.Buffer, ref tmp, (ushort) state.QueryLength); IAsyncResult asyncResult = state.TcpStream.BeginWrite(state.Buffer, 0, 2, TcpSendLengthCompleted<TMessage>, state); state.Timer = new Timer(TcpTimedOut<TMessage>, asyncResult, state.TimeRemaining, Timeout.Infinite); } catch (Exception e) { Trace.TraceError("Error on dns query: " + e); try { state.TcpClient.Close(); state.Timer.Dispose(); } catch {} state.EndpointInfoIndex++; TcpBeginConnect(state); } } } private void TcpSendLengthCompleted<TMessage>(IAsyncResult ar) where TMessage : DnsMessageBase, new() { DnsClientAsyncState<TMessage> state = (DnsClientAsyncState<TMessage>) ar.AsyncState; if (state.Timer != null) state.Timer.Dispose(); if (state.TimedOut) { state.EndpointInfoIndex++; TcpBeginConnect(state); } else { try { state.TcpStream.EndWrite(ar); IAsyncResult asyncResult = state.TcpStream.BeginWrite(state.QueryData, 0, state.QueryLength, TcpSendCompleted<TMessage>, state); state.Timer = new Timer(TcpTimedOut<TMessage>, asyncResult, state.TimeRemaining, Timeout.Infinite); } catch (Exception e) { Trace.TraceError("Error on dns query: " + e); try { state.TcpClient.Close(); state.Timer.Dispose(); } catch {} state.EndpointInfoIndex++; TcpBeginConnect(state); } } } private void TcpSendCompleted<TMessage>(IAsyncResult ar) where TMessage : DnsMessageBase, new() { DnsClientAsyncState<TMessage> state = (DnsClientAsyncState<TMessage>) ar.AsyncState; if (state.Timer != null) state.Timer.Dispose(); if (state.TimedOut) { state.EndpointInfoIndex++; TcpBeginConnect(state); } else { try { state.TcpStream.EndWrite(ar); state.TcpBytesToReceive = 2; IAsyncResult asyncResult = state.TcpStream.BeginRead(state.Buffer, 0, 2, TcpReceiveLengthCompleted<TMessage>, state); state.Timer = new Timer(TcpTimedOut<TMessage>, asyncResult, state.TimeRemaining, Timeout.Infinite); } catch (Exception e) { Trace.TraceError("Error on dns query: " + e); try { state.TcpClient.Close(); state.Timer.Dispose(); } catch {} state.EndpointInfoIndex++; TcpBeginConnect(state); } } } private void TcpReceiveLengthCompleted<TMessage>(IAsyncResult ar) where TMessage : DnsMessageBase, new() { DnsClientAsyncState<TMessage> state = (DnsClientAsyncState<TMessage>) ar.AsyncState; if (state.Timer != null) state.Timer.Dispose(); if (state.TimedOut) { state.EndpointInfoIndex++; TcpBeginConnect(state); } else { try { state.TcpBytesToReceive -= state.TcpStream.EndRead(ar); if (state.TcpBytesToReceive > 0) { IAsyncResult asyncResult = state.TcpStream.BeginRead(state.Buffer, 2 - state.TcpBytesToReceive, state.TcpBytesToReceive, TcpReceiveLengthCompleted<TMessage>, state); state.Timer = new Timer(TcpTimedOut<TMessage>, asyncResult, state.TimeRemaining, Timeout.Infinite); } else { int tmp = 0; int responseLength = DnsMessageBase.ParseUShort(state.Buffer, ref tmp); state.Buffer = new byte[responseLength]; state.TcpBytesToReceive = responseLength; IAsyncResult asyncResult = state.TcpStream.BeginRead(state.Buffer, 0, responseLength, TcpReceiveCompleted<TMessage>, state); state.Timer = new Timer(TcpTimedOut<TMessage>, asyncResult, state.TimeRemaining, Timeout.Infinite); } } catch (Exception e) { Trace.TraceError("Error on dns query: " + e); try { state.TcpClient.Close(); state.Timer.Dispose(); } catch {} state.EndpointInfoIndex++; TcpBeginConnect(state); } } } private void TcpReceiveCompleted<TMessage>(IAsyncResult ar) where TMessage : DnsMessageBase, new() { DnsClientAsyncState<TMessage> state = (DnsClientAsyncState<TMessage>) ar.AsyncState; if (state.Timer != null) state.Timer.Dispose(); if (state.TimedOut) { state.EndpointInfoIndex++; TcpBeginConnect(state); } else { try { state.TcpBytesToReceive -= state.TcpStream.EndRead(ar); if (state.TcpBytesToReceive > 0) { IAsyncResult asyncResult = state.TcpStream.BeginRead(state.Buffer, state.Buffer.Length - state.TcpBytesToReceive, state.TcpBytesToReceive, TcpReceiveCompleted<TMessage>, state); state.Timer = new Timer(TcpTimedOut<TMessage>, asyncResult, state.TimeRemaining, Timeout.Infinite); } else { byte[] buffer = state.Buffer; state.Buffer = null; TMessage response = new TMessage(); response.Parse(buffer, false, state.TSigKeySelector, state.TSigOriginalMac); if (!ValidateResponse(state.Query, response) || (response.ReturnCode == ReturnCode.ServerFailure)) { state.EndpointInfoIndex++; state.PartialMessage = null; state.TcpStream.Close(); state.TcpClient.Close(); state.TcpStream = null; state.TcpClient = null; TcpBeginConnect(state); } else { if (state.PartialMessage != null) { state.PartialMessage.AnswerRecords.AddRange(response.AnswerRecords); } else { state.PartialMessage = response; } if (response.IsTcpNextMessageWaiting) { state.TcpBytesToReceive = 2; state.Buffer = new byte[2]; IAsyncResult asyncResult = state.TcpStream.BeginRead(state.Buffer, 0, 2, TcpReceiveLengthCompleted<TMessage>, state); state.Timer = new Timer(TcpTimedOut<TMessage>, asyncResult, state.TimeRemaining, Timeout.Infinite); } else { state.TcpStream.Close(); state.TcpClient.Close(); state.TcpStream = null; state.TcpClient = null; state.Responses.Add(state.PartialMessage); state.SetCompleted(); } } } } catch (Exception e) { Trace.TraceError("Error on dns query: " + e); try { state.TcpClient.Close(); state.Timer.Dispose(); } catch {} state.EndpointInfoIndex++; TcpBeginConnect(state); } } } } }
// // (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.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Drawing; using System.Collections; using System.Drawing.Drawing2D; using Autodesk.Revit; using Autodesk.Revit.DB; using Autodesk.Revit.UI; namespace Revit.SDK.Samples.CurtainWallGrid.CS { /// <summary> /// manages the behaviors & operations of CurtainGrid /// </summary> public class GridGeometry { #region Fields // the document of this sample private MyDocument m_myDocument; // stores the curtain grid information of the created curtain wall private CurtainGrid m_activeGrid; // the referred drawing class for the curtain grid private GridDrawing m_drawing; //object which contains reference of Revit Application private ExternalCommandData m_commandData; // the active document of Revit private Document m_activeDocument; // store the mullion type used in this sample private MullionType m_mullionType; // all the grid lines of U direction (in CurtainGridLine format) private List<CurtainGridLine> m_uGridLines; // all the grid lines of V direction (in CurtainGridLine format) private List<CurtainGridLine> m_vGridLines; // stores all the vertexes of the curtain grid (in Autodesk.Revit.DB.XYZ format) private List<Autodesk.Revit.DB.XYZ> m_GridVertexesXYZ; // stores all the properties of the curtain grid private GridProperties m_gridProperties; // store the grid line to be removed private CurtainGridLine m_lineToBeMoved = null; // store the offset to be moved for the specified grid line private int m_moveOffset = 0; #endregion #region Properties /// <summary> /// stores the curtain grid information of the created curtain wall /// </summary> public CurtainGrid ActiveGrid { get { return m_activeGrid; } } /// <summary> /// the referred drawing class for the curtain grid /// </summary> public GridDrawing Drawing { get { return m_drawing; } } /// <summary> /// store the mullion type used in this sample /// </summary> public MullionType MullionType { get { return m_mullionType; } set { m_mullionType = value; } } /// <summary> /// all the grid lines of U direction (in CurtainGridLine format) /// </summary> public List<CurtainGridLine> UGridLines { get { return m_uGridLines; } } /// <summary> /// all the grid lines of V direction (in CurtainGridLine format) /// </summary> public List<CurtainGridLine> VGridLines { get { return m_vGridLines; } } /// <summary> /// stores all the vertexes of the curtain grid (in Autodesk.Revit.DB.XYZ format) /// </summary> public List<Autodesk.Revit.DB.XYZ> GridVertexesXYZ { get { return m_GridVertexesXYZ; } } /// <summary> /// stores all the properties of the curtain grid /// </summary> public GridProperties GridProperties { get { return m_gridProperties; } } public CurtainGridLine LineToBeMoved { get { return m_lineToBeMoved; } } /// <summary> /// store the offset to be moved for the specified grid line /// </summary> public int MoveOffset { get { return m_moveOffset; } set { m_moveOffset = value; } } #endregion #region Constructors /// <summary> /// constructor /// </summary> /// <param name="myDoc"> /// the document of the sample /// </param> public GridGeometry(MyDocument myDoc) { m_myDocument = myDoc; m_commandData = myDoc.CommandData; m_activeDocument = myDoc.Document; m_gridProperties = new GridProperties(); //m_activeGrid = grid; m_drawing = new GridDrawing(myDoc, this); m_uGridLines = new List<CurtainGridLine>(); m_vGridLines = new List<CurtainGridLine>(); m_GridVertexesXYZ = new List<Autodesk.Revit.DB.XYZ>(); } #endregion #region Public methods /// <summary> /// obtain all the properties of the curtain grid /// </summary> public void ReloadGridProperties() { if (null == m_activeGrid) { if (true == m_myDocument.WallCreated) { m_activeGrid = m_myDocument.CurtainWall.CurtainGrid; } else { return; } } // horizontal grid pattern Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString()); act.Start(); switch (m_activeGrid.Grid2Justification) { case CurtainGridAlignType.Beginning: m_gridProperties.HorizontalJustification = CurtainGridAlign.Beginning; break; case CurtainGridAlignType.Center: m_gridProperties.HorizontalJustification = CurtainGridAlign.Center; break; case CurtainGridAlignType.End: m_gridProperties.HorizontalJustification = CurtainGridAlign.End; break; default: break; } m_gridProperties.HorizontalAngle = m_activeGrid.Grid2Angle * 180.0 / Math.PI; m_gridProperties.HorizontalOffset = m_activeGrid.Grid2Offset; m_gridProperties.HorizontalLinesNumber = m_activeGrid.NumULines; // vertical grid pattern switch (m_activeGrid.Grid1Justification) { case CurtainGridAlignType.Beginning: m_gridProperties.VerticalJustification = CurtainGridAlign.Beginning; break; case CurtainGridAlignType.Center: m_gridProperties.VerticalJustification = CurtainGridAlign.Center; break; case CurtainGridAlignType.End: m_gridProperties.VerticalJustification = CurtainGridAlign.End; break; default: break; } m_gridProperties.VerticalAngle = m_activeGrid.Grid1Angle * 180.0 / Math.PI; m_gridProperties.VerticalOffset = m_activeGrid.Grid1Offset; m_gridProperties.VerticalLinesNumber = m_activeGrid.NumVLines; // other data m_gridProperties.PanelNumber = m_activeGrid.NumPanels; m_gridProperties.UnlockedPanelsNumber = m_activeGrid.UnlockedPanels.Size; m_gridProperties.CellNumber = m_activeGrid.Cells.Size; if (null != m_activeGrid.Mullions) { m_gridProperties.MullionsNumber = m_activeGrid.Mullions.Size; m_gridProperties.UnlockedmullionsNumber = m_activeGrid.UnlockedMullions.Size; } act.Commit(); } /// <summary> /// reload all the geometry data of the curtain grid (grid lines, vertexes, and convert them to 2D format) /// </summary> public void ReloadGeometryData() { if (null == m_activeGrid) { if (true == m_myDocument.WallCreated) { m_activeGrid = m_myDocument.CurtainWall.CurtainGrid; } else { return; } } Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString()); act.Start(); ElementSet mullions = m_activeGrid.Mullions; act.Commit(); if (null != mullions && false == mullions.IsEmpty) { foreach (Mullion mullion in mullions) { if (null != mullion) { m_mullionType = mullion.MullionType; break; } } } GetULines(); GetVLines(); GetCurtainGridVertexes(); // covert those lines to 2D format m_drawing.GetLines2D(); } /// <summary> /// remove the selected segment from the curtain grid /// </summary> public void RemoveSegment() { // verify that the mouse is inside the curtain grid area List<KeyValuePair<Line2D, Pen>> lines2D = m_drawing.DrawObject.Lines2D; if (lines2D.Count < 1) { return; } List<SegmentLine2D> toBeRemovedList = new List<SegmentLine2D>(); // check whether the deletion is valid bool canRemove = true; MimicRemoveSegments(ref canRemove, toBeRemovedList); // in the "MimicRemove" process, we didn't find that we need to "Remove the last segment of the grid line" // so the "Remove" action can go on if (true == canRemove) { try { Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString()); act.Start(); foreach (SegmentLine2D seg2D in toBeRemovedList) { int gridLineIndex = seg2D.GridLineIndex; int segIndex = seg2D.SegmentIndex; bool isUSegment = seg2D.IsUSegment; CurtainGridLine line; if (true == isUSegment) { line = m_uGridLines[gridLineIndex]; } else { line = m_vGridLines[gridLineIndex]; } Curve curve = line.AllSegmentCurves.get_Item(segIndex); line.RemoveSegment(curve); } act.Commit(); } catch (System.Exception e) { MessageBox.Show(e.Message); return; } } // in the "MimicRemove" process, we found that we would "Remove the last segment of the grid line" // so the whole "Remove" action will roll back else { foreach (SegmentLine2D seg2D in toBeRemovedList) { int gridLineIndex = seg2D.GridLineIndex; int segIndex = seg2D.SegmentIndex; bool isUSegment = seg2D.IsUSegment; GridLine2D gridLine2D; if (true == isUSegment) { gridLine2D = m_drawing.UGridLines2D[gridLineIndex]; } else { gridLine2D = m_drawing.VGridLines2D[gridLineIndex]; } gridLine2D.RemovedNumber--; SegmentLine2D segLine2D = gridLine2D.Segments[segIndex]; segLine2D.Removed = false; gridLine2D.Segments[segIndex] = segLine2D; } string statusMsg = "Delete this segment will make some grid lines have no existent segments."; m_myDocument.Message = new KeyValuePair<string, bool>(statusMsg, true); } this.ReloadGeometryData(); m_drawing.DrawObject.Clear(); } /// <summary> /// add a new segment to the specified location /// </summary> public void AddSegment() { // verify that the mouse is inside the curtain grid area List<KeyValuePair<Line2D, Pen>> lines2D = m_drawing.DrawObject.Lines2D; if (lines2D.Count < 1) { return; } // the selected segment location is on a U grid line if (-1 != m_drawing.SelectedUIndex) { CurtainGridLine line = m_uGridLines[m_drawing.SelectedUIndex]; Curve curve = line.AllSegmentCurves.get_Item(m_drawing.SelectedUSegmentIndex); if (null != line && null != curve) { try { Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString()); act.Start(); line.AddSegment(curve); act.Commit(); } catch (System.Exception e) { MessageBox.Show(e.Message); return; } } GridLine2D gridLine2D = m_drawing.UGridLines2D[m_drawing.SelectedUIndex]; gridLine2D.RemovedNumber--; SegmentLine2D segLine2D = gridLine2D.Segments[m_drawing.SelectedUSegmentIndex]; segLine2D.Removed = false; gridLine2D.Segments[m_drawing.SelectedUSegmentIndex] = segLine2D; } // the selected segment location is on a V grid line else if (-1 != m_drawing.SelectedVIndex) { CurtainGridLine line = m_vGridLines[m_drawing.SelectedVIndex]; Curve curve = line.AllSegmentCurves.get_Item(m_drawing.SelectedVSegmentIndex); if (null != line && null != curve) { try { Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString()); act.Start(); line.AddSegment(curve); act.Commit(); } catch (System.Exception e) { MessageBox.Show(e.Message); return; } } GridLine2D gridLine2D = m_drawing.VGridLines2D[m_drawing.SelectedVIndex]; gridLine2D.RemovedNumber--; SegmentLine2D segLine2D = gridLine2D.Segments[m_drawing.SelectedVSegmentIndex]; segLine2D.Removed = false; gridLine2D.Segments[m_drawing.SelectedVSegmentIndex] = segLine2D; } this.ReloadGeometryData(); m_drawing.DrawObject.Clear(); } /// <summary> /// add all the deleted segments back for a grid line /// </summary> public void AddAllSegments() { // verify that the mouse is inside the curtain grid area List<KeyValuePair<Line2D, Pen>> lines2D = m_drawing.DrawObject.Lines2D; if (lines2D.Count < 1) { return; } if (-1 != m_drawing.SelectedUIndex) { CurtainGridLine line = m_uGridLines[m_drawing.SelectedUIndex]; if (null != line) { try { Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString()); act.Start(); line.AddAllSegments(); act.Commit(); } catch (System.Exception e) { MessageBox.Show(e.Message); return; } } GridLine2D gridLine2D = m_drawing.UGridLines2D[m_drawing.SelectedUIndex]; gridLine2D.RemovedNumber = 0; foreach (SegmentLine2D segLine2D in gridLine2D.Segments) { segLine2D.Removed = false; } } else if (-1 != m_drawing.SelectedVIndex) { CurtainGridLine line = m_vGridLines[m_drawing.SelectedVIndex]; if (null != line) { try { Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString()); act.Start(); line.AddAllSegments(); act.Commit(); } catch (System.Exception e) { MessageBox.Show(e.Message); return; } } GridLine2D gridLine2D = m_drawing.VGridLines2D[m_drawing.SelectedVIndex]; gridLine2D.RemovedNumber = 0; foreach (SegmentLine2D segLine2D in gridLine2D.Segments) { segLine2D.Removed = false; } } this.ReloadGeometryData(); m_drawing.DrawObject.Clear(); } /// <summary> /// add a new U grid line to the specified location /// </summary> public void AddUGridLine() { // verify that the mouse location is valid: it's inside the curtain grid area // & it doesn't lap over another grid line (it's not allowed to add a grid line to lap over another one) if (false == m_drawing.MouseLocationValid) { return; } // all the assistant lines (in "Add U (Horizontal) Grid Line" operation, // there's only one dash line, this line indicates the location to be added) List<KeyValuePair<Line2D, Pen>> lines2D = m_drawing.DrawObject.Lines2D; if (lines2D.Count < 1) { return; } // the dash U line shown in the sample (incidates the location to be added) Line2D line2D = lines2D[0].Key; if (System.Drawing.Point.Empty == line2D.StartPoint || System.Drawing.Point.Empty == line2D.EndPoint) { return; } // get the point to be added int midX = (line2D.StartPoint.X + line2D.EndPoint.X) / 2; int midY = (line2D.StartPoint.Y + line2D.EndPoint.Y) / 2; // transform the 2D point to Autodesk.Revit.DB.XYZ format Autodesk.Revit.DB.XYZ pos = new Autodesk.Revit.DB.XYZ(midX, midY, 0); Vector4 vec = new Vector4(pos); vec = m_drawing.Coordinates.RestoreMatrix.Transform(vec); CurtainGridLine newLine; Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString()); act.Start(); try { newLine = ActiveGrid.AddGridLine(true, new Autodesk.Revit.DB.XYZ(vec.X, vec.Y, vec.Z), false); } catch (System.Exception e) { MessageBox.Show(e.Message); // "add U line" failed, so return directly return; } act.Commit(); // U line added, the V line's segment information changed, so reload all the geometry data this.ReloadGeometryData(); } /// <summary> /// add a new V grid line to the specified location /// </summary> public void AddVGridLine() { // verify that the mouse location is valid: it's inside the curtain grid area // & it doesn't lap over another grid line (it's not allowed to add a grid line to lap over another one) if (false == m_drawing.MouseLocationValid) { return; } // all the assistant lines (in "Add V (Vertical) Grid Line" operation, // there's only one dash line, this line indicates the location to be added) List<KeyValuePair<Line2D, Pen>> lines2D = m_drawing.DrawObject.Lines2D; if (lines2D.Count < 1) { return; } // the dash V line shown in the sample (incidates the location to be added) Line2D line2D = lines2D[0].Key; if (System.Drawing.Point.Empty == line2D.StartPoint || System.Drawing.Point.Empty == line2D.EndPoint) { return; } // get the point to be added int midX = (line2D.StartPoint.X + line2D.EndPoint.X) / 2; int midY = (line2D.StartPoint.Y + line2D.EndPoint.Y) / 2; // transform the 2D point to Autodesk.Revit.DB.XYZ format Autodesk.Revit.DB.XYZ pos = new Autodesk.Revit.DB.XYZ(midX, midY, 0); Vector4 vec = new Vector4(pos); vec = m_drawing.Coordinates.RestoreMatrix.Transform(vec); CurtainGridLine newLine; Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString()); act.Start(); try { newLine = ActiveGrid.AddGridLine(false, new Autodesk.Revit.DB.XYZ(vec.X, vec.Y, vec.Z), false); } catch (System.Exception e) { MessageBox.Show(e.Message); // "add V line" failed, so return directly return; } act.Commit(); // V line added, the U line's segment information changed, so reload all the geometry data this.ReloadGeometryData(); } /// <summary> /// toggle the selected grid line's Lock status: if it's locked, unlock it, vice versa /// </summary> public void LockOrUnlockSelectedGridLine() { CurtainGridLine line = null; GridLine2D line2D = new GridLine2D(); // get the selected grid line if (-1 != m_drawing.SelectedUIndex) { line = m_uGridLines[m_drawing.SelectedUIndex]; line2D = m_drawing.UGridLines2D[m_drawing.SelectedUIndex]; } else if (-1 != m_drawing.SelectedVIndex) { line = m_vGridLines[m_drawing.SelectedVIndex]; line2D = m_drawing.VGridLines2D[m_drawing.SelectedVIndex]; } else { return; } // lock/unlock the grid line if (null != line) { Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString()); act.Start(); line.Lock = !line.Lock; act.Commit(); } // update the mapped line2D's data line2D.Locked = line.Lock; // clear the intermediate variables and instances m_drawing.DrawObject.Clear(); } /// <summary> /// get the grid line to be removed /// </summary> /// <returns> /// if the line obtained, return true; otherwise false /// </returns> public bool GetLineToBeMoved() { if (-1 != m_drawing.SelectedUIndex) { m_lineToBeMoved = m_uGridLines[m_drawing.SelectedUIndex]; return true; } else if (-1 != m_drawing.SelectedVIndex) { m_lineToBeMoved = m_vGridLines[m_drawing.SelectedVIndex]; return true; } else { m_lineToBeMoved = null; return false; } } /// <summary> /// move the selected grid line to the location of the mouse cursor /// </summary> /// <param name="mousePosition"> /// indicates the destination position of the grid line /// </param> /// <returns> /// return whether the grid line be moved successfully /// </returns> public bool MoveGridLine(System.Drawing.Point mousePosition) { // verify that the mouse location is valid: it's inside the curtain grid area // & it doesn't lap over another grid line (it's not allowed to move a grid line to lap over another one) if (false == m_drawing.MouseLocationValid) { return false; } if (null == m_lineToBeMoved) { return false; } // move a U line along the V direction if (-1 != m_drawing.SelectedUIndex) { // convert the 2D data to 3D Autodesk.Revit.DB.XYZ xyz = new Autodesk.Revit.DB.XYZ(mousePosition.X, mousePosition.Y, 0); Vector4 vec = new Vector4(xyz); vec = m_drawing.Coordinates.RestoreMatrix.Transform(vec); double offset = vec.Z - m_lineToBeMoved.FullCurve.get_EndPoint(0).Z; xyz = new Autodesk.Revit.DB.XYZ(0, 0, offset); Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString()); act.Start(); try { m_lineToBeMoved.Move(xyz); } catch (System.Exception e) { MessageBox.Show(e.Message); return false; } act.Commit(); // update the grid line 2d GridLine2D line = m_drawing.UGridLines2D[m_drawing.SelectedUIndex]; line.StartPoint = new System.Drawing.Point(line.StartPoint.X, line.StartPoint.Y + m_moveOffset); line.EndPoint = new System.Drawing.Point(line.EndPoint.X, line.EndPoint.Y + m_moveOffset); // update the mapped grid line graphics path GraphicsPath path = new GraphicsPath(); path.AddLine(line.StartPoint, line.EndPoint); m_drawing.ULinePathList[m_drawing.SelectedUIndex] = path; // update the mapped segment line and its graphics path List<GraphicsPath> pathList = m_drawing.USegLinePathListList[m_drawing.SelectedUIndex]; List<SegmentLine2D> segLineList = line.Segments; for (int i = 0; i < segLineList.Count; i++) { // update the segment SegmentLine2D segLine2D = segLineList[i]; segLine2D.StartPoint = new System.Drawing.Point(segLine2D.StartPoint.X, segLine2D.StartPoint.Y + m_moveOffset); segLine2D.EndPoint = new System.Drawing.Point(segLine2D.EndPoint.X, segLine2D.EndPoint.Y + m_moveOffset); // update the segment's graphics path GraphicsPath gpath = new GraphicsPath(); path.AddLine(segLine2D.StartPoint, segLine2D.EndPoint); pathList[i] = gpath; } } // move a V line along the U direction else if (-1 != m_drawing.SelectedVIndex) { // convert the 2D data to 3D Autodesk.Revit.DB.XYZ xyz = new Autodesk.Revit.DB.XYZ(mousePosition.X, mousePosition.Y, 0); Vector4 vec = new Vector4(xyz); vec = m_drawing.Coordinates.RestoreMatrix.Transform(vec); double offset = vec.X - m_lineToBeMoved.FullCurve.get_EndPoint(0).X; xyz = new Autodesk.Revit.DB.XYZ(offset, 0, 0); Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString()); act.Start(); try { m_lineToBeMoved.Move(xyz); } catch (System.Exception e) { MessageBox.Show(e.Message); return false; } act.Commit(); // update the grid line 2d GridLine2D line = m_drawing.VGridLines2D[m_drawing.SelectedVIndex]; line.StartPoint = new System.Drawing.Point(line.StartPoint.X + m_moveOffset, line.StartPoint.Y); line.EndPoint = new System.Drawing.Point(line.EndPoint.X + m_moveOffset, line.EndPoint.Y); // update the mapped grid line graphics path GraphicsPath path = new GraphicsPath(); path.AddLine(line.StartPoint, line.EndPoint); m_drawing.VLinePathList[m_drawing.SelectedVIndex] = path; // update the mapped segment line and its graphics path List<GraphicsPath> pathList = m_drawing.VSegLinePathListList[m_drawing.SelectedVIndex]; List<SegmentLine2D> segLineList = line.Segments; for (int i = 0; i < segLineList.Count; i++) { // update the segment SegmentLine2D segLine2D = segLineList[i]; segLine2D.StartPoint = new System.Drawing.Point(segLine2D.StartPoint.X + m_moveOffset, segLine2D.StartPoint.Y); segLine2D.EndPoint = new System.Drawing.Point(segLine2D.EndPoint.X + m_moveOffset, segLine2D.EndPoint.Y); // update the segment's graphics path GraphicsPath gpath = new GraphicsPath(); path.AddLine(segLine2D.StartPoint, segLine2D.EndPoint); pathList[i] = gpath; } } // line moved, the segment information changed, so reload all the geometry data this.ReloadGeometryData(); m_drawing.DrawObject.Clear(); return true; } /// <summary> /// add mullions to all the segments of the curtain grid /// due to the limitations of Mullions, it's not available yet to add mullions to the /// edges of the curtain grid as Revit UI does /// </summary> public void AddAllMullions() { Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString()); act.Start(); try { // add mullions to all U grid lines foreach (CurtainGridLine line in m_uGridLines) { line.AddMullions(line.AllSegmentCurves.get_Item(0), m_mullionType, false); } // add mullions to all V grid lines foreach (CurtainGridLine line in m_vGridLines) { line.AddMullions(line.AllSegmentCurves.get_Item(0), m_mullionType, false); } } catch (System.Exception e) { MessageBox.Show(e.Message); return; } act.Commit(); } /// <summary> /// delete all the mullions of the curtain grid /// </summary> public void DeleteAllMullions() { Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString()); act.Start(); try { foreach (Mullion mullion in m_activeGrid.Mullions) { // Exceptions may jump out if attempting to delete "Locked" mullions if (true == mullion.Lockable && true == mullion.Lock) { mullion.Lock = false; } m_activeDocument.Delete(mullion); } } catch (System.Exception e) { MessageBox.Show(e.Message); return; } act.Commit(); } #endregion #region Private methods /// <summary> /// get all the U grid lines' data of the curtain grid /// </summary> private void GetULines() { m_uGridLines.Clear(); Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString()); act.Start(); ElementSet uLines = m_activeGrid.UGridLines; act.Commit(); if (true == uLines.IsEmpty || 0 == uLines.Size) { return; } foreach (CurtainGridLine line in uLines) { m_uGridLines.Add(line); } } /// <summary> /// get all the V grid lines' data of the curtain grid /// </summary> private void GetVLines() { m_vGridLines.Clear(); Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString()); act.Start(); ElementSet vLines = m_activeGrid.VGridLines; act.Commit(); if (true == vLines.IsEmpty || 0 == vLines.Size) { return; } foreach (CurtainGridLine line in vLines) { m_vGridLines.Add(line); } } /// <summary> /// get all of the 4 vertexes of the curtain grid /// </summary> /// <returns></returns> private bool GetCurtainGridVertexes() { // even in "ReloadGeometryData()" method, no need to reload the boundary information // (as the boundary of the curtain grid won't be changed in the sample) // just need to load it after the curtain wall been created if (null != m_GridVertexesXYZ && 0 < m_GridVertexesXYZ.Count) { return true; } // the curtain grid is from "Curtain Wall: Curtain Wall 1" (by default, the "Curtain Wall 1" has no U/V grid lines) if (m_uGridLines.Count <= 0 || m_vGridLines.Count <= 0) { // special handling for "Curtain Wall: Curtain Wall 1" // as the "Curtain Wall: Curtain Wall 1" has no U/V grid lines, so we can't compute the boundary from the grid lines // as that kind of curtain wall contains only one curtain cell // so we compute the boundary from the data of the curtain cell // Obtain the geometry information of the curtain wall // also works with some curtain grids with only U grid lines or only V grid lines Transaction act = new Transaction(m_activeDocument, Guid.NewGuid().GetHashCode().ToString()); act.Start(); CurtainCellSet cells = m_activeGrid.Cells; act.Commit(); Autodesk.Revit.DB.XYZ minXYZ = new Autodesk.Revit.DB.XYZ(Double.MaxValue, Double.MaxValue, Double.MaxValue); Autodesk.Revit.DB.XYZ maxXYZ = new Autodesk.Revit.DB.XYZ(Double.MinValue, Double.MinValue, Double.MinValue); GetVertexesByCells(cells, ref minXYZ, ref maxXYZ); // move the U & V lines to the boundary of the curtain grid, and get their end points as the vertexes of the curtain grid m_GridVertexesXYZ.Add(new Autodesk.Revit.DB.XYZ(minXYZ.X, minXYZ.Y, minXYZ.Z)); m_GridVertexesXYZ.Add(new Autodesk.Revit.DB.XYZ(maxXYZ.X, maxXYZ.Y, minXYZ.Z)); m_GridVertexesXYZ.Add(new Autodesk.Revit.DB.XYZ(maxXYZ.X, maxXYZ.Y, maxXYZ.Z)); m_GridVertexesXYZ.Add(new Autodesk.Revit.DB.XYZ(minXYZ.X, minXYZ.Y, maxXYZ.Z)); return true; } else { // handling for the other kinds of curtain walls (contains U&V grid lines by default) CurtainGridLine uLine = m_uGridLines[0]; CurtainGridLine vLine = m_vGridLines[0]; List<Autodesk.Revit.DB.XYZ> points = new List<Autodesk.Revit.DB.XYZ>(); Autodesk.Revit.DB.XYZ uStartPoint = uLine.FullCurve.get_EndPoint(0); Autodesk.Revit.DB.XYZ uEndPoint = uLine.FullCurve.get_EndPoint(1); Autodesk.Revit.DB.XYZ vStartPoint = vLine.FullCurve.get_EndPoint(0); Autodesk.Revit.DB.XYZ vEndPoint = vLine.FullCurve.get_EndPoint(1); points.Add(uStartPoint); points.Add(uEndPoint); points.Add(vStartPoint); points.Add(vEndPoint); //move the U & V lines to the boundary of the curtain grid, and get their end points as the vertexes of the curtain grid m_GridVertexesXYZ.Add(new Autodesk.Revit.DB.XYZ(uStartPoint.X, uStartPoint.Y, vStartPoint.Z)); m_GridVertexesXYZ.Add(new Autodesk.Revit.DB.XYZ(uEndPoint.X, uEndPoint.Y, vStartPoint.Z)); m_GridVertexesXYZ.Add(new Autodesk.Revit.DB.XYZ(uEndPoint.X, uEndPoint.Y, vEndPoint.Z)); m_GridVertexesXYZ.Add(new Autodesk.Revit.DB.XYZ(uStartPoint.X, uStartPoint.Y, vEndPoint.Z)); return true; } } /// <summary> /// get all the vertexes of the curtain cells /// </summary> /// <param name="cells"> /// the curtain cells which need to be got the vertexes /// </param> /// <returns> /// the vertexes of the curtain cells /// </returns> private List<Autodesk.Revit.DB.XYZ> GetPoints(CurtainCellSet cells) { List<Autodesk.Revit.DB.XYZ> points = new List<Autodesk.Revit.DB.XYZ>(); if (null == cells || true == cells.IsEmpty) { return points; } foreach (CurtainCell cell in cells) { if (null == cell || 0 == cell.CurveLoops.Size) { continue; } CurveArray curves = cell.CurveLoops.get_Item(0); foreach (Curve curve in curves) { points.Add(curve.get_EndPoint(0)); points.Add(curve.get_EndPoint(1)); } } return points; } /// <summary> /// get a bounding box which covers all the input points /// </summary> /// <param name="points"> /// the source points /// </param> /// <param name="minXYZ"> /// one of the bounding box points /// </param> /// <param name="maxXYZ"> /// one of the bounding box points /// </param> private void GetVertexesByPoints(List<Autodesk.Revit.DB.XYZ> points, ref Autodesk.Revit.DB.XYZ minXYZ, ref Autodesk.Revit.DB.XYZ maxXYZ) { if (null == points || 0 == points.Count) { return; } double minX = minXYZ.X; double minY = minXYZ.Y; double minZ = minXYZ.Z; double maxX = maxXYZ.X; double maxY = maxXYZ.Y; double maxZ = maxXYZ.Z; foreach (Autodesk.Revit.DB.XYZ xyz in points) { // compare the values and update the min and max value if (xyz.X < minX) { minX = xyz.X; minY = xyz.Y; } if (xyz.X > maxX) { maxX = xyz.X; maxY = xyz.Y; } if (xyz.Z < minZ) { minZ = xyz.Z; } if (xyz.Z > maxZ) { maxZ = xyz.Z; } } // end of loop minXYZ = new Autodesk.Revit.DB.XYZ(minX, minY, minZ); maxXYZ = new Autodesk.Revit.DB.XYZ(maxX, maxY, maxZ); } /// <summary> /// get the vertexes of the bounding box which covers all the curtain cells /// </summary> /// <param name="cells"> /// the source curtain cells /// </param> /// <param name="minXYZ"> /// the result bounding point /// </param> /// <param name="maxXYZ"> /// the result bounding point /// </param> private void GetVertexesByCells(CurtainCellSet cells, ref Autodesk.Revit.DB.XYZ minXYZ, ref Autodesk.Revit.DB.XYZ maxXYZ) { if (null == cells || true == cells.IsEmpty) { return; } List<Autodesk.Revit.DB.XYZ> points = GetPoints(cells); GetVertexesByPoints(points, ref minXYZ, ref maxXYZ); } /// <summary> /// a simulative "Delete Segment" operation before real deletion /// as we may occur some situations that prevent us to delete the specific segment /// for example, delete the specific segment will make some other segments to be deleted automatically (the "conjoint" ones) /// and the "automatically deleted" segment is the last segment of its parent grid line /// in this situation, we should prevent deleting that specific segment and rollback all the simulative deletion /// </summary> /// <param name="removeList"> /// the refferred to-be-removed list, in the simulative deletion operation, all the suitable (not the last segment) segments will /// be added to that list /// </param> private void MimicRemoveSegments(ref bool canRemove, List<SegmentLine2D> removeList) { // the currently operated is a U segment if (-1 != m_drawing.SelectedUIndex) { GridLine2D gridLine2D = m_drawing.UGridLines2D[m_drawing.SelectedUIndex]; SegmentLine2D segLine2D = gridLine2D.Segments[m_drawing.SelectedUSegmentIndex]; // the to-be-deleted segment is the last one of the grid line, it's not allowed to delete it int existingNumber = gridLine2D.Segments.Count - gridLine2D.RemovedNumber; if (1 == existingNumber) { canRemove = false; return; } // simulative deletion gridLine2D.RemovedNumber++; segLine2D.Removed = true; gridLine2D.Segments[m_drawing.SelectedUSegmentIndex] = segLine2D; removeList.Add(segLine2D); // the "regeneration" step: if there're only 2 segments existing in one joint and they're in the same line, delete one seg will cause the other // been deleted automatically MimicRecursiveDelete(ref canRemove, segLine2D, removeList); } // the currently operated is a V segment else if (-1 != m_drawing.SelectedVIndex) { GridLine2D gridLine2D = m_drawing.VGridLines2D[m_drawing.SelectedVIndex]; SegmentLine2D segLine2D = gridLine2D.Segments[m_drawing.SelectedVSegmentIndex]; int existingNumber = gridLine2D.Segments.Count - gridLine2D.RemovedNumber; // the to-be-deleted segment is the last one of the grid line, it's not allowed to delete it if (1 == existingNumber) { canRemove = false; return; } // simulative deletion gridLine2D.RemovedNumber++; segLine2D.Removed = true; gridLine2D.Segments[m_drawing.SelectedVSegmentIndex] = segLine2D; removeList.Add(segLine2D); // the "regeneration" step: if there're only 2 segments existing in one joint and they're in the same line, delete one seg will cause the other // been deleted automatically MimicRecursiveDelete(ref canRemove, segLine2D, removeList); } } /// <summary> /// the "regeneration" step: if there're only 2 segments existing in one joint and they're in the same line, /// delete one seg will cause the other been deleted automatically /// </summary> /// <param name="segLine2D"> /// the to-be-automatically-deleted segment /// </param> /// <param name="removeList"> /// the referred to-be-deleted list of the segments /// </param> /// <returns> /// returns the operation result: if there's no "last" segment in the deletion operation, return true; otherwise false /// </returns> private void MimicRecursiveDelete(ref bool canRemove, SegmentLine2D segLine2D, List<SegmentLine2D> removeList) { // the "regeneration" step: if there're only 2 segments existing in one joint // and they're in the same line, delete one seg will cause the other // been deleted automatically // get conjoint U line segments List<SegmentLine2D> removeSegments = new List<SegmentLine2D>(); m_drawing.GetConjointSegments(segLine2D, removeSegments); // there's no isolated segment need to be removed automatically if (null == removeSegments || 0 == removeSegments.Count) { // didn't "remove last segment of the curtain grid line", all the operations are valid. so return true return; } // there're conjoint segments need to be removed automatically // add the segments to removeList first, and compute whether other segments need to be // removed automatically because of the deletion of this newly removed segment if (true == segLine2D.Removed) { foreach (SegmentLine2D seg in removeSegments) { MimicRemoveSegment(ref canRemove, seg, removeList); if (false == canRemove) { return; } // recursive calling MimicRecursiveDelete(ref canRemove, seg, removeList); } } } /// <summary> /// remove the segment from the grid line /// </summary> /// <param name="canRemove"> /// the returned result value, indicates whether the segment can be removed (is NOT the last segment) /// </param> /// <param name="seg"> /// the to-be-removed segment /// </param> /// <param name="removeList"> /// the referred to-be-deleted list of the segments /// </param> private void MimicRemoveSegment(ref bool canRemove, SegmentLine2D seg, List<SegmentLine2D> removeList) { int gridLineIndex = seg.GridLineIndex; int segIndex = seg.SegmentIndex; if (-1 != gridLineIndex && -1 != segIndex) { // update the gridline2d and segmentline2d data GridLine2D grid; if (true == seg.IsUSegment) { grid = m_drawing.UGridLines2D[gridLineIndex]; } else { grid = m_drawing.VGridLines2D[gridLineIndex]; } // the last segment of the grid line int existingNumber = grid.Segments.Count - grid.RemovedNumber; if (1 == existingNumber) { canRemove = false; return; } grid.RemovedNumber++; SegmentLine2D seg2D = grid.Segments[segIndex]; seg2D.Removed = true; grid.Segments[segIndex] = seg2D; removeList.Add(seg2D); } } #endregion }// end of class }
// 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 RegexWriter class is internal to the Regex package. // It builds a block of regular expression codes (RegexCode) // from a RegexTree parse tree. // Implementation notes: // // This step is as simple as walking the tree and emitting // sequences of codes. // using System.Collections; using System.Collections.Generic; using System.Globalization; namespace System.Text.RegularExpressions { internal ref struct RegexWriter { private const int BeforeChild = 64; private const int AfterChild = 128; // Distribution of common patterns indicates an average amount of 56 op codes. private const int EmittedSize = 56; private const int IntStackSize = 32; private ValueListBuilder<int> _emitted; private ValueListBuilder<int> _intStack; private readonly Dictionary<string, int> _stringHash; private readonly List<string> _stringTable; private Hashtable _caps; private int _trackCount; private RegexWriter(Span<int> emittedSpan, Span<int> intStackSpan) { _emitted = new ValueListBuilder<int>(emittedSpan); _intStack = new ValueListBuilder<int>(intStackSpan); _stringHash = new Dictionary<string, int>(); _stringTable = new List<string>(); _caps = null; _trackCount = 0; } /// <summary> /// This is the only function that should be called from outside. /// It takes a RegexTree and creates a corresponding RegexCode. /// </summary> public static RegexCode Write(RegexTree tree) { Span<int> emittedSpan = stackalloc int[EmittedSize]; Span<int> intStackSpan = stackalloc int[IntStackSize]; var writer = new RegexWriter(emittedSpan, intStackSpan); RegexCode code = writer.RegexCodeFromRegexTree(tree); writer.Dispose(); #if DEBUG if (tree.Debug) { tree.Dump(); code.Dump(); } #endif return code; } /// <summary> /// Return rented buffers. /// </summary> public void Dispose() { _emitted.Dispose(); _intStack.Dispose(); } /// <summary> /// The top level RegexCode generator. It does a depth-first walk /// through the tree and calls EmitFragment to emits code before /// and after each child of an interior node, and at each leaf. /// </summary> public RegexCode RegexCodeFromRegexTree(RegexTree tree) { // construct sparse capnum mapping if some numbers are unused int capsize; if (tree.CapNumList == null || tree.CapTop == tree.CapNumList.Length) { capsize = tree.CapTop; _caps = null; } else { capsize = tree.CapNumList.Length; _caps = tree.Caps; for (int i = 0; i < tree.CapNumList.Length; i++) _caps[tree.CapNumList[i]] = i; } RegexNode curNode = tree.Root; int curChild = 0; Emit(RegexCode.Lazybranch, 0); while (true) { if (curNode.Children == null) { EmitFragment(curNode.NType, curNode, 0); } else if (curChild < curNode.Children.Count) { EmitFragment(curNode.NType | BeforeChild, curNode, curChild); curNode = curNode.Children[curChild]; _intStack.Append(curChild); curChild = 0; continue; } if (_intStack.Length == 0) break; curChild = _intStack.Pop(); curNode = curNode.Next; EmitFragment(curNode.NType | AfterChild, curNode, curChild); curChild++; } PatchJump(0, _emitted.Length); Emit(RegexCode.Stop); RegexPrefix? fcPrefix = RegexFCD.FirstChars(tree); RegexPrefix prefix = RegexFCD.Prefix(tree); bool rtl = ((tree.Options & RegexOptions.RightToLeft) != 0); CultureInfo culture = (tree.Options & RegexOptions.CultureInvariant) != 0 ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture; RegexBoyerMoore bmPrefix; if (prefix.Prefix.Length > 0) bmPrefix = new RegexBoyerMoore(prefix.Prefix, prefix.CaseInsensitive, rtl, culture); else bmPrefix = null; int anchors = RegexFCD.Anchors(tree); int[] emitted = _emitted.AsSpan().ToArray(); return new RegexCode(emitted, _stringTable, _trackCount, _caps, capsize, bmPrefix, fcPrefix, anchors, rtl); } /// <summary> /// Fixes up a jump instruction at the specified offset /// so that it jumps to the specified jumpDest. /// </summary> private void PatchJump(int offset, int jumpDest) { _emitted[offset + 1] = jumpDest; } /// <summary> /// Emits a zero-argument operation. Note that the emit /// functions all run in two modes: they can emit code, or /// they can just count the size of the code. /// </summary> private void Emit(int op) { if (RegexCode.OpcodeBacktracks(op)) _trackCount++; _emitted.Append(op); } /// <summary> /// Emits a one-argument operation. /// </summary> private void Emit(int op, int opd1) { if (RegexCode.OpcodeBacktracks(op)) _trackCount++; _emitted.Append(op); _emitted.Append(opd1); } /// <summary> /// Emits a two-argument operation. /// </summary> private void Emit(int op, int opd1, int opd2) { if (RegexCode.OpcodeBacktracks(op)) _trackCount++; _emitted.Append(op); _emitted.Append(opd1); _emitted.Append(opd2); } /// <summary> /// Returns an index in the string table for a string; /// uses a hashtable to eliminate duplicates. /// </summary> private int StringCode(string str) { if (str == null) str = string.Empty; int i; if (!_stringHash.TryGetValue(str, out i)) { i = _stringTable.Count; _stringHash[str] = i; _stringTable.Add(str); } return i; } /// <summary> /// When generating code on a regex that uses a sparse set /// of capture slots, we hash them to a dense set of indices /// for an array of capture slots. Instead of doing the hash /// at match time, it's done at compile time, here. /// </summary> private int MapCapnum(int capnum) { if (capnum == -1) return -1; if (_caps != null) return (int)_caps[capnum]; else return capnum; } /// <summary> /// The main RegexCode generator. It does a depth-first walk /// through the tree and calls EmitFragment to emits code before /// and after each child of an interior node, and at each leaf. /// </summary> private void EmitFragment(int nodetype, RegexNode node, int curIndex) { int bits = 0; if (nodetype <= RegexNode.Ref) { if (node.UseOptionR()) bits |= RegexCode.Rtl; if ((node.Options & RegexOptions.IgnoreCase) != 0) bits |= RegexCode.Ci; } switch (nodetype) { case RegexNode.Concatenate | BeforeChild: case RegexNode.Concatenate | AfterChild: case RegexNode.Empty: break; case RegexNode.Alternate | BeforeChild: if (curIndex < node.Children.Count - 1) { _intStack.Append(_emitted.Length); Emit(RegexCode.Lazybranch, 0); } break; case RegexNode.Alternate | AfterChild: { if (curIndex < node.Children.Count - 1) { int LBPos = _intStack.Pop(); _intStack.Append(_emitted.Length); Emit(RegexCode.Goto, 0); PatchJump(LBPos, _emitted.Length); } else { int I; for (I = 0; I < curIndex; I++) { PatchJump(_intStack.Pop(), _emitted.Length); } } break; } case RegexNode.Testref | BeforeChild: switch (curIndex) { case 0: Emit(RegexCode.Setjump); _intStack.Append(_emitted.Length); Emit(RegexCode.Lazybranch, 0); Emit(RegexCode.Testref, MapCapnum(node.M)); Emit(RegexCode.Forejump); break; } break; case RegexNode.Testref | AfterChild: switch (curIndex) { case 0: { int Branchpos = _intStack.Pop(); _intStack.Append(_emitted.Length); Emit(RegexCode.Goto, 0); PatchJump(Branchpos, _emitted.Length); Emit(RegexCode.Forejump); if (node.Children.Count > 1) break; // else fallthrough goto case 1; } case 1: PatchJump(_intStack.Pop(), _emitted.Length); break; } break; case RegexNode.Testgroup | BeforeChild: switch (curIndex) { case 0: Emit(RegexCode.Setjump); Emit(RegexCode.Setmark); _intStack.Append(_emitted.Length); Emit(RegexCode.Lazybranch, 0); break; } break; case RegexNode.Testgroup | AfterChild: switch (curIndex) { case 0: Emit(RegexCode.Getmark); Emit(RegexCode.Forejump); break; case 1: int Branchpos = _intStack.Pop(); _intStack.Append(_emitted.Length); Emit(RegexCode.Goto, 0); PatchJump(Branchpos, _emitted.Length); Emit(RegexCode.Getmark); Emit(RegexCode.Forejump); if (node.Children.Count > 2) break; // else fallthrough goto case 2; case 2: PatchJump(_intStack.Pop(), _emitted.Length); break; } break; case RegexNode.Loop | BeforeChild: case RegexNode.Lazyloop | BeforeChild: if (node.N < int.MaxValue || node.M > 1) Emit(node.M == 0 ? RegexCode.Nullcount : RegexCode.Setcount, node.M == 0 ? 0 : 1 - node.M); else Emit(node.M == 0 ? RegexCode.Nullmark : RegexCode.Setmark); if (node.M == 0) { _intStack.Append(_emitted.Length); Emit(RegexCode.Goto, 0); } _intStack.Append(_emitted.Length); break; case RegexNode.Loop | AfterChild: case RegexNode.Lazyloop | AfterChild: { int StartJumpPos = _emitted.Length; int Lazy = (nodetype - (RegexNode.Loop | AfterChild)); if (node.N < int.MaxValue || node.M > 1) Emit(RegexCode.Branchcount + Lazy, _intStack.Pop(), node.N == int.MaxValue ? int.MaxValue : node.N - node.M); else Emit(RegexCode.Branchmark + Lazy, _intStack.Pop()); if (node.M == 0) PatchJump(_intStack.Pop(), StartJumpPos); } break; case RegexNode.Group | BeforeChild: case RegexNode.Group | AfterChild: break; case RegexNode.Capture | BeforeChild: Emit(RegexCode.Setmark); break; case RegexNode.Capture | AfterChild: Emit(RegexCode.Capturemark, MapCapnum(node.M), MapCapnum(node.N)); break; case RegexNode.Require | BeforeChild: // NOTE: the following line causes lookahead/lookbehind to be // NON-BACKTRACKING. It can be commented out with (*) Emit(RegexCode.Setjump); Emit(RegexCode.Setmark); break; case RegexNode.Require | AfterChild: Emit(RegexCode.Getmark); // NOTE: the following line causes lookahead/lookbehind to be // NON-BACKTRACKING. It can be commented out with (*) Emit(RegexCode.Forejump); break; case RegexNode.Prevent | BeforeChild: Emit(RegexCode.Setjump); _intStack.Append(_emitted.Length); Emit(RegexCode.Lazybranch, 0); break; case RegexNode.Prevent | AfterChild: Emit(RegexCode.Backjump); PatchJump(_intStack.Pop(), _emitted.Length); Emit(RegexCode.Forejump); break; case RegexNode.Greedy | BeforeChild: Emit(RegexCode.Setjump); break; case RegexNode.Greedy | AfterChild: Emit(RegexCode.Forejump); break; case RegexNode.One: case RegexNode.Notone: Emit(node.NType | bits, node.Ch); break; case RegexNode.Notoneloop: case RegexNode.Notonelazy: case RegexNode.Oneloop: case RegexNode.Onelazy: if (node.M > 0) Emit(((node.NType == RegexNode.Oneloop || node.NType == RegexNode.Onelazy) ? RegexCode.Onerep : RegexCode.Notonerep) | bits, node.Ch, node.M); if (node.N > node.M) Emit(node.NType | bits, node.Ch, node.N == int.MaxValue ? int.MaxValue : node.N - node.M); break; case RegexNode.Setloop: case RegexNode.Setlazy: if (node.M > 0) Emit(RegexCode.Setrep | bits, StringCode(node.Str), node.M); if (node.N > node.M) Emit(node.NType | bits, StringCode(node.Str), (node.N == int.MaxValue) ? int.MaxValue : node.N - node.M); break; case RegexNode.Multi: Emit(node.NType | bits, StringCode(node.Str)); break; case RegexNode.Set: Emit(node.NType | bits, StringCode(node.Str)); break; case RegexNode.Ref: Emit(node.NType | bits, MapCapnum(node.M)); break; case RegexNode.Nothing: case RegexNode.Bol: case RegexNode.Eol: case RegexNode.Boundary: case RegexNode.Nonboundary: case RegexNode.ECMABoundary: case RegexNode.NonECMABoundary: case RegexNode.Beginning: case RegexNode.Start: case RegexNode.EndZ: case RegexNode.End: Emit(node.NType); break; default: throw new ArgumentException(SR.Format(SR.UnexpectedOpcode, nodetype.ToString())); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * 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; using static System.Runtime.Intrinsics.X86.Sse; using static System.Runtime.Intrinsics.X86.Sse2; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void InsertSingle2() { var test = new InsertVector128Test__InsertSingle2(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // 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(); if (Sse.IsSupported) { // 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(); if (Sse.IsSupported) { // 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 class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 InsertVector128Test__InsertSingle2 { private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(InsertVector128Test__InsertSingle2 testClass) { var result = Sse41.Insert(_fld1, _fld2, 2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable; static InsertVector128Test__InsertSingle2() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public InsertVector128Test__InsertSingle2() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.Insert( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr), 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.Insert( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), LoadVector128((Single*)(_dataTable.inArray2Ptr)), 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.Insert( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)), 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr), (byte)2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), LoadVector128((Single*)(_dataTable.inArray2Ptr)), (byte)2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)), (byte)2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.Insert( _clsVar1, _clsVar2, 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse41.Insert(left, right, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse41.Insert(left, right, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse41.Insert(left, right, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertVector128Test__InsertSingle2(); var result = Sse41.Insert(test._fld1, test._fld2, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.Insert(_fld1, _fld2, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.Insert(test._fld1, test._fld2, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (i == 1 ? BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(0.0f) : BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(left[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<Single>(Vector128<Single>, Vector128<Single>.2): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
#region License // Copyright (c) K2 Workflow (SourceCode Technology Holdings Inc.). All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. #endregion using System; using System.Collections.Generic; using Xunit; namespace SourceCode.Clay.Buffers.Tests { public static class BufferComparerTests { public static ArraySegment<byte> GenerateSegment(ushort offset, int length, int delta = 0) { var result = new byte[length + offset * 2]; // Add extra space at start and end for (var i = 1 + offset; i < length + offset; i++) result[i] = (byte)((result[i - 1] + i - offset + delta) & 0xFF); return new ArraySegment<byte>(result, offset, length); } public static ReadOnlyMemory<byte> AsReadOnlyMemory(this ArraySegment<byte> seg) => (ReadOnlyMemory<byte>)seg; public static ReadOnlyMemory<byte> AsReadOnlyMemory(this byte[] array) => (ReadOnlyMemory<byte>)array; [Trait("Type", "Unit")] [Fact] public static void BufferComparer_GetHashCode_Null_Array() { Assert.Equal(0, BufferComparer.Array.GetHashCode(default)); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_GetHashCode_Empty_Array() { Assert.Equal(ByteHashCode.Combine(Array.Empty<byte>()), BufferComparer.Array.GetHashCode(Array.Empty<byte>())); Assert.Equal(ByteHashCode.Combine(Array.Empty<byte>()), BufferComparer.Memory.GetHashCode(Array.Empty<byte>())); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_GetHashCode_Empty_Memory() { Assert.Equal(ByteHashCode.Combine(Array.Empty<byte>()), BufferComparer.Memory.GetHashCode(Memory<byte>.Empty)); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_GetHashCode_MemoryShort() { ArraySegment<byte> bytes = GenerateSegment(0, 16); var hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes), hash); bytes = GenerateSegment(10, 16); hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes), hash); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_GetHashCode_MemoryMedium() { ArraySegment<byte> bytes = GenerateSegment(0, 712); var hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes.AsSpan(0, BufferComparer.DefaultHashCodeFidelity)), hash); bytes = GenerateSegment(10, 712); hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes.AsSpan(0, BufferComparer.DefaultHashCodeFidelity)), hash); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_GetHashCode_MemoryLong() { ArraySegment<byte> bytes = GenerateSegment(0, 1024); var hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes.AsSpan(0, BufferComparer.DefaultHashCodeFidelity)), hash); bytes = GenerateSegment(10, 1024); hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes.AsSpan(0, BufferComparer.DefaultHashCodeFidelity)), hash); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_GetHashCode_ReadOnlyMemoryShort() { ReadOnlyMemory<byte> bytes = GenerateSegment(0, 16).AsReadOnlyMemory(); var hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes.Span), hash); bytes = GenerateSegment(10, 16).AsReadOnlyMemory(); hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes.Span), hash); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_GetHashCode_ReadOnlyMemoryMedium() { ReadOnlyMemory<byte> bytes = GenerateSegment(0, 712).AsReadOnlyMemory(); var hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes.Span.Slice(0, BufferComparer.DefaultHashCodeFidelity)), hash); bytes = GenerateSegment(10, 712).AsReadOnlyMemory(); hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes.Span.Slice(0, BufferComparer.DefaultHashCodeFidelity)), hash); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_GetHashCode_ReadOnlyMemoryLong() { ReadOnlyMemory<byte> bytes = GenerateSegment(0, 1024).AsReadOnlyMemory(); var hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes.Span.Slice(0, BufferComparer.DefaultHashCodeFidelity)), hash); bytes = GenerateSegment(10, 1024).AsReadOnlyMemory(); hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes.Span.Slice(0, BufferComparer.DefaultHashCodeFidelity)), hash); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_GetHashCode_ArrayShort() { var bytes = GenerateSegment(0, 16).Array; var hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes), hash); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_GetHashCode_ArrayMedium() { var bytes = GenerateSegment(0, BufferComparer.DefaultHashCodeFidelity).Array; var hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes), hash); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_GetHashCode_ArrayLong() { var bytes = GenerateSegment(0, 1024).Array; var hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes.AsSpan(0, BufferComparer.DefaultHashCodeFidelity)), hash); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_GetHashCode_ArraySegmentShort() { ArraySegment<byte> bytes = GenerateSegment(0, 16); var hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes), hash); bytes = GenerateSegment(10, 16); hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes), hash); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_GetHashCode_ArraySegmentMedium() { ArraySegment<byte> bytes = GenerateSegment(0, 712); var hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes.AsSpan(0, BufferComparer.DefaultHashCodeFidelity)), hash); bytes = GenerateSegment(10, 712); hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes.AsSpan(0, BufferComparer.DefaultHashCodeFidelity)), hash); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_GetHashCode_ArraySegmentLong() { ArraySegment<byte> bytes = GenerateSegment(0, 1024); var hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes.AsSpan(0, BufferComparer.DefaultHashCodeFidelity)), hash); bytes = GenerateSegment(10, 1024); hash = BufferComparer.Memory.GetHashCode(bytes); Assert.Equal(ByteHashCode.Combine(bytes.AsSpan(0, BufferComparer.DefaultHashCodeFidelity)), hash); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_Equals_Null_Array() { byte[] a = null; byte[] b = null; Assert.Equal(a, b, BufferComparer.Array); Assert.True(BufferComparer.Array.Equals(a, b)); Assert.Equal(a, b, BufferComparer.Memory); Assert.True(BufferComparer.Memory.Equals(a, b)); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_Equals_Empty_Array() { var a = Array.Empty<byte>(); var b = Array.Empty<byte>(); Assert.Equal(a, b, BufferComparer.Array); Assert.Equal(a, b, BufferComparer.Memory); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_Equals_Memory() { ArraySegment<byte> a = GenerateSegment(0, 16); ArraySegment<byte> a1 = GenerateSegment(10, 16); // Same ArraySegment<byte> a2 = GenerateSegment(0, 16); // Same ArraySegment<byte> c = GenerateSegment(0, 16, 1); ArraySegment<byte> d = GenerateSegment(0, 15); Assert.Equal(a, a1, BufferComparer.Memory); Assert.Equal(a, a2, BufferComparer.Memory); Assert.NotEqual(a, c, BufferComparer.Memory); Assert.NotEqual(a, d, BufferComparer.Memory); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_Equals_ReadOnlyMemory() { ReadOnlyMemory<byte> a = GenerateSegment(0, 16).AsReadOnlyMemory(); ReadOnlyMemory<byte> a1 = GenerateSegment(10, 16).AsReadOnlyMemory(); // Same ReadOnlyMemory<byte> a2 = GenerateSegment(0, 16).AsReadOnlyMemory(); // Same ReadOnlyMemory<byte> c = GenerateSegment(0, 16, 1).AsReadOnlyMemory(); ReadOnlyMemory<byte> d = GenerateSegment(0, 15).AsReadOnlyMemory(); Assert.Equal(a, a1, BufferComparer.Memory); Assert.Equal(a, a2, BufferComparer.Memory); Assert.NotEqual(a, c, BufferComparer.Memory); Assert.NotEqual(a, d, BufferComparer.Memory); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_Equals_Array() { var a = GenerateSegment(0, 16).Array; var a1 = GenerateSegment(0, 16).Array; // Same var c = GenerateSegment(0, 16, 1).Array; var d = GenerateSegment(0, 15).Array; // Array Assert.Equal(a, a1, BufferComparer.Array); Assert.NotEqual(a, c, BufferComparer.Array); Assert.NotEqual(a, d, BufferComparer.Array); // Span Assert.Equal(a, a1, BufferComparer.Memory); Assert.NotEqual(a, c, BufferComparer.Memory); Assert.NotEqual(a, d, BufferComparer.Memory); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_Equals_ArraySegment() { ArraySegment<byte> a = GenerateSegment(0, 16); ArraySegment<byte> a1 = GenerateSegment(10, 16); // Same ArraySegment<byte> a2 = GenerateSegment(0, 16); // Same ArraySegment<byte> c = GenerateSegment(0, 16, 1); ArraySegment<byte> d = GenerateSegment(0, 15); Assert.Equal(a, a1, BufferComparer.Memory); Assert.Equal(a, a2, BufferComparer.Memory); Assert.NotEqual(a, c, BufferComparer.Memory); Assert.NotEqual(a, d, BufferComparer.Memory); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_Compare_Array_Null() { byte[] a = null; byte[] b = null; var c = new byte[0]; // empty // Array Assert.True(BufferComparer.Array.Compare(a, a) == 0); Assert.True(BufferComparer.Array.Compare(a, b) == 0); Assert.True(BufferComparer.Array.Compare(a, c) < 0); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_Compare_Array_Length_One() { var a = new byte[1] { 1 }; var a1 = new byte[1] { 1 }; // Same var a2 = new byte[4] { 3, 2, 1, 2 }; // Same-ish var b = new byte[1] { 2 }; var c = new byte[1] { 0 }; // Array Assert.True(BufferComparer.Array.Compare(a, a1) == 0); Assert.True(BufferComparer.Array.Compare(a, b) < 0); Assert.True(BufferComparer.Array.Compare(a, c) > 0); // ReadOnlyMemory Assert.True(BufferComparer.Memory.Compare((ReadOnlyMemory<byte>)a, a1) == 0); Assert.True(BufferComparer.Memory.Compare((ReadOnlyMemory<byte>)a, b) < 0); Assert.True(BufferComparer.Memory.Compare((ReadOnlyMemory<byte>)a, c) > 0); // Span (implicit conversion from Span to ReadOnlyMemory) Assert.True(BufferComparer.Memory.Compare((Memory<byte>)a, a1) == 0); Assert.True(BufferComparer.Memory.Compare((Memory<byte>)a, b) < 0); Assert.True(BufferComparer.Memory.Compare((Memory<byte>)a, c) > 0); // Array (implicit conversion from byte[] to ReadOnlyMemory) Assert.True(BufferComparer.Memory.Compare(a, a1) == 0); Assert.True(BufferComparer.Memory.Compare(a, b) < 0); Assert.True(BufferComparer.Memory.Compare(a, c) > 0); // ArraySegment (implicit conversion from ArraySegment to ReadOnlyMemory) Assert.True(BufferComparer.Memory.Compare(new ArraySegment<byte>(a), new ArraySegment<byte>(a1)) == 0); Assert.True(BufferComparer.Memory.Compare(new ArraySegment<byte>(a), new ArraySegment<byte>(a2, 2, 1)) == 0); Assert.True(BufferComparer.Memory.Compare(new ArraySegment<byte>(a), new ArraySegment<byte>(b)) < 0); Assert.True(BufferComparer.Memory.Compare(new ArraySegment<byte>(a), new ArraySegment<byte>(c)) > 0); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_Compare_Array_Length_N() { ArraySegment<byte> a = GenerateSegment(0, 16); ArraySegment<byte> a1 = GenerateSegment(0, 16); // Same ArraySegment<byte> a2 = GenerateSegment(10, 16); // Same ArraySegment<byte> c = GenerateSegment(0, 16, 1); ArraySegment<byte> d = GenerateSegment(0, 15); // Array Assert.True(BufferComparer.Array.Compare(a.Array, a1.Array) == 0); Assert.True(BufferComparer.Array.Compare(a.Array, c.Array) < 0); Assert.True(BufferComparer.Array.Compare(c.Array, a.Array) > 0); Assert.True(BufferComparer.Array.Compare(d.Array, a.Array) < 0); Assert.True(BufferComparer.Array.Compare(a.Array, d.Array) > 0); // ReadOnlyMemory Assert.True(BufferComparer.Memory.Compare((ReadOnlyMemory<byte>)a, a1) == 0); Assert.True(BufferComparer.Memory.Compare((ReadOnlyMemory<byte>)a, a2) == 0); Assert.True(BufferComparer.Memory.Compare((ReadOnlyMemory<byte>)a, c) < 0); Assert.True(BufferComparer.Memory.Compare((ReadOnlyMemory<byte>)c, a) > 0); Assert.True(BufferComparer.Memory.Compare((ReadOnlyMemory<byte>)d, a) < 0); Assert.True(BufferComparer.Memory.Compare((ReadOnlyMemory<byte>)a, d) > 0); // Span (implicit conversion from Span to ReadOnlyMemory) Assert.True(BufferComparer.Memory.Compare((Memory<byte>)a, a1) == 0); Assert.True(BufferComparer.Memory.Compare((Memory<byte>)a, a2) == 0); Assert.True(BufferComparer.Memory.Compare((Memory<byte>)a, c) < 0); Assert.True(BufferComparer.Memory.Compare((Memory<byte>)c, a) > 0); Assert.True(BufferComparer.Memory.Compare((Memory<byte>)d, a) < 0); Assert.True(BufferComparer.Memory.Compare((Memory<byte>)a, d) > 0); // Array (implicit conversion from byte[] to ReadOnlyMemory) Assert.True(BufferComparer.Memory.Compare(a.Array, a1.Array) == 0); Assert.True(BufferComparer.Memory.Compare(a.Array, c.Array) < 0); Assert.True(BufferComparer.Memory.Compare(c.Array, a.Array) > 0); Assert.True(BufferComparer.Memory.Compare(d.Array, a.Array) < 0); Assert.True(BufferComparer.Memory.Compare(a.Array, d.Array) > 0); // ArraySegment (implicit conversion from ArraySegment to ReadOnlyMemory) Assert.True(BufferComparer.Memory.Compare(a, a1) == 0); Assert.True(BufferComparer.Memory.Compare(a, a2) == 0); Assert.True(BufferComparer.Memory.Compare(a, c) < 0); Assert.True(BufferComparer.Memory.Compare(c, a) > 0); Assert.True(BufferComparer.Memory.Compare(d, a) < 0); Assert.True(BufferComparer.Memory.Compare(a, d) > 0); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_Compare_ArraySegment_Length_One() { var a = new ArraySegment<byte>(new byte[] { 1 }); var a1 = new ArraySegment<byte>(new byte[5] { 5, 4, 1, 2, 3 }, 2, 1); // Same var b = new ArraySegment<byte>(new byte[] { 0, 0, 0, 2 }, 3, 1); var c = new ArraySegment<byte>(new byte[] { 3, 3, 3, 3, 0 }, 4, 1); // ArraySegment (implicit conversion) Assert.True(BufferComparer.Memory.Compare(a, a1) == 0); Assert.True(BufferComparer.Memory.Compare(a, b) < 0); Assert.True(BufferComparer.Memory.Compare(a, c) > 0); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_Compare_ArraySegment_Length_N() { ArraySegment<byte> a = GenerateSegment(0, 16); ArraySegment<byte> a1 = GenerateSegment(0, 16); // Same ArraySegment<byte> a2 = GenerateSegment(10, 16); // Same ArraySegment<byte> c = GenerateSegment(0, 16, 1); ArraySegment<byte> d = GenerateSegment(0, 15); // ArraySegment (implicit conversion) Assert.True(BufferComparer.Memory.Compare(a, a1) == 0); Assert.True(BufferComparer.Memory.Compare(a, a2) == 0); Assert.True(BufferComparer.Memory.Compare(a, c) < 0); Assert.True(BufferComparer.Memory.Compare(c, a) > 0); Assert.True(BufferComparer.Memory.Compare(d, a) < 0); Assert.True(BufferComparer.Memory.Compare(a, d) > 0); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_Compare_Array_With_Comparison() { var expected = new byte[4] { 1, 2, 3, 4 }; var a1 = new byte[4] { 1, 2, 3, 6 }; var a2 = new byte[4] { 1, 2, 3, 7 }; var a3 = new byte[4] { 1, 2, 3, 5 }; var list = new List<byte[]>(new[] { a1, a2, expected, a3 }); list.Sort(BufferComparer.Array.Compare); Assert.Equal(expected, list[0], BufferComparer.Array); } [Trait("Type", "Unit")] [Fact] public static void BufferComparer_Compare_Memory_With_Comparison() { ReadOnlyMemory<byte> expected = new byte[4] { 1, 2, 3, 4 }.AsReadOnlyMemory(); ReadOnlyMemory<byte> a1 = new byte[4] { 1, 2, 3, 6 }.AsReadOnlyMemory(); ReadOnlyMemory<byte> a2 = new byte[4] { 1, 2, 3, 7 }.AsReadOnlyMemory(); ReadOnlyMemory<byte> a3 = new byte[4] { 1, 2, 3, 5 }.AsReadOnlyMemory(); var list = new List<ReadOnlyMemory<byte>>(new[] { a1, a2, expected, a3 }); list.Sort(BufferComparer.Memory.Compare); Assert.Equal(expected, list[0], BufferComparer.Memory); } } }
// <copyright file="XmlElementField.cs" company="Fubar Development Junker"> // Copyright (c) 2016 Fubar Development Junker. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.Linq; using BeanIO.Internal.Parser.Format.Xml.Annotations; using BeanIO.Internal.Util; namespace BeanIO.Internal.Parser.Format.Xml { /// <summary> /// A <see cref="IFieldFormat"/> for a field in an XML formatted stream parsed as /// an element of its parent. /// </summary> internal class XmlElementField : XmlFieldFormat { private string _localName; private string _namespace; private string _prefix; private bool _namespaceAware; private bool _repeating; private bool _nillable; /// <summary> /// Gets the XML node type /// </summary> public override XmlNodeType Type => XmlNodeType.Element; /// <summary> /// Gets the XML local name for this node. /// </summary> public override string LocalName => _localName; /// <summary> /// Gets the namespace of this node. If there is no namespace for this /// node, or this node is not namespace aware, <code>null</code> is returned. /// </summary> public override string Namespace => _namespace; /// <summary> /// Gets a value indicating whether a namespace was configured for this node, /// and is therefore used to unmarshal and marshal the node. /// </summary> public override bool IsNamespaceAware => _namespaceAware; /// <summary> /// Gets the namespace prefix for marshaling this node, or <code>null</code> /// if the namespace should override the default namespace. /// </summary> public override string Prefix => _prefix; /// <summary> /// Gets a value indicating whether this field is nillable /// </summary> public override bool IsNillable => _nillable; /// <summary> /// Gets a value indicating whether this node may repeat in the context of its immediate parent. /// </summary> public override bool IsRepeating => _repeating; /// <summary> /// Inserts a field into the record during marshalling /// </summary> /// <param name="ctx">the <see cref="XmlMarshallingContext"/> holding the record</param> /// <param name="fieldText">the field text to insert</param> public override void InsertText(XmlMarshallingContext ctx, string fieldText) { if (fieldText == null && IsLazy) return; if (ReferenceEquals(fieldText, Value.Nil)) fieldText = null; var element = new XElement(this.ToXName(true).ToConvertedName(ctx.NameConversionMode)); var annotations = new List<object>(); if (!IsNamespaceAware) { annotations.Add(new NamespaceModeAnnotation(NamespaceHandlingMode.IgnoreNamespace)); } else if (string.IsNullOrEmpty(Namespace)) { annotations.Add(new NamespaceModeAnnotation(NamespaceHandlingMode.DefaultNamespace)); } else if (string.Equals(Prefix, string.Empty)) { annotations.Add(new NamespaceModeAnnotation(NamespaceHandlingMode.NoPrefix)); } else if (Prefix != null) { element.SetAttributeValue(XNamespace.Xmlns + Prefix, Namespace); } element = XElement.Parse(element.ToString()); foreach (var annotation in annotations) element.SetAnnotation(annotation); if (fieldText == null && IsNillable) { element.SetNil(); } else if (!string.IsNullOrEmpty(fieldText)) { element.Add(new XText(fieldText)); } var parent = ctx.Parent; parent.Add(element); } /// <summary> /// Sets the attribute name. /// </summary> /// <param name="localName">the attribute name</param> public void SetLocalName(string localName) { _localName = localName; } /// <summary> /// Sets the namespace of the attribute (typically null). /// </summary> /// <param name="ns">the attribute namespace</param> public void SetNamespace(string ns) { _namespace = ns; } /// <summary> /// Sets the prefix to use for this attribute's namespace. /// </summary> /// <param name="prefix">the namespace prefix</param> public void SetPrefix(string prefix) { _prefix = prefix; } /// <summary> /// Sets whether this attribute uses a namespace /// </summary> /// <param name="namespaceAware">true if this attribute uses a namespace, false otherwise</param> public void SetNamespaceAware(bool namespaceAware) { _namespaceAware = namespaceAware; } /// <summary> /// Sets a value indicating whether this element repeats within the context of its parent /// </summary> /// <param name="repeating">true if repeating, false otherwise</param> public void SetRepeating(bool repeating) { _repeating = repeating; } /// <summary> /// Sets a value indicating whether this element is nillable /// </summary> /// <param name="nillable">true if nillable, false otherwise</param> public void SetNillable(bool nillable) { _nillable = nillable; } /// <summary> /// Extracts a field from a record during unmarshalling /// </summary> /// <param name="context">the <see cref="XmlUnmarshallingContext"/> holding the record</param> /// <returns>the extracted field text</returns> protected override string ExtractText(XmlUnmarshallingContext context) { var node = context.FindElement(this); if (node == null) return null; // check for nil elements if (node.IsNil()) return Value.Nil; var fieldText = node.GetText() ?? string.Empty; return fieldText; } /// <summary> /// Called by <see cref="XmlFieldFormat.ToString"/> to append attributes of this field. /// </summary> /// <param name="s">the string builder to add the parameters to</param> protected override void ToParamString(StringBuilder s) { base.ToParamString(s); s.AppendFormat(", localName={0}", LocalName); if (Prefix != null) s.AppendFormat(", prefix={0}", Prefix); if (Namespace != null) s.AppendFormat(", xmlns={0}", Namespace); s.AppendFormat(", {0}", DebugUtil.FormatOption("nillable", IsNillable)); } } }
// Copyright 2013 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NodaTime.Annotations; using NodaTime.Globalization; using NodaTime.Text.Patterns; using NodaTime.Utility; using System.Globalization; using System.Text; namespace NodaTime.Text { /// <summary> /// Represents a pattern for parsing and formatting <see cref="OffsetDateTime"/> values. /// </summary> /// <threadsafety> /// When used with a read-only <see cref="CultureInfo" />, this type is immutable and instances /// may be shared freely between threads. We recommend only using read-only cultures for patterns, although this is /// not currently enforced. /// </threadsafety> [Immutable] // Well, assuming an immutable culture... public sealed class OffsetDateTimePattern : IPattern<OffsetDateTime> { internal static readonly OffsetDateTime DefaultTemplateValue = new LocalDateTime(2000, 1, 1, 0, 0).WithOffset(Offset.Zero); /// <summary> /// Gets an invariant offset date/time pattern based on ISO-8601 (down to the second), including offset from UTC. /// </summary> /// <remarks> /// The calendar system is not parsed or formatted as part of this pattern. It corresponds to a custom pattern of /// "uuuu'-'MM'-'dd'T'HH':'mm':'sso&lt;G&gt;". This pattern is available as the "G" /// standard pattern (even though it is invariant). /// </remarks> /// <value>An invariant offset date/time pattern based on ISO-8601 (down to the second), including offset from UTC.</value> public static OffsetDateTimePattern GeneralIso => Patterns.GeneralIsoPatternImpl; /// <summary> /// Gets an invariant offset date/time pattern based on ISO-8601 (down to the nanosecond), including offset from UTC. /// </summary> /// <remarks> /// The calendar system is not parsed or formatted as part of this pattern. It corresponds to a custom pattern of /// "uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo&lt;G&gt;". This will round-trip any values /// in the ISO calendar, and is available as the "o" standard pattern. /// </remarks> /// <value>An invariant offset date/time pattern based on ISO-8601 (down to the nanosecond), including offset from UTC.</value> public static OffsetDateTimePattern ExtendedIso => Patterns.ExtendedIsoPatternImpl; /// <summary> /// Gets an invariant offset date/time pattern based on RFC 3339 (down to the nanosecond), including offset from UTC /// as hours and minutes only. /// </summary> /// <remarks> /// The minutes part of the offset is always included, but any sub-minute component /// of the offset is lost. An offset of zero is formatted as 'Z', but all of 'Z', '+00:00' and '-00:00' are parsed /// the same way. The RFC 3339 meaning of '-00:00' is not supported by Noda Time. /// Note that parsing is case-sensitive (so 'T' and 'Z' must be upper case). /// The calendar system is not parsed or formatted as part of this pattern. It corresponds to a custom pattern of /// "uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo&lt;Z+HH:mm&gt;". /// </remarks> /// <value>An invariant offset date/time pattern based on RFC 3339 (down to the nanosecond), including offset from UTC /// as hours and minutes only.</value> public static OffsetDateTimePattern Rfc3339 => Patterns.Rfc3339PatternImpl; /// <summary> /// Gets an invariant offset date/time pattern based on ISO-8601 (down to the nanosecond) /// including offset from UTC and calendar ID. /// </summary> /// <remarks> /// The returned pattern corresponds to a custom pattern of /// "uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo&lt;G&gt; '('c')'". This will round-trip any value in any calendar, /// and is available as the "r" standard pattern. /// </remarks> /// <value>An invariant offset date/time pattern based on ISO-8601 (down to the nanosecond) /// including offset from UTC and calendar ID.</value> public static OffsetDateTimePattern FullRoundtrip => Patterns.FullRoundtripPatternImpl; /// <summary> /// Class whose existence is solely to avoid type initialization order issues, most of which stem /// from needing NodaFormatInfo.InvariantInfo... /// </summary> internal static class Patterns { internal static readonly OffsetDateTimePattern GeneralIsoPatternImpl = Create("uuuu'-'MM'-'dd'T'HH':'mm':'sso<G>", NodaFormatInfo.InvariantInfo, DefaultTemplateValue); internal static readonly OffsetDateTimePattern ExtendedIsoPatternImpl = Create("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<G>", NodaFormatInfo.InvariantInfo, DefaultTemplateValue); internal static readonly OffsetDateTimePattern Rfc3339PatternImpl = Create("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<Z+HH:mm>", NodaFormatInfo.InvariantInfo, DefaultTemplateValue); internal static readonly OffsetDateTimePattern FullRoundtripPatternImpl = Create("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<G> '('c')'", NodaFormatInfo.InvariantInfo, DefaultTemplateValue); internal static readonly PatternBclSupport<OffsetDateTime> BclSupport = new PatternBclSupport<OffsetDateTime>("G", fi => fi.OffsetDateTimePatternParser); } private readonly IPattern<OffsetDateTime> pattern; /// <summary> /// Gets the pattern text for this pattern, as supplied on creation. /// </summary> /// <value>The pattern text for this pattern, as supplied on creation.</value> public string PatternText { get; } // Visible for testing /// <summary> /// Gets the localization information used in this pattern. /// </summary> internal NodaFormatInfo FormatInfo { get; } /// <summary> /// Gets the value used as a template for parsing: any field values unspecified /// in the pattern are taken from the template. /// </summary> /// <value>The value used as a template for parsing.</value> public OffsetDateTime TemplateValue { get; } private OffsetDateTimePattern(string patternText, NodaFormatInfo formatInfo, OffsetDateTime templateValue, IPattern<OffsetDateTime> pattern) { this.PatternText = patternText; this.FormatInfo = formatInfo; this.TemplateValue = templateValue; this.pattern = pattern; } /// <summary> /// Parses the given text value according to the rules of this pattern. /// </summary> /// <remarks> /// This method never throws an exception (barring a bug in Noda Time itself). Even errors such as /// the argument being null are wrapped in a parse result. /// </remarks> /// <param name="text">The text value to parse.</param> /// <returns>The result of parsing, which may be successful or unsuccessful.</returns> public ParseResult<OffsetDateTime> Parse([SpecialNullHandling] string text) => pattern.Parse(text); /// <summary> /// Formats the given zoned date/time as text according to the rules of this pattern. /// </summary> /// <param name="value">The zoned date/time to format.</param> /// <returns>The zoned date/time formatted according to this pattern.</returns> public string Format(OffsetDateTime value) => pattern.Format(value); /// <summary> /// Formats the given value as text according to the rules of this pattern, /// appending to the given <see cref="StringBuilder"/>. /// </summary> /// <param name="value">The value to format.</param> /// <param name="builder">The <c>StringBuilder</c> to append to.</param> /// <returns>The builder passed in as <paramref name="builder"/>.</returns> public StringBuilder AppendFormat(OffsetDateTime value, StringBuilder builder) => pattern.AppendFormat(value, builder); /// <summary> /// Creates a pattern for the given pattern text, format info, and template value. /// </summary> /// <param name="patternText">Pattern text to create the pattern for</param> /// <param name="formatInfo">The format info to use in the pattern</param> /// <param name="templateValue">Template value to use for unspecified fields</param> /// <returns>A pattern for parsing and formatting zoned date/times.</returns> /// <exception cref="InvalidPatternException">The pattern text was invalid.</exception> private static OffsetDateTimePattern Create(string patternText, NodaFormatInfo formatInfo, OffsetDateTime templateValue) { Preconditions.CheckNotNull(patternText, nameof(patternText)); Preconditions.CheckNotNull(formatInfo, nameof(formatInfo)); var pattern = new OffsetDateTimePatternParser(templateValue).ParsePattern(patternText, formatInfo); return new OffsetDateTimePattern(patternText, formatInfo, templateValue, pattern); } /// <summary> /// Creates a pattern for the given pattern text, culture, and template value. /// </summary> /// <remarks> /// See the user guide for the available pattern text options. /// </remarks> /// <param name="patternText">Pattern text to create the pattern for</param> /// <param name="cultureInfo">The culture to use in the pattern</param> /// <param name="templateValue">Template value to use for unspecified fields</param> /// <returns>A pattern for parsing and formatting local date/times.</returns> /// <exception cref="InvalidPatternException">The pattern text was invalid.</exception> public static OffsetDateTimePattern Create(string patternText, CultureInfo cultureInfo, OffsetDateTime templateValue) => Create(patternText, NodaFormatInfo.GetFormatInfo(cultureInfo), templateValue); /// <summary> /// Creates a pattern for the given pattern text in the invariant culture, using the default /// template value of midnight January 1st 2000 at an offset of 0. /// </summary> /// <remarks> /// See the user guide for the available pattern text options. /// </remarks> /// <param name="patternText">Pattern text to create the pattern for</param> /// <returns>A pattern for parsing and formatting local date/times.</returns> /// <exception cref="InvalidPatternException">The pattern text was invalid.</exception> public static OffsetDateTimePattern CreateWithInvariantCulture(string patternText) => Create(patternText, NodaFormatInfo.InvariantInfo, DefaultTemplateValue); /// <summary> /// Creates a pattern for the given pattern text in the current culture, using the default /// template value of midnight January 1st 2000 at an offset of 0. /// </summary> /// <remarks> /// See the user guide for the available pattern text options. Note that the current culture /// is captured at the time this method is called - it is not captured at the point of parsing /// or formatting values. /// </remarks> /// <param name="patternText">Pattern text to create the pattern for</param> /// <returns>A pattern for parsing and formatting local date/times.</returns> /// <exception cref="InvalidPatternException">The pattern text was invalid.</exception> public static OffsetDateTimePattern CreateWithCurrentCulture(string patternText) => Create(patternText, NodaFormatInfo.CurrentInfo, DefaultTemplateValue); /// <summary> /// Creates a pattern for the same original localization information as this pattern, but with the specified /// pattern text. /// </summary> /// <param name="patternText">The pattern text to use in the new pattern.</param> /// <returns>A new pattern with the given pattern text.</returns> public OffsetDateTimePattern WithPatternText(string patternText) => Create(patternText, FormatInfo, TemplateValue); /// <summary> /// Creates a pattern for the same original pattern text as this pattern, but with the specified /// localization information. /// </summary> /// <param name="formatInfo">The localization information to use in the new pattern.</param> /// <returns>A new pattern with the given localization information.</returns> private OffsetDateTimePattern WithFormatInfo(NodaFormatInfo formatInfo) => Create(PatternText, formatInfo, TemplateValue); /// <summary> /// Creates a pattern for the same original pattern text as this pattern, but with the specified /// culture. /// </summary> /// <param name="cultureInfo">The culture to use in the new pattern.</param> /// <returns>A new pattern with the given culture.</returns> public OffsetDateTimePattern WithCulture(CultureInfo cultureInfo) => WithFormatInfo(NodaFormatInfo.GetFormatInfo(cultureInfo)); /// <summary> /// Creates a pattern for the same original pattern text and culture as this pattern, but with /// the specified template value. /// </summary> /// <param name="newTemplateValue">The template value to use in the new pattern.</param> /// <returns>A new pattern with the given template value.</returns> public OffsetDateTimePattern WithTemplateValue(OffsetDateTime newTemplateValue) => Create(PatternText, FormatInfo, newTemplateValue); /// <summary> /// Creates a pattern like this one, but with the template value modified to use /// the specified calendar system. /// </summary> /// <remarks> /// <para> /// Care should be taken in two (relatively rare) scenarios. Although the default template value /// is supported by all Noda Time calendar systems, if a pattern is created with a different /// template value and then this method is called with a calendar system which doesn't support that /// date, an exception will be thrown. Additionally, if the pattern only specifies some date fields, /// it's possible that the new template value will not be suitable for all values. /// </para> /// </remarks> /// <param name="calendar">The calendar system to convert the template value into.</param> /// <returns>A new pattern with a template value in the specified calendar system.</returns> public OffsetDateTimePattern WithCalendar(CalendarSystem calendar) => WithTemplateValue(TemplateValue.WithCalendar(calendar)); } }
/* * 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. */ // ReSharper disable UnusedMember.Local // ReSharper disable UnusedMember.Global // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable MemberCanBePrivate.Global // ReSharper disable UnusedAutoPropertyAccessor.Local // ReSharper disable UnassignedField.Global namespace Apache.Ignite.Core.Tests.Compute { using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Test resource injections in tasks and jobs. /// </summary> public class ResourceTaskTest : AbstractTaskTest { /// <summary> /// Constructor. /// </summary> public ResourceTaskTest() : base(false) { } /// <summary> /// Constructor. /// </summary> /// <param name="fork">Fork flag.</param> protected ResourceTaskTest(bool fork) : base(fork) { } /// <summary> /// Test Ignite injection into the task. /// </summary> [Test] public void TestTaskInjection() { int res = Grid1.GetCompute().Execute(new InjectionTask(), 0); Assert.AreEqual(GetServerCount(), res); } /// <summary> /// Test Ignite injection into the task. /// </summary> [Test] public void TestTaskInjectionBinarizable() { int res = Grid1.GetCompute().Execute(new InjectionTaskBinarizable(), 0); Assert.AreEqual(GetServerCount(), res); } /// <summary> /// Test Ignite injection into the closure. /// </summary> [Test] public void TestClosureInjection() { var res = Grid1.GetCompute().Broadcast(new InjectionClosure(), 1); Assert.AreEqual(GetServerCount(), res.Sum()); } /// <summary> /// Test Ignite injection into reducer. /// </summary> [Test] public void TestReducerInjection() { int res = Grid1.GetCompute().Apply(new InjectionClosure(), new List<int> { 1, 1, 1 }, new InjectionReducer()); Assert.AreEqual(3, res); } /// <summary> /// Test no-result-cache attribute. /// </summary> [Test] public void TestNoResultCache() { int res = Grid1.GetCompute().Execute(new NoResultCacheTask(), 0); Assert.AreEqual(GetServerCount(), res); } /// <summary> /// Injection task. /// </summary> public class InjectionTask : Injectee, IComputeTask<object, int, int> { /** <inheritDoc /> */ public IDictionary<IComputeJob<int>, IClusterNode> Map(IList<IClusterNode> subgrid, object arg) { CheckInjection(); return subgrid.ToDictionary(x => (IComputeJob<int>) new InjectionJob(), x => x); } /** <inheritDoc /> */ public ComputeJobResultPolicy OnResult(IComputeJobResult<int> res, IList<IComputeJobResult<int>> rcvd) { return ComputeJobResultPolicy.Wait; } /** <inheritDoc /> */ public int Reduce(IList<IComputeJobResult<int>> results) { return results.Sum(res => res.Data); } } /// <summary> /// Injection task. /// </summary> private class InjectionTaskBinarizable : Injectee, IComputeTask<object, int, int> { /** <inheritDoc /> */ public IDictionary<IComputeJob<int>, IClusterNode> Map(IList<IClusterNode> subgrid, object arg) { CheckInjection(); return subgrid.ToDictionary(x => (IComputeJob<int>) new InjectionJobBinarizable(), x => x); } /** <inheritDoc /> */ public ComputeJobResultPolicy OnResult(IComputeJobResult<int> res, IList<IComputeJobResult<int>> rcvd) { return ComputeJobResultPolicy.Wait; } /** <inheritDoc /> */ public int Reduce(IList<IComputeJobResult<int>> results) { return results.Sum(res => res.Data); } } /// <summary> /// Binarizable job. /// </summary> public class InjectionJobBinarizable : InjectionJob, IBinarizable { public void WriteBinary(IBinaryWriter writer) { // No-op. } public void ReadBinary(IBinaryReader reader) { // No-op. } } /// <summary> /// Injection job. /// </summary> [Serializable] public class InjectionJob : Injectee, IComputeJob<int> { /// <summary> /// /// </summary> public InjectionJob() { // No-op. } /// <summary> /// /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected InjectionJob(SerializationInfo info, StreamingContext context) : base(info, context) { // No-op. } /** <inheritDoc /> */ public int Execute() { CheckInjection(); return 1; } public void Cancel() { // No-op. } } /// <summary> /// Injection closure. /// </summary> [Serializable] public class InjectionClosure : IComputeFunc<int, int> { /** */ [InstanceResource] private static IIgnite _staticGrid1; /** */ [InstanceResource] public static IIgnite StaticGrid2; /// <summary> /// /// </summary> [InstanceResource] public static IIgnite StaticPropGrid1 { get { return _staticGrid1; } set { _staticGrid1 = value; } } /// <summary> /// /// </summary> [InstanceResource] private static IIgnite StaticPropGrid2 { get { return StaticGrid2; } set { StaticGrid2 = value; } } /// <summary> /// /// </summary> /// <param name="grid"></param> [InstanceResource] public static void StaticMethod1(IIgnite grid) { _staticGrid1 = grid; } /// <summary> /// /// </summary> /// <param name="grid"></param> [InstanceResource] private static void StaticMethod2(IIgnite grid) { StaticGrid2 = grid; } /** */ [InstanceResource] private readonly IIgnite _grid1 = null; /** */ [InstanceResource] public IIgnite Grid2; /** */ private IIgnite _mthdGrid1; /** */ private IIgnite _mthdGrid2; /// <summary> /// /// </summary> [InstanceResource] public IIgnite PropGrid1 { get; set; } /// <summary> /// /// </summary> [InstanceResource] private IIgnite PropGrid2 { get; set; } /// <summary> /// /// </summary> /// <param name="grid"></param> [InstanceResource] public void Method1(IIgnite grid) { _mthdGrid1 = grid; } /// <summary> /// /// </summary> /// <param name="grid"></param> [InstanceResource] private void Method2(IIgnite grid) { _mthdGrid2 = grid; } /// <summary> /// Check Ignite injections. /// </summary> protected void CheckInjection() { Assert.IsTrue(_staticGrid1 == null); Assert.IsTrue(StaticGrid2 == null); Assert.IsTrue(_grid1 != null); Assert.IsTrue(Grid2 == _grid1); Assert.IsTrue(PropGrid1 == _grid1); Assert.IsTrue(PropGrid2 == _grid1); Assert.IsTrue(_mthdGrid1 == _grid1); Assert.IsTrue(_mthdGrid2 == _grid1); } /** <inheritDoc /> */ public int Invoke(int arg) { CheckInjection(); return arg; } } /// <summary> /// Injection reducer. /// </summary> public class InjectionReducer : Injectee, IComputeReducer<int, int> { /** Collected results. */ private readonly ICollection<int> _ress = new List<int>(); /** <inheritDoc /> */ public bool Collect(int res) { CheckInjection(); lock (_ress) { _ress.Add(res); } return true; } /** <inheritDoc /> */ public int Reduce() { CheckInjection(); lock (_ress) { return _ress.Sum(); } } } /// <summary> /// Injectee. /// </summary> [Serializable] public class Injectee : ISerializable { /** */ [InstanceResource] private static IIgnite _staticGrid1; /** */ [InstanceResource] public static IIgnite StaticGrid2; /// <summary> /// /// </summary> [InstanceResource] public static IIgnite StaticPropGrid1 { get { return _staticGrid1; } set { _staticGrid1 = value; } } /// <summary> /// /// </summary> [InstanceResource] private static IIgnite StaticPropGrid2 { get { return StaticGrid2; } set { StaticGrid2 = value; } } /// <summary> /// /// </summary> /// <param name="grid"></param> [InstanceResource] public static void StaticMethod1(IIgnite grid) { _staticGrid1 = grid; } /// <summary> /// /// </summary> /// <param name="grid"></param> [InstanceResource] private static void StaticMethod2(IIgnite grid) { StaticGrid2 = grid; } /// <summary> /// /// </summary> protected Injectee() { // No-op. } /// <summary> /// /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected Injectee(SerializationInfo info, StreamingContext context) { // No-op. } /** */ [InstanceResource] private readonly IIgnite _grid1 = null; /** */ [InstanceResource] public IIgnite Grid2; /** */ private IIgnite _mthdGrid1; /** */ private IIgnite _mthdGrid2; /// <summary> /// /// </summary> [InstanceResource] public IIgnite PropGrid1 { get; set; } /// <summary> /// /// </summary> [InstanceResource] private IIgnite PropGrid2 { get; set; } /// <summary> /// /// </summary> /// <param name="grid"></param> [InstanceResource] public void Method1(IIgnite grid) { _mthdGrid1 = grid; } /// <summary> /// /// </summary> /// <param name="grid"></param> [InstanceResource] private void Method2(IIgnite grid) { _mthdGrid2 = grid; } /// <summary> /// Check Ignite injections. /// </summary> protected void CheckInjection() { Assert.IsTrue(_staticGrid1 == null); Assert.IsTrue(StaticGrid2 == null); Assert.IsTrue(_grid1 != null); Assert.IsTrue(Grid2 == _grid1); Assert.IsTrue(PropGrid1 == _grid1); Assert.IsTrue(PropGrid2 == _grid1); Assert.IsTrue(_mthdGrid1 == _grid1); Assert.IsTrue(_mthdGrid2 == _grid1); } /** <inheritDoc /> */ public void GetObjectData(SerializationInfo info, StreamingContext context) { // No-op. } } /// <summary> /// /// </summary> [ComputeTaskNoResultCache] public class NoResultCacheTask : IComputeTask<int, int, int> { /** Sum. */ private int _sum; /** <inheritDoc /> */ public IDictionary<IComputeJob<int>, IClusterNode> Map(IList<IClusterNode> subgrid, int arg) { return subgrid.ToDictionary(x => (IComputeJob<int>) new NoResultCacheJob(), x => x); } /** <inheritDoc /> */ public ComputeJobResultPolicy OnResult(IComputeJobResult<int> res, IList<IComputeJobResult<int>> rcvd) { Assert.IsTrue(rcvd != null); Assert.IsTrue(rcvd.Count == 0); _sum += res.Data; return ComputeJobResultPolicy.Wait; } /** <inheritDoc /> */ public int Reduce(IList<IComputeJobResult<int>> results) { Assert.IsTrue(results != null); Assert.IsTrue(results.Count == 0); return _sum; } } /// <summary> /// /// </summary> [Serializable] public class NoResultCacheJob : IComputeJob<int> { /** <inheritDoc /> */ public int Execute() { return 1; } public void Cancel() { // No-op. } } } }
using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Text; using Microsoft.Extensions.Logging; using OmniSharp.Models.V2; using OmniSharp.Services; namespace OmniSharp.Roslyn.CSharp.Services.Refactoring.V2 { public static class CodeActionHelper { public static async Task<IEnumerable<CodeAction>> GetActions(OmnisharpWorkspace workspace, IEnumerable<ICodeActionProvider> codeActionProviders, ILogger logger, ICodeActionRequest request) { var actions = new List<CodeAction>(); var originalDocument = workspace.GetDocument(request.FileName); if (originalDocument == null) { return actions; } var refactoringContext = await GetRefactoringContext(originalDocument, request, actions); var codeFixContext = await GetCodeFixContext(originalDocument, request, actions); await CollectRefactoringActions(codeActionProviders, logger, refactoringContext); await CollectCodeFixActions(codeActionProviders, logger, codeFixContext); actions.Reverse(); return actions; } private static async Task<CodeRefactoringContext?> GetRefactoringContext(Document originalDocument, ICodeActionRequest request, List<CodeAction> actionsDestination) { var sourceText = await originalDocument.GetTextAsync(); var location = GetTextSpan(request, sourceText); return new CodeRefactoringContext(originalDocument, location, (a) => actionsDestination.Add(a), CancellationToken.None); } private static async Task<CodeFixContext?> GetCodeFixContext(Document originalDocument, ICodeActionRequest request, List<CodeAction> actionsDestination) { var sourceText = await originalDocument.GetTextAsync(); var semanticModel = await originalDocument.GetSemanticModelAsync(); var diagnostics = semanticModel.GetDiagnostics(); var span = GetTextSpan(request, sourceText); // Try to find exact match var pointDiagnostics = diagnostics.Where(d => d.Location.SourceSpan.Equals(span)).ToImmutableArray(); // No exact match found, try approximate match instead if (pointDiagnostics.Length == 0) { var firstMatchingDiagnostic = diagnostics.FirstOrDefault(d => d.Location.SourceSpan.Contains(span)); // Try to find other matches with the same exact span as the first approximate match if (firstMatchingDiagnostic != null) { pointDiagnostics = diagnostics.Where(d => d.Location.SourceSpan.Equals(firstMatchingDiagnostic.Location.SourceSpan)).ToImmutableArray(); } } // At this point all pointDiagnostics guaranteed to have the same span if (pointDiagnostics.Length > 0) { return new CodeFixContext(originalDocument, pointDiagnostics[0].Location.SourceSpan, pointDiagnostics, (a, d) => actionsDestination.Add(a), CancellationToken.None); } return null; } private static TextSpan GetTextSpan(ICodeActionRequest request, SourceText sourceText) { if (request.Selection != null) { var startPosition = sourceText.Lines.GetPosition(new LinePosition(request.Selection.Start.Line, request.Selection.Start.Column)); var endPosition = sourceText.Lines.GetPosition(new LinePosition(request.Selection.End.Line, request.Selection.End.Column)); return TextSpan.FromBounds(startPosition, endPosition); } var position = sourceText.Lines.GetPosition(new LinePosition(request.Line, request.Column)); return new TextSpan(position, 1); } private static readonly HashSet<string> _blacklist = new HashSet<string> { // This list is horrible but will be temporary "Microsoft.CodeAnalysis.CSharp.CodeFixes.AddMissingReference.AddMissingReferenceCodeFixProvider", "Microsoft.CodeAnalysis.CSharp.CodeFixes.Async.CSharpConvertToAsyncMethodCodeFixProvider", "Microsoft.CodeAnalysis.CSharp.CodeFixes.Iterator.CSharpChangeToIEnumerableCodeFixProvider", "Microsoft.CodeAnalysis.CSharp.CodeRefactorings.ChangeSignature.ChangeSignatureCodeRefactoringProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CreateMethodDeclarationAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.UseStringFormatAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.UseAsAndNullCheckAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.SplitStringAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.SplitIfAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.SplitDeclarationListAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.SplitDeclarationAndAssignmentAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.SimplifyIfInLoopsFlowAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.SimplifyIfFlowAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReverseDirectionForForLoopAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOperatorAssignmentAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantCaseLabelFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.LocalVariableNotUsedFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.PartialTypeWithSinglePartFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantBaseConstructorCallFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantDefaultFieldInitializerFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantOverridenMemberFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantParamsFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.UnusedLabelFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.UnusedParameterFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConstantNullCoalescingConditionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantArgumentDefaultValueFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantBoolCompareFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantCatchClauseFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantCheckBeforeAssignmentFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantCommaInArrayInitializerFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantComparisonWithNullFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantDelegateCreationFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantEmptyFinallyBlockFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantEnumerableCastCallFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantObjectCreationArgumentListFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantExplicitArrayCreationFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantExplicitArraySizeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantExplicitNullableCreationFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantExtendsListEntryFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantIfElseBlockFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantLambdaParameterTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantLambdaSignatureParenthesesFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantLogicalConditionalExpressionOperandFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantObjectOrCollectionInitializerFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantStringToCharArrayCallFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantToStringCallForValueTypesFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantToStringCallFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantUnsafeContextFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantUsingDirectiveFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RemoveRedundantOrStatementFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.UnusedAnonymousMethodSignatureFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.AccessToStaticMemberViaDerivedTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConvertIfToOrExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConvertToConstantFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.MemberCanBeMadeStaticFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ParameterCanBeDeclaredWithBaseTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.PossibleMistakenCallToGetTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.PublicConstructorInAbstractClassFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReferenceEqualsWithValueTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithFirstOrDefaultFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithLastOrDefaultFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeAnyFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeCountFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeFirstFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeFirstOrDefaultFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeLastFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeLastOrDefaultFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeLongCountFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeSingleFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeSingleOrDefaultFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeWhereFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithSingleCallToAnyFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithSingleCallToCountFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithSingleCallToFirstFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithSingleCallToFirstOrDefaultFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithSingleCallToLastFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithSingleCallToLastOrDefaultFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithSingleCallToLongCountFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithSingleCallToSingleFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithSingleCallToSingleOrDefaultFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithStringIsNullOrEmptyFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.SimplifyConditionalTernaryExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.SimplifyLinqExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.StringCompareIsCultureSpecificFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.StringCompareToIsCultureSpecificFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.StringEndsWithIsCultureSpecificFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.StringLastIndexOfIsCultureSpecificFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.StringIndexOfIsCultureSpecificFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.StringStartsWithIsCultureSpecificFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.UseArrayCreationExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.UseIsOperatorFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.UseMethodAnyFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.UseMethodIsInstanceOfTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConvertIfStatementToNullCoalescingExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConvertIfStatementToSwitchStatementFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConvertNullableToShortFormFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConvertToAutoPropertyFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConvertToLambdaExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ForCanBeConvertedToForeachFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RewriteIfReturnToReturnFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.SuggestUseVarKeywordEvidentFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS0183ExpressionIsAlwaysOfProvidedTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS1573ParameterHasNoMatchingParamTagFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS1717AssignmentMadeToSameVariableFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.UnassignedReadonlyFieldFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ProhibitedModifiersFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CanBeReplacedWithTryCastAndCheckForNullFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.EqualExpressionComparisonFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ForControlVariableIsNeverModifiedFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.FormatStringProblemFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.FunctionNeverReturnsFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.LocalVariableHidesMemberFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.LongLiteralEndingLowerLFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.MemberHidesStaticFromOuterClassFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.MethodOverloadWithOptionalParameterFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.NotResolvedInTextIssueFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.OperatorIsCanBeUsedIssueFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.OptionalParameterHierarchyMismatchFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ParameterHidesMemberFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.PartialMethodParameterNameMismatchFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.PolymorphicFieldLikeEventInvocationFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.PossibleAssignmentToReadonlyFieldFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.PossibleMultipleEnumerationFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.StaticFieldInGenericTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ThreadStaticAtInstanceFieldFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ValueParameterNotUsedFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.AdditionalOfTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CastExpressionOfIncompatibleTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CheckNamespaceFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConstantConditionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConvertIfToAndExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.LockThisFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.NegativeRelationalExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ParameterOnlyAssignedFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantAssignmentFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.StaticEventSubscriptionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.XmlDocFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS0029InvalidConversionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS0126ReturnMustBeFollowedByAnyExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS0127ReturnMustNotBeFollowedByAnyExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS0152DuplicateCaseLabelValueFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS0169FieldIsNeverUsedFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS0618UsageOfObsoleteMemberFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS0659ClassOverrideEqualsWithoutGetHashCodeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS0759RedundantPartialMethodIssueFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS1729TypeHasNoConstructorWithNArgumentsFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ExpressionIsNeverOfProvidedTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.MissingInterfaceMemberImplementationFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.InconsistentNamingIssueFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConditionIsAlwaysTrueOrFalseFixProvider" }; private static async Task CollectCodeFixActions(IEnumerable<ICodeActionProvider> codeActionProviders, ILogger logger, CodeFixContext? fixContext) { if (!fixContext.HasValue) return; foreach (var provider in codeActionProviders) { foreach (var codeFix in provider.CodeFixes) { if (_blacklist.Contains(codeFix.ToString())) { continue; } try { await codeFix.RegisterCodeFixesAsync(fixContext.Value); } catch { logger.LogError("Error registering code fixes " + codeFix); } } } } private static async Task CollectRefactoringActions(IEnumerable<ICodeActionProvider> codeActionProviders, ILogger logger, CodeRefactoringContext? refactoringContext) { if (!refactoringContext.HasValue) return; foreach (var provider in codeActionProviders) { foreach (var refactoring in provider.Refactorings) { if (_blacklist.Contains(refactoring.ToString())) { continue; } try { await refactoring.ComputeRefactoringsAsync(refactoringContext.Value); } catch { logger.LogError("Error computing refactorings for " + refactoring); } } } } } }
using System; using System.Collections.ObjectModel; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Web; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using Aspose.Words.Live.Demos.UI.Services; using Aspose.Words.Live.Demos.UI.Models; namespace Aspose.Words.Live.Demos.UI.Config { public class BasePage : BaseRootPage { private string _product; /// <summary> /// Product name (e.g. words, cells) /// </summary> public string Product { get { if (string.IsNullOrEmpty(_product)) { if (Page.RouteData.Values["Product"] != null) { _product = Page.RouteData.Values["Product"].ToString().ToLower(); } } return _product; } set => _product = value; } public string _pageProductTitle; /// <summary> /// Product title (e.g. Aspose.Words) /// </summary> public string PageProductTitle { get { if (_pageProductTitle == null) _pageProductTitle = Resources["Aspose" + TitleCase(Product)]; return _pageProductTitle; } } private int _appURLID = 0; public int AppURLID { get { return _appURLID; } } protected override void OnLoad(EventArgs e) { if (Resources != null) { Page.Title = Resources["ApplicationTitle"]; } base.OnLoad(e); } /// <summary> /// Set validation for RegularExpressionValidators, InputFile and ViewStates using Resources[Product + "ValidationExpression"] /// </summary> private void SetAccept(string validationExpression, params HtmlInputFile[] inpufiles) { var accept = validationExpression.ToLower().Replace("|", ","); foreach (var inpufile in inpufiles) inpufile.Attributes.Add("accept", accept.ToLower().Replace("|", ",")); } /// <summary> /// Set validation for RegularExpressionValidators and ViewStates using Resources[Product + "ValidationExpression"]. /// If the 'ControlToValidate' option is HtmlInputFile, it sets accept an attribute to that control /// </summary> /// <param name="validators"></param> protected void SetValidation(params RegularExpressionValidator[] validators) { var validationExpression = ""; var validFileExtensions = ""; // Check for format like .Doc if (Page.RouteData.Values["Format"] != null) { validFileExtensions = Page.RouteData.Values["Format"].ToString().ToUpper(); validationExpression = "." + validFileExtensions.ToLower(); } else { validationExpression = Resources[Product + "ValidationExpression"]; validFileExtensions = GetValidFileExtensions(validationExpression); } SetValidation(validationExpression, validators); ViewState["product"] = Product; ViewState["validFileExtensions"] = validFileExtensions; } protected void SetValidationExpression(string validationExpression, params RegularExpressionValidator[] validators) { var validFileExtensions = GetValidFileExtensions(validationExpression); SetValidation(validationExpression, validators); ViewState["product"] = Product; ViewState["validFileExtensions"] = validFileExtensions; } /// <summary> /// Set validation for RegularExpressionValidators, InputFile and ViewStates using validationExpression /// </summary> protected string SetValidation(string validationExpression, params RegularExpressionValidator[] validators) { // Check for format if format is available then valid expression will be only format for auto generated URLs if (Page.RouteData.Values["Format"] != null) { validationExpression = "." + Page.RouteData.Values["Format"].ToString().ToLower(); } var validFileExtensions = GetValidFileExtensions(validationExpression); foreach (var v in validators) { v.ValidationExpression = @"(.*?)(" + validationExpression.ToLower() + "|" + validationExpression.ToUpper() + ")$"; v.ErrorMessage = Resources["InvalidFileExtension"] + " " + validFileExtensions; if (!string.IsNullOrEmpty(v.ControlToValidate)) { var control = v.FindControl(v.ControlToValidate); if (control is HtmlInputFile inpufile) SetAccept(validationExpression, inpufile); } } return validFileExtensions; } /// <summary> /// Get the text of valid file extensions /// e.g. DOC, DOCX, DOT, DOTX, RTF or ODT /// </summary> /// <param name="validationExpression"></param> /// <returns></returns> protected string GetValidFileExtensions(string validationExpression) { var validFileExtensions = validationExpression.Replace(".", "").Replace("|", ", ").ToUpper(); var index = validFileExtensions.LastIndexOf(","); if (index != -1) { var substr = validFileExtensions.Substring(index); var str = substr.Replace(",", " or"); validFileExtensions = validFileExtensions.Replace(substr, str); } return validFileExtensions; } /// <summary> /// Check for null and ContentLength of the PostedFile /// </summary> /// <param name="fileInputs"></param> /// <returns></returns> protected bool CheckFileInputs(params HtmlInputFile[] fileInputs) { return fileInputs.All(x => x != null && x.PostedFile.ContentLength > 0); } /// <summary> /// Save uploaded file to the directory /// </summary> /// <returns>SaveLocation with filename</returns> private FileUploadResponse SaveUploadedFile(string directory, HtmlInputFile fileInput, string folder) { var fn = Path.GetFileName(fileInput.PostedFile.FileName); // Edge browser sents a full path for a filename var saveLocation = Path.Combine(directory, fn); fileInput.PostedFile.SaveAs(saveLocation); return new FileUploadResponse { FileName = fn, FileLength = fileInput.PostedFile.ContentLength, FolderId = folder, LocalFilePath = saveLocation }; } /// <summary> /// Check response for null and StatusCode. Call action if everything is fine or show error message if not /// </summary> /// <param name="response"></param> /// <param name="controlErrorMessage"></param> /// <param name="action"></param> protected void PerformResponse(Response response, HtmlGenericControl controlErrorMessage, Action<Response> action) { if (response == null) throw new Exception(Resources["ResponseTime"]); if (response.StatusCode == 200 && response.FileProcessingErrorCode == 0) action(response); else ShowErrorMessage(controlErrorMessage, response); } /// <summary> /// Check FileProcessingErrorCode of the response and show the error message /// </summary> /// <param name="control"></param> /// <param name="response"></param> protected void ShowErrorMessage(HtmlGenericControl control, Response response) { string txt; switch (response.FileProcessingErrorCode) { case FileProcessingErrorCode.NoImagesFound: txt = Resources["NoImagesFoundMessage"]; break; case FileProcessingErrorCode.NoSearchResults: txt = Resources["NoSearchResultsMessage"]; break; case FileProcessingErrorCode.WrongRegExp: txt = Resources["WrongRegExpMessage"]; break; default: txt = response.Status; break; } ShowErrorMessage(control, txt); } protected Collection<FileUploadResponse> UploadFiles(params HtmlInputFile[] fileInputs) { //Collection<FileUploadResponse> uploadResult = null; string _folderName = Guid.NewGuid().ToString(); var directory = Path.Combine(Configuration.WorkingDirectory,_folderName); Directory.CreateDirectory(directory); var uploadResult = fileInputs.Select(x => SaveUploadedFile(directory, x, _folderName)).ToArray(); var list = new Collection<FileUploadResponse>(uploadResult); return list; } protected void ShowErrorMessage(HtmlGenericControl control, string message) { if(message.ToLower().Contains("password")) { if ("pdf words cells slides note".Contains(Product.ToLower()) && !AppRelativeVirtualPath.ToLower().Contains("unlock")) { string asposeUrl = "/" + Product + "/unlock"; message = "Your file seems to be encrypted. Please use our <a style=\"color:yellow\" href=\"" + asposeUrl + "\">" + PageProductTitle + " Unlock</a> app to remove the password."; } } control.Visible = true; control.InnerHtml = message; control.Attributes.Add("class", "alert alert-danger"); } protected void ShowSuccessMessage(HtmlGenericControl control, string message) { control.Visible = true; control.InnerHtml = message; control.Attributes.Add("class", "alert alert-success"); } protected void CheckReturnFromViewer(Action<Response> action) { if (Request.QueryString["folderName"] != null && Request.QueryString["fileName"] != null) { var response = new Response() { FileName = Request.QueryString["fileName"], FolderName = Request.QueryString["folderName"] }; action(response); } } protected string TitleCase(string value) { return new CultureInfo("en-US", false).TextInfo.ToTitleCase(value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Xml.Schema; namespace System.Xml.Xsl.Qil { /// <summary> /// Additional factory methods for constructing common QIL patterns. /// </summary> /// <remarks> /// Some of the methods here are exactly like the ones in QilFactory except /// that they perform constant-folding and other normalization. Others are /// "macro patterns" that simplify the task of constructing otherwise complex patterns. /// </remarks> internal class QilPatternFactory { private bool _debug; private QilFactory _f; public QilPatternFactory(QilFactory f, bool debug) { Debug.Assert(f != null); _f = f; _debug = debug; } public QilFactory BaseFactory { get { return _f; } } public bool IsDebug { get { return _debug; } } #region Convenience methods public QilLiteral String(string val) { return _f.LiteralString(val); } public QilLiteral Int32(int val) { return _f.LiteralInt32(val); } public QilLiteral Double(double val) { return _f.LiteralDouble(val); } public QilName QName(string local, string uri, string prefix) { return _f.LiteralQName(local, uri, prefix); } public QilName QName(string local, string uri) { return _f.LiteralQName(local, uri, string.Empty); } public QilName QName(string local) { return _f.LiteralQName(local, string.Empty, string.Empty); } public QilNode Unknown(XmlQueryType t) { return _f.Unknown(t); } #endregion #region meta //----------------------------------------------- // meta //----------------------------------------------- public QilExpression QilExpression(QilNode root, QilFactory factory) { return _f.QilExpression(root, factory); } public QilList FunctionList() { return _f.FunctionList(); } public QilList GlobalVariableList() { return _f.GlobalVariableList(); } public QilList GlobalParameterList() { return _f.GlobalParameterList(); } public QilList ActualParameterList() { return _f.ActualParameterList(); } public QilList ActualParameterList(QilNode arg1, QilNode arg2) { QilList result = _f.ActualParameterList(); result.Add(arg1); result.Add(arg2); return result; } public QilList ActualParameterList(params QilNode[] args) { return _f.ActualParameterList(args); } public QilList FormalParameterList() { return _f.FormalParameterList(); } public QilList FormalParameterList(QilNode arg1, QilNode arg2) { QilList result = _f.FormalParameterList(); result.Add(arg1); result.Add(arg2); return result; } public QilList FormalParameterList(params QilNode[] args) { return _f.FormalParameterList(args); } public QilList BranchList(params QilNode[] args) { return _f.BranchList(args); } public QilNode OptimizeBarrier(QilNode child) { return _f.OptimizeBarrier(child); } #endregion // meta #region specials //----------------------------------------------- // specials //----------------------------------------------- public QilNode DataSource(QilNode name, QilNode baseUri) { return _f.DataSource(name, baseUri); } public QilNode Nop(QilNode child) { return _f.Nop(child); } public QilNode Error(QilNode text) { return _f.Error(text); } public QilNode Warning(QilNode text) { return _f.Warning(text); } #endregion // specials #region variables //----------------------------------------------- // variables //----------------------------------------------- public QilIterator For(QilNode binding) { return _f.For(binding); } public QilIterator Let(QilNode binding) { return _f.Let(binding); } public QilParameter Parameter(XmlQueryType t) { return _f.Parameter(t); } public QilParameter Parameter(QilNode defaultValue, QilName name, XmlQueryType t) { return _f.Parameter(defaultValue, name, t); } public QilNode PositionOf(QilIterator expr) { return _f.PositionOf(expr); } #endregion // variables #region literals //----------------------------------------------- // literals //----------------------------------------------- public QilNode True() { return _f.True(); } public QilNode False() { return _f.False(); } public QilNode Boolean(bool b) { return b ? this.True() : this.False(); } #endregion // literals #region boolean operators //----------------------------------------------- // boolean operators //----------------------------------------------- private static void CheckLogicArg(QilNode arg) { Debug.Assert(arg != null, "Argument shouldn't be null"); Debug.Assert(arg.XmlType.TypeCode == XmlTypeCode.Boolean && arg.XmlType.IsSingleton, "The operand must be boolean-typed" ); } public QilNode And(QilNode left, QilNode right) { CheckLogicArg(left); CheckLogicArg(right); if (!_debug) { // True, True => True (right) other, True => other (left) // True, False => False (right) other, False => False (right) // True, other => other (right) other, other => And if (left.NodeType == QilNodeType.True || right.NodeType == QilNodeType.False) { return right; } if (left.NodeType == QilNodeType.False || right.NodeType == QilNodeType.True) { return left; } } return _f.And(left, right); } public QilNode Or(QilNode left, QilNode right) { CheckLogicArg(left); CheckLogicArg(right); if (!_debug) { // True, True => True (left) other, True => True (right) // True, False => True (left) other, False => other (left) // True, other => True (left) other, other => Or if (left.NodeType == QilNodeType.True || right.NodeType == QilNodeType.False) { return left; } if (left.NodeType == QilNodeType.False || right.NodeType == QilNodeType.True) { return right; } } return _f.Or(left, right); } public QilNode Not(QilNode child) { if (!_debug) { switch (child.NodeType) { case QilNodeType.True: return _f.False(); case QilNodeType.False: return _f.True(); case QilNodeType.Not: return ((QilUnary)child).Child; } } return _f.Not(child); } #endregion // boolean operators #region choice //----------------------------------------------- // choice //----------------------------------------------- public QilNode Conditional(QilNode condition, QilNode trueBranch, QilNode falseBranch) { if (!_debug) { switch (condition.NodeType) { case QilNodeType.True: return trueBranch; case QilNodeType.False: return falseBranch; case QilNodeType.Not: return this.Conditional(((QilUnary)condition).Child, falseBranch, trueBranch); } } return _f.Conditional(condition, trueBranch, falseBranch); } public QilNode Choice(QilNode expr, QilList branches) { if (!_debug) { switch (branches.Count) { case 1: // If expr has no side effects, it will be eliminated by optimizer return _f.Loop(_f.Let(expr), branches[0]); case 2: return _f.Conditional(_f.Eq(expr, _f.LiteralInt32(0)), branches[0], branches[1]); } } return _f.Choice(expr, branches); } #endregion // choice #region collection operators //----------------------------------------------- // collection operators //----------------------------------------------- public QilNode Length(QilNode child) { return _f.Length(child); } public QilNode Sequence() { return _f.Sequence(); } public QilNode Sequence(QilNode child) { if (!_debug) { return child; } QilList res = _f.Sequence(); res.Add(child); return res; } public QilNode Sequence(QilNode child1, QilNode child2) { QilList res = _f.Sequence(); res.Add(child1); res.Add(child2); return res; } public QilNode Sequence(params QilNode[] args) { if (!_debug) { switch (args.Length) { case 0: return _f.Sequence(); case 1: return args[0]; } } QilList res = _f.Sequence(); foreach (QilNode n in args) res.Add(n); return res; } public QilNode Union(QilNode left, QilNode right) { return _f.Union(left, right); } public QilNode Sum(QilNode collection) { return _f.Sum(collection); } #endregion // collection operators #region arithmetic operators //----------------------------------------------- // arithmetic operators //----------------------------------------------- public QilNode Negate(QilNode child) { return _f.Negate(child); } public QilNode Add(QilNode left, QilNode right) { return _f.Add(left, right); } public QilNode Subtract(QilNode left, QilNode right) { return _f.Subtract(left, right); } public QilNode Multiply(QilNode left, QilNode right) { return _f.Multiply(left, right); } public QilNode Divide(QilNode left, QilNode right) { return _f.Divide(left, right); } public QilNode Modulo(QilNode left, QilNode right) { return _f.Modulo(left, right); } #endregion // arithmetic operators #region string operators //----------------------------------------------- // string operators //----------------------------------------------- public QilNode StrLength(QilNode str) { return _f.StrLength(str); } public QilNode StrConcat(QilNode values) { if (!_debug) { if (values.XmlType.IsSingleton) return values; } return _f.StrConcat(values); } public QilNode StrConcat(params QilNode[] args) { return StrConcat((IList<QilNode>)args); } public QilNode StrConcat(IList<QilNode> args) { if (!_debug) { switch (args.Count) { case 0: return _f.LiteralString(string.Empty); case 1: return StrConcat(args[0]); } } return StrConcat(_f.Sequence(args)); } public QilNode StrParseQName(QilNode str, QilNode ns) { return _f.StrParseQName(str, ns); } #endregion // string operators #region value comparison operators //----------------------------------------------- // value comparison operators //----------------------------------------------- public QilNode Ne(QilNode left, QilNode right) { return _f.Ne(left, right); } public QilNode Eq(QilNode left, QilNode right) { return _f.Eq(left, right); } public QilNode Gt(QilNode left, QilNode right) { return _f.Gt(left, right); } public QilNode Ge(QilNode left, QilNode right) { return _f.Ge(left, right); } public QilNode Lt(QilNode left, QilNode right) { return _f.Lt(left, right); } public QilNode Le(QilNode left, QilNode right) { return _f.Le(left, right); } #endregion // value comparison operators #region node comparison operators //----------------------------------------------- // node comparison operators //----------------------------------------------- public QilNode Is(QilNode left, QilNode right) { return _f.Is(left, right); } public QilNode Before(QilNode left, QilNode right) { return _f.Before(left, right); } #endregion // node comparison operators #region loops //----------------------------------------------- // loops //----------------------------------------------- public QilNode Loop(QilIterator variable, QilNode body) { if (!_debug) { //((Loop (For $Binding) ($Binding) ) => ($binding)) if (body == variable.Binding) { return body; } } return _f.Loop(variable, body); } public QilNode Filter(QilIterator variable, QilNode expr) { if (!_debug) { //((Filter (For $Binding) (True ) ) => ($binding)) if (expr.NodeType == QilNodeType.True) { return variable.Binding; } // The following optimization is not safe if the iterator has side effects //((Filter (For $Binding) (False) ) => (Sequence)) } return _f.Filter(variable, expr); } #endregion // loops #region sorting //----------------------------------------------- // sorting //----------------------------------------------- public QilNode Sort(QilIterator iter, QilNode keys) { return _f.Sort(iter, keys); } public QilSortKey SortKey(QilNode key, QilNode collation) { return _f.SortKey(key, collation); } public QilNode DocOrderDistinct(QilNode collection) { if (collection.NodeType == QilNodeType.DocOrderDistinct) { return collection; } return _f.DocOrderDistinct(collection); } #endregion // sorting #region function definition and invocation //----------------------------------------------- // function definition and invocation //----------------------------------------------- public QilFunction Function(QilList args, QilNode sideEffects, XmlQueryType resultType) { Debug.Assert(args.NodeType == QilNodeType.FormalParameterList); return _f.Function(args, sideEffects, resultType); } public QilFunction Function(QilList args, QilNode defn, QilNode sideEffects) { Debug.Assert(args.NodeType == QilNodeType.FormalParameterList); return _f.Function(args, defn, sideEffects, defn.XmlType); } public QilNode Invoke(QilFunction func, QilList args) { Debug.Assert(args.NodeType == QilNodeType.ActualParameterList); Debug.Assert(func.Arguments.Count == args.Count); return _f.Invoke(func, args); } #endregion // function definition and invocation #region XML navigation //----------------------------------------------- // XML navigation //----------------------------------------------- public QilNode Content(QilNode context) { return _f.Content(context); } public QilNode Parent(QilNode context) { return _f.Parent(context); } public QilNode Root(QilNode context) { return _f.Root(context); } public QilNode XmlContext() { return _f.XmlContext(); } public QilNode Descendant(QilNode expr) { return _f.Descendant(expr); } public QilNode DescendantOrSelf(QilNode context) { return _f.DescendantOrSelf(context); } public QilNode Ancestor(QilNode expr) { return _f.Ancestor(expr); } public QilNode AncestorOrSelf(QilNode expr) { return _f.AncestorOrSelf(expr); } public QilNode Preceding(QilNode expr) { return _f.Preceding(expr); } public QilNode FollowingSibling(QilNode expr) { return _f.FollowingSibling(expr); } public QilNode PrecedingSibling(QilNode expr) { return _f.PrecedingSibling(expr); } public QilNode NodeRange(QilNode left, QilNode right) { return _f.NodeRange(left, right); } public QilBinary Deref(QilNode context, QilNode id) { return _f.Deref(context, id); } #endregion // XML navigation #region XML construction //----------------------------------------------- // XML construction //----------------------------------------------- public QilNode ElementCtor(QilNode name, QilNode content) { return _f.ElementCtor(name, content); } public QilNode AttributeCtor(QilNode name, QilNode val) { return _f.AttributeCtor(name, val); } public QilNode CommentCtor(QilNode content) { return _f.CommentCtor(content); } public QilNode PICtor(QilNode name, QilNode content) { return _f.PICtor(name, content); } public QilNode TextCtor(QilNode content) { return _f.TextCtor(content); } public QilNode RawTextCtor(QilNode content) { return _f.RawTextCtor(content); } public QilNode DocumentCtor(QilNode child) { return _f.DocumentCtor(child); } public QilNode NamespaceDecl(QilNode prefix, QilNode uri) { return _f.NamespaceDecl(prefix, uri); } public QilNode RtfCtor(QilNode content, QilNode baseUri) { return _f.RtfCtor(content, baseUri); } #endregion // XML construction #region Node properties //----------------------------------------------- // Node properties //----------------------------------------------- public QilNode NameOf(QilNode expr) { return _f.NameOf(expr); } public QilNode LocalNameOf(QilNode expr) { return _f.LocalNameOf(expr); } public QilNode NamespaceUriOf(QilNode expr) { return _f.NamespaceUriOf(expr); } public QilNode PrefixOf(QilNode expr) { return _f.PrefixOf(expr); } #endregion // Node properties #region Type operators //----------------------------------------------- // Type operators //----------------------------------------------- public QilNode TypeAssert(QilNode expr, XmlQueryType t) { return _f.TypeAssert(expr, t); } public QilNode IsType(QilNode expr, XmlQueryType t) { Debug.Assert(t != null, "Type can't be null"); return _f.IsType(expr, t); } public QilNode IsEmpty(QilNode set) { return _f.IsEmpty(set); } #endregion // Type operators #region XPath operators //----------------------------------------------- // XPath operators //----------------------------------------------- public QilNode XPathNodeValue(QilNode expr) { return _f.XPathNodeValue(expr); } public QilNode XPathFollowing(QilNode expr) { return _f.XPathFollowing(expr); } public QilNode XPathNamespace(QilNode expr) { return _f.XPathNamespace(expr); } public QilNode XPathPreceding(QilNode expr) { return _f.XPathPreceding(expr); } #endregion // XPath operators #region XSLT //----------------------------------------------- // XSLT //----------------------------------------------- public QilNode XsltGenerateId(QilNode expr) { return _f.XsltGenerateId(expr); } public QilNode XsltInvokeEarlyBound(QilNode name, MethodInfo d, XmlQueryType t, IList<QilNode> args) { QilList list = _f.ActualParameterList(); list.Add(args); return _f.XsltInvokeEarlyBound(name, _f.LiteralObject(d), list, t); } public QilNode XsltInvokeLateBound(QilNode name, IList<QilNode> args) { QilList list = _f.ActualParameterList(); list.Add(args); return _f.XsltInvokeLateBound(name, list); } public QilNode XsltCopy(QilNode expr, QilNode content) { return _f.XsltCopy(expr, content); } public QilNode XsltCopyOf(QilNode expr) { return _f.XsltCopyOf(expr); } public QilNode XsltConvert(QilNode expr, XmlQueryType t) { return _f.XsltConvert(expr, t); } #endregion // XSLT } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Encog.Util.CSV; using System.IO; using System.Globalization; namespace Encog.ML.Data.Market.Loader { public partial class CSVFormLoader : Form { string chosenfile = ""; public string Chosenfile { get { return chosenfile; } set { chosenfile = value; } } public CSVFormLoader() { InitializeComponent(); GetCSVFormats(); this.ShowDialog(); } CSVFormat currentFormat; public Encog.Util.CSV.CSVFormat CurrentFormat { get { return currentFormat; } set { currentFormat = value; } } Dictionary<string, CSVFormat> FormatDictionary = new Dictionary<string, CSVFormat>(); Dictionary<string, MarketDataType> MarketDataTypesToUse = new Dictionary<string, MarketDataType>(); string[] MarketDataTypesValues; public void GetCSVFormats() { FormatDictionary.Add("Decimal Point", CSVFormat.DecimalPoint); FormatDictionary.Add("Decimal Comma", CSVFormat.DecimalComma); FormatDictionary.Add("English Format", CSVFormat.English); FormatDictionary.Add("EG Format", CSVFormat.EgFormat); Array a = Enum.GetNames(typeof(MarketDataType)); MarketDataTypesValues = new string[a.Length]; int i = 0; foreach (string item in a) { MarketDataTypesValues[i] = item; i++; } return; } public CSVFormat format { get; set; } public List<MarketDataType> TypesLoaded = new List<MarketDataType>(); public List<MarketDataType> MarketTypesUsed { get { return TypesLoaded; } set { TypesLoaded = value; } } OpenFileDialog openFileDialog1; private void button1_Click(object sender, EventArgs e) { openFileDialog1 = new OpenFileDialog(); openFileDialog1.InitialDirectory = ("c:\\"); openFileDialog1.Filter = ("txt files (*.csv)|*.csv|All files (*.*)|*.*"); openFileDialog1.FilterIndex = (2); openFileDialog1.RestoreDirectory = (true); this.Visible = false; DialogResult result = this.openFileDialog1.ShowDialog(); // Show the dialog. if (result == DialogResult.OK) // Test result. { string file = openFileDialog1.FileName; try { Chosenfile = file; format = FormatDictionary[CSVFormatsCombo.Text]; foreach (string item in MarketDataTypesListBox.SelectedItems) { TypesLoaded.Add((MarketDataType) Enum.Parse(typeof(MarketDataType),item)); } ReadCSV csv = new ReadCSV(Chosenfile, true, format); var ColQuery = from Names in csv.ColumnNames select new {Names}; //ComboBox comboxTypes = new ComboBox(); // comboxTypes.Items.Add("DateTime"); // comboxTypes.Items.Add("Double"); // comboxTypes.Items.Add("Skip"); // comboxTypes.SelectedIndex = 0; // DataGridViewRow dr = new DataGridViewRow(); // DataGridViewComboBoxCell CellGrids = new DataGridViewComboBoxCell(); // foreach (string item in comboxTypes.Items) // { // CellGrids.Items.Add(item); // } // dr.Cells.Add(CellGrids); // //newColumnsSetup.dataGridView1.Rows.Add(dr); // DataGridViewColumn cols = new DataGridViewColumn(CellGrids); // cols.Name = "Combo"; // newColumnsSetup.dataGridView1.Columns.Add(cols); //DataGridViewColumn aCol = new DataGridViewColumn(); //foreach (DataGridViewRow item in newColumnsSetup.dataGridView1.Rows) //{ // DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)(item.Cells[0]); //} } catch (Exception ex) { toolStripStatusLabel1.Text = "Error Loading the CSV:" + ex.Message; } } } private void CSVFormLoader_Load(object sender, EventArgs e) { foreach (string item in FormatDictionary.Keys) { CSVFormatsCombo.Items.Add(item); } foreach (string item in MarketDataTypesValues) { MarketDataTypesListBox.Items.Add(item); } CSVFormatsCombo.SelectedIndex = 2; } private void button2_Click(object sender, EventArgs e) { Chosenfile = openFileDialog1.FileName; toolStripStatusLabel1.Text = " File:" + openFileDialog1.FileName + " has been successfully loaded"; } } }
using CoherentNoise.Interpolation; using UnityEngine; namespace CoherentNoise.Generation { /// <summary> /// Gradient noise is a smoother variant of coherent noise. Instead of assingning random values to integer points, it assigns random gradient vectros, and interpolates values /// between them. Resulting noise is smoother than value noise, as one more degree of continuity is achieved (i.e. gradient noise with linear interpolation has continuous 1st-order derivative) /// However, it is slower than value noise. /// /// This generator returns values in the [-1,1] range. /// </summary> public class GradientNoise : Generator { // 256 random vectors private static readonly float[] Vectors = new[] { -0.763874f, -0.596439f, -0.246489f, 0.396055f, 0.904518f, -0.158073f, -0.499004f, -0.8665f, -0.0131631f, 0.468724f, -0.824756f, 0.316346f, 0.829598f, 0.43195f, 0.353816f, -0.454473f, 0.629497f, -0.630228f, -0.162349f, -0.869962f, -0.465628f, 0.932805f, 0.253451f, 0.256198f, -0.345419f, 0.927299f, -0.144227f, -0.715026f, -0.293698f, -0.634413f, -0.245997f, 0.717467f, -0.651711f, -0.967409f, -0.250435f, -0.037451f, 0.901729f, 0.397108f, -0.170852f, 0.892657f, -0.0720622f, -0.444938f, 0.0260084f, -0.0361701f, 0.999007f, 0.949107f, -0.19486f, 0.247439f, 0.471803f, -0.807064f, -0.355036f, 0.879737f, 0.141845f, 0.453809f, 0.570747f, 0.696415f, 0.435033f, -0.141751f, -0.988233f, -0.0574584f, -0.58219f, -0.0303005f, 0.812488f, -0.60922f, 0.239482f, -0.755975f, 0.299394f, -0.197066f, -0.933557f, -0.851615f, -0.220702f, -0.47544f, 0.848886f, 0.341829f, -0.403169f, -0.156129f, -0.687241f, 0.709453f, -0.665651f, 0.626724f, 0.405124f, 0.595914f, -0.674582f, 0.43569f, 0.171025f, -0.509292f, 0.843428f, 0.78605f, 0.536414f, -0.307222f, 0.18905f, -0.791613f, 0.581042f, -0.294916f, 0.844994f, 0.446105f, 0.342031f, -0.58736f, -0.7335f, 0.57155f, 0.7869f, 0.232635f, 0.885026f, -0.408223f, 0.223791f, -0.789518f, 0.571645f, 0.223347f, 0.774571f, 0.31566f, 0.548087f, -0.79695f, -0.0433603f, -0.602487f, -0.142425f, -0.473249f, -0.869339f, -0.0698838f, 0.170442f, 0.982886f, 0.687815f, -0.484748f, 0.540306f, 0.543703f, -0.534446f, -0.647112f, 0.97186f, 0.184391f, -0.146588f, 0.707084f, 0.485713f, -0.513921f, 0.942302f, 0.331945f, 0.043348f, 0.499084f, 0.599922f, 0.625307f, -0.289203f, 0.211107f, 0.9337f, 0.412433f, -0.71667f, -0.56239f, 0.87721f, -0.082816f, 0.47291f, -0.420685f, -0.214278f, 0.881538f, 0.752558f, -0.0391579f, 0.657361f, 0.0765725f, -0.996789f, 0.0234082f, -0.544312f, -0.309435f, -0.779727f, -0.455358f, -0.415572f, 0.787368f, -0.874586f, 0.483746f, 0.0330131f, 0.245172f, -0.0838623f, 0.965846f, 0.382293f, -0.432813f, 0.81641f, -0.287735f, -0.905514f, 0.311853f, -0.667704f, 0.704955f, -0.239186f, 0.717885f, -0.464002f, -0.518983f, 0.976342f, -0.214895f, 0.0240053f, -0.0733096f, -0.921136f, 0.382276f, -0.986284f, 0.151224f, -0.0661379f, -0.899319f, -0.429671f, 0.0812908f, 0.652102f, -0.724625f, 0.222893f, 0.203761f, 0.458023f, -0.865272f, -0.030396f, 0.698724f, -0.714745f, -0.460232f, 0.839138f, 0.289887f, -0.0898602f, 0.837894f, 0.538386f, -0.731595f, 0.0793784f, 0.677102f, -0.447236f, -0.788397f, 0.422386f, 0.186481f, 0.645855f, -0.740335f, -0.259006f, 0.935463f, 0.240467f, 0.445839f, 0.819655f, -0.359712f, 0.349962f, 0.755022f, -0.554499f, -0.997078f, -0.0359577f, 0.0673977f, -0.431163f, -0.147516f, -0.890133f, 0.299648f, -0.63914f, 0.708316f, 0.397043f, 0.566526f, -0.722084f, -0.502489f, 0.438308f, -0.745246f, 0.0687235f, 0.354097f, 0.93268f, -0.0476651f, -0.462597f, 0.885286f, -0.221934f, 0.900739f, -0.373383f, -0.956107f, -0.225676f, 0.186893f, -0.187627f, 0.391487f, -0.900852f, -0.224209f, -0.315405f, 0.92209f, -0.730807f, -0.537068f, 0.421283f, -0.0353135f, -0.816748f, 0.575913f, -0.941391f, 0.176991f, -0.287153f, -0.154174f, 0.390458f, 0.90762f, -0.283847f, 0.533842f, 0.796519f, -0.482737f, -0.850448f, 0.209052f, -0.649175f, 0.477748f, 0.591886f, 0.885373f, -0.405387f, -0.227543f, -0.147261f, 0.181623f, -0.972279f, 0.0959236f, -0.115847f, -0.988624f, -0.89724f, -0.191348f, 0.397928f, 0.903553f, -0.428461f, -0.00350461f, 0.849072f, -0.295807f, -0.437693f, 0.65551f, 0.741754f, -0.141804f, 0.61598f, -0.178669f, 0.767232f, 0.0112967f, 0.932256f, -0.361623f, -0.793031f, 0.258012f, 0.551845f, 0.421933f, 0.454311f, 0.784585f, -0.319993f, 0.0401618f, -0.946568f, -0.81571f, 0.551307f, -0.175151f, -0.377644f, 0.00322313f, 0.925945f, 0.129759f, -0.666581f, -0.734052f, 0.601901f, -0.654237f, -0.457919f, -0.927463f, -0.0343576f, -0.372334f, -0.438663f, -0.868301f, -0.231578f, -0.648845f, -0.749138f, -0.133387f, 0.507393f, -0.588294f, 0.629653f, 0.726958f, 0.623665f, 0.287358f, 0.411159f, 0.367614f, -0.834151f, 0.806333f, 0.585117f, -0.0864016f, 0.263935f, -0.880876f, 0.392932f, 0.421546f, -0.201336f, 0.884174f, -0.683198f, -0.569557f, -0.456996f, -0.117116f, -0.0406654f, -0.992285f, -0.643679f, -0.109196f, -0.757465f, -0.561559f, -0.62989f, 0.536554f, 0.0628422f, 0.104677f, -0.992519f, 0.480759f, -0.2867f, -0.828658f, -0.228559f, -0.228965f, -0.946222f, -0.10194f, -0.65706f, -0.746914f, 0.0689193f, -0.678236f, 0.731605f, 0.401019f, -0.754026f, 0.52022f, -0.742141f, 0.547083f, -0.387203f, -0.00210603f, -0.796417f, -0.604745f, 0.296725f, -0.409909f, -0.862513f, -0.260932f, -0.798201f, 0.542945f, -0.641628f, 0.742379f, 0.192838f, -0.186009f, -0.101514f, 0.97729f, 0.106711f, -0.962067f, 0.251079f, -0.743499f, 0.30988f, -0.592607f, -0.795853f, -0.605066f, -0.0226607f, -0.828661f, -0.419471f, -0.370628f, 0.0847218f, -0.489815f, -0.8677f, -0.381405f, 0.788019f, -0.483276f, 0.282042f, -0.953394f, 0.107205f, 0.530774f, 0.847413f, 0.0130696f, 0.0515397f, 0.922524f, 0.382484f, -0.631467f, -0.709046f, 0.313852f, 0.688248f, 0.517273f, 0.508668f, 0.646689f, -0.333782f, -0.685845f, -0.932528f, -0.247532f, -0.262906f, 0.630609f, 0.68757f, -0.359973f, 0.577805f, -0.394189f, 0.714673f, -0.887833f, -0.437301f, -0.14325f, 0.690982f, 0.174003f, 0.701617f, -0.866701f, 0.0118182f, 0.498689f, -0.482876f, 0.727143f, 0.487949f, -0.577567f, 0.682593f, -0.447752f, 0.373768f, 0.0982991f, 0.922299f, 0.170744f, 0.964243f, -0.202687f, 0.993654f, -0.035791f, -0.106632f, 0.587065f, 0.4143f, -0.695493f, -0.396509f, 0.26509f, -0.878924f, -0.0866853f, 0.83553f, -0.542563f, 0.923193f, 0.133398f, -0.360443f, 0.00379108f, -0.258618f, 0.965972f, 0.239144f, 0.245154f, -0.939526f, 0.758731f, -0.555871f, 0.33961f, 0.295355f, 0.309513f, 0.903862f, 0.0531222f, -0.91003f, -0.411124f, 0.270452f, 0.0229439f, -0.96246f, 0.563634f, 0.0324352f, 0.825387f, 0.156326f, 0.147392f, 0.976646f, -0.0410141f, 0.981824f, 0.185309f, -0.385562f, -0.576343f, -0.720535f, 0.388281f, 0.904441f, 0.176702f, 0.945561f, -0.192859f, -0.262146f, 0.844504f, 0.520193f, 0.127325f, 0.0330893f, 0.999121f, -0.0257505f, -0.592616f, -0.482475f, -0.644999f, 0.539471f, 0.631024f, -0.557476f, 0.655851f, -0.027319f, -0.754396f, 0.274465f, 0.887659f, 0.369772f, -0.123419f, 0.975177f, -0.183842f, -0.223429f, 0.708045f, 0.66989f, -0.908654f, 0.196302f, 0.368528f, -0.95759f, -0.00863708f, 0.288005f, 0.960535f, 0.030592f, 0.276472f, -0.413146f, 0.907537f, 0.0754161f, -0.847992f, 0.350849f, -0.397259f, 0.614736f, 0.395841f, 0.68221f, -0.503504f, -0.666128f, -0.550234f, -0.268833f, -0.738524f, -0.618314f, 0.792737f, -0.60001f, -0.107502f, -0.637582f, 0.508144f, -0.579032f, 0.750105f, 0.282165f, -0.598101f, -0.351199f, -0.392294f, -0.850155f, 0.250126f, -0.960993f, -0.118025f, -0.732341f, 0.680909f, -0.0063274f, -0.760674f, -0.141009f, 0.633634f, 0.222823f, -0.304012f, 0.926243f, 0.209178f, 0.505671f, 0.836984f, 0.757914f, -0.56629f, -0.323857f, -0.782926f, -0.339196f, 0.52151f, -0.462952f, 0.585565f, 0.665424f, 0.61879f, 0.194119f, -0.761194f, 0.741388f, -0.276743f, 0.611357f, 0.707571f, 0.702621f, 0.0752872f, 0.156562f, 0.819977f, 0.550569f, -0.793606f, 0.440216f, 0.42f, 0.234547f, 0.885309f, -0.401517f, 0.132598f, 0.80115f, -0.58359f, -0.377899f, -0.639179f, 0.669808f, -0.865993f, -0.396465f, 0.304748f, -0.624815f, -0.44283f, 0.643046f, -0.485705f, 0.825614f, -0.287146f, -0.971788f, 0.175535f, 0.157529f, -0.456027f, 0.392629f, 0.798675f, -0.0104443f, 0.521623f, -0.853112f, -0.660575f, -0.74519f, 0.091282f, -0.0157698f, -0.307475f, -0.951425f, -0.603467f, -0.250192f, 0.757121f, 0.506876f, 0.25006f, 0.824952f, 0.255404f, 0.966794f, 0.00884498f, 0.466764f, -0.874228f, -0.133625f, 0.475077f, -0.0682351f, -0.877295f, -0.224967f, -0.938972f, -0.260233f, -0.377929f, -0.814757f, -0.439705f, -0.305847f, 0.542333f, -0.782517f, 0.26658f, -0.902905f, -0.337191f, 0.0275773f, 0.322158f, -0.946284f, 0.0185422f, 0.716349f, 0.697496f, -0.20483f, 0.978416f, 0.0273371f, -0.898276f, 0.373969f, 0.230752f, -0.00909378f, 0.546594f, 0.837349f, 0.6602f, -0.751089f, 0.000959236f, 0.855301f, -0.303056f, 0.420259f, 0.797138f, 0.0623013f, -0.600574f, 0.48947f, -0.866813f, 0.0951509f, 0.251142f, 0.674531f, 0.694216f, -0.578422f, -0.737373f, -0.348867f, -0.254689f, -0.514807f, 0.818601f, 0.374972f, 0.761612f, 0.528529f, 0.640303f, -0.734271f, -0.225517f, -0.638076f, 0.285527f, 0.715075f, 0.772956f, -0.15984f, -0.613995f, 0.798217f, -0.590628f, 0.118356f, -0.986276f, -0.0578337f, -0.154644f, -0.312988f, -0.94549f, 0.0899272f, -0.497338f, 0.178325f, 0.849032f, -0.101136f, -0.981014f, 0.165477f, -0.521688f, 0.0553434f, -0.851339f, -0.786182f, -0.583814f, 0.202678f, -0.565191f, 0.821858f, -0.0714658f, 0.437895f, 0.152598f, -0.885981f, -0.92394f, 0.353436f, -0.14635f, 0.212189f, -0.815162f, -0.538969f, -0.859262f, 0.143405f, -0.491024f, 0.991353f, 0.112814f, 0.0670273f, 0.0337884f, -0.979891f, -0.196654f, }; private readonly int m_Seed; private readonly SCurve m_SCurve; /// <summary> /// Create new generator with specified seed /// </summary> /// <param name="seed">noise seed</param> public GradientNoise(int seed) : this(seed, null) { } /// <summary> /// Create new generator with specified seed and interpolation algorithm. Different interpolation algorithms can make noise smoother at the expense of speed. /// </summary> /// <param name="seed">noise seed</param> /// <param name="sCurve">Interpolator to use. Can be null, in which case default will be used</param> public GradientNoise(int seed, SCurve sCurve) { m_Seed = seed; m_SCurve = sCurve; } /// <summary> /// Noise period. Used for repeating (seamless) noise. /// When Period &gt;0 resulting noise pattern repeats exactly every Period, for all coordinates. /// </summary> public int Period { get; set; } private SCurve SCurve { get { return m_SCurve ?? SCurve.Default; } } #region Implementation of Noise /// <summary> /// Returns noise value at given point. /// </summary> /// <param name="x">X coordinate</param> /// <param name="y">Y coordinate</param> /// <param name="z">Z coordinate</param> /// <returns>Noise value</returns> public override float GetValue(float x, float y, float z) { int ix = Mathf.FloorToInt(x); int iy = Mathf.FloorToInt(y); int iz = Mathf.FloorToInt(z); // interpolate the coordinates instead of values - this way we need only 4 calls instead of 7 float xs = SCurve.Interpolate(x - ix); float ys = SCurve.Interpolate(y - iy); float zs = SCurve.Interpolate(z - iz); // THEN we can use linear interp to find our value - triliear actually float n0 = GetNoise(x, y, z, ix, iy, iz); float n1 = GetNoise(x, y, z, ix + 1, iy, iz); float ix0 = Mathf.Lerp(n0, n1, xs); n0 = GetNoise(x, y, z, ix, iy + 1, iz); n1 = GetNoise(x, y, z, ix + 1, iy + 1, iz); float ix1 = Mathf.Lerp(n0, n1, xs); float iy0 = Mathf.Lerp(ix0, ix1, ys); n0 = GetNoise(x, y, z, ix, iy, iz + 1); n1 = GetNoise(x, y, z, ix + 1, iy, iz + 1); ix0 = Mathf.Lerp(n0, n1, xs); // on y=0, z=1 edge n0 = GetNoise(x, y, z, ix, iy + 1, iz + 1); n1 = GetNoise(x, y, z, ix + 1, iy + 1, iz + 1); ix1 = Mathf.Lerp(n0, n1, xs); // on y=z=1 edge float iy1 = Mathf.Lerp(ix0, ix1, ys); return Mathf.Lerp(iy0, iy1, zs); // inside cube } } Vector3 GetRandomVector(int x, int y, int z) { if (Period > 0) { // make periodic lattice. Repeat every Period cells x = x % Period; if (x < 0) x += Period; y = y % Period; if (y < 0) y += Period; z = z % Period; if (z < 0) z += Period; } int vectorIndex = ( Constants.MultiplierX * x + Constants.MultiplierY * y + Constants.MultiplierZ * z + Constants.MultiplierSeed * m_Seed) & 0x7fffffff; vectorIndex = (((vectorIndex >> Constants.ValueShift) ^ vectorIndex) & 0xff) * 3; return new Vector3(Vectors[vectorIndex], Vectors[vectorIndex + 1], Vectors[vectorIndex + 2]); } private float GetNoise(float x, float y, float z, int ix, int iy, int iz) { var gradient = GetRandomVector(ix, iy, iz); return Vector3.Dot(gradient, new Vector3(x - ix, y - iy, z - iz)) * 2.12f; // scale to [-1,1] } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal abstract partial class AbstractEditorInlineRenameService { /// <summary> /// Represents information about the ability to rename a particular location. /// </summary> private partial class SymbolInlineRenameInfo : IInlineRenameInfo { private const string AttributeSuffix = "Attribute"; private readonly object _gate = new object(); private readonly Document _document; private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices; private Task<RenameLocations> _underlyingFindRenameLocationsTask; /// <summary> /// Whether or not we shortened the trigger span (say because we were renaming an attribute, /// and we didn't select the 'Attribute' portion of the name. /// </summary> private readonly bool _shortenedTriggerSpan; private readonly bool _isRenamingAttributePrefix; public bool CanRename { get; } public string LocalizedErrorMessage { get; } public TextSpan TriggerSpan { get; } public ISymbol RenameSymbol { get; } public bool HasOverloads { get; } public bool ForceRenameOverloads { get; } public SymbolInlineRenameInfo( IEnumerable<IRefactorNotifyService> refactorNotifyServices, Document document, TextSpan triggerSpan, ISymbol renameSymbol, bool forceRenameOverloads, CancellationToken cancellationToken) { this.CanRename = true; _refactorNotifyServices = refactorNotifyServices; _document = document; this.RenameSymbol = renameSymbol; this.HasOverloads = RenameLocations.GetOverloadedSymbols(this.RenameSymbol).Any(); this.ForceRenameOverloads = forceRenameOverloads; _isRenamingAttributePrefix = CanRenameAttributePrefix(document, triggerSpan, cancellationToken); this.TriggerSpan = GetReferenceEditSpan(new InlineRenameLocation(document, triggerSpan), cancellationToken); _shortenedTriggerSpan = this.TriggerSpan != triggerSpan; } private bool CanRenameAttributePrefix(Document document, TextSpan triggerSpan, CancellationToken cancellationToken) { // if this isn't an attribute, or it doesn't have the 'Attribute' suffix, then clearly // we can't rename just the attribute prefix. if (!this.IsRenamingAttributeTypeWithAttributeSuffix()) { return false; } // Ok, the symbol is good. Now, make sure that the trigger text starts with the prefix // of the attribute. If it does, then we can rename just the attribute prefix (otherwise // we need to rename the entire attribute). var nameWithoutAttribute = this.RenameSymbol.Name.GetWithoutAttributeSuffix(isCaseSensitive: true); var triggerText = GetSpanText(document, triggerSpan, cancellationToken); return triggerText.StartsWith(triggerText); // TODO: Always true? What was it supposed to do? } /// <summary> /// Given a span of text, we need to return the subspan that is editable and /// contains the current replacementText. /// /// These cases are currently handled: /// - Escaped identifiers [foo] => foo /// - Type suffixes in VB foo$ => foo /// - Qualified names from complexification A.foo => foo /// - Optional Attribute suffixes XAttribute => X /// Careful here: XAttribute => XAttribute if renamesymbol is XAttributeAttribute /// - Compiler-generated EventHandler suffix XEventHandler => X /// - Compiler-generated get_ and set_ prefixes get_X => X /// </summary> public TextSpan GetReferenceEditSpan(InlineRenameLocation location, CancellationToken cancellationToken) { var searchName = this.RenameSymbol.Name; if (_isRenamingAttributePrefix) { // We're only renaming the attribute prefix part. We want to adjust the span of // the reference we've found to only update the prefix portion. searchName = GetWithoutAttributeSuffix(this.RenameSymbol.Name); } var spanText = GetSpanText(location.Document, location.TextSpan, cancellationToken); var index = spanText.LastIndexOf(searchName, StringComparison.Ordinal); if (index < 0) { // Couldn't even find the search text at this reference location. This might happen // if the user used things like unicode escapes. IN that case, we'll have to rename // the entire identifier. return location.TextSpan; } return new TextSpan(location.TextSpan.Start + index, searchName.Length); } public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string replacementText, CancellationToken cancellationToken) { var spanText = GetSpanText(location.Document, location.TextSpan, cancellationToken); var position = spanText.LastIndexOf(replacementText, StringComparison.Ordinal); if (_isRenamingAttributePrefix) { // We're only renaming the attribute prefix part. We want to adjust the span of // the reference we've found to only update the prefix portion. var index = spanText.LastIndexOf(replacementText + AttributeSuffix, StringComparison.Ordinal); position = index >= 0 ? index : position; } if (position < 0) { return null; } return new TextSpan(location.TextSpan.Start + position, replacementText.Length); } private static string GetSpanText(Document document, TextSpan triggerSpan, CancellationToken cancellationToken) { var sourceText = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); var triggerText = sourceText.ToString(triggerSpan); return triggerText; } private static string GetWithoutAttributeSuffix(string value) { return value.GetWithoutAttributeSuffix(isCaseSensitive: true); } internal bool IsRenamingAttributeTypeWithAttributeSuffix() { if (this.RenameSymbol.IsAttribute() || (this.RenameSymbol.Kind == SymbolKind.Alias && ((IAliasSymbol)this.RenameSymbol).Target.IsAttribute())) { var name = this.RenameSymbol.Name; if (name.TryGetWithoutAttributeSuffix(isCaseSensitive: true, result: out name)) { return true; } } return false; } public string DisplayName { get { return this.RenameSymbol.Name; } } public string FullDisplayName { get { return this.RenameSymbol.ToDisplayString(); } } public Glyph Glyph { get { return this.RenameSymbol.GetGlyph(); } } public string GetFinalSymbolName(string replacementText) { if (_isRenamingAttributePrefix) { return replacementText + AttributeSuffix; } return replacementText; } public Task<IInlineRenameLocationSet> FindRenameLocationsAsync(OptionSet optionSet, CancellationToken cancellationToken) { Task<RenameLocations> renameTask; lock (_gate) { if (_underlyingFindRenameLocationsTask == null) { // If this is the first call, then just start finding the initial set of rename // locations. _underlyingFindRenameLocationsTask = RenameLocations.FindAsync( this.RenameSymbol, _document.Project.Solution, optionSet, cancellationToken); renameTask = _underlyingFindRenameLocationsTask; // null out the option set. We don't need it anymore, and this will ensure // we don't call FindWithUpdatedOptionsAsync below. optionSet = null; } else { // We already have a task to figure out the set of rename locations. Let it // finish, then ask it to get the rename locations with the updated options. renameTask = _underlyingFindRenameLocationsTask; } } return GetLocationSet(renameTask, optionSet, cancellationToken); } private async Task<IInlineRenameLocationSet> GetLocationSet(Task<RenameLocations> renameTask, OptionSet optionSet, CancellationToken cancellationToken) { var locationSet = await renameTask.ConfigureAwait(false); if (optionSet != null) { locationSet = await locationSet.FindWithUpdatedOptionsAsync(optionSet, cancellationToken).ConfigureAwait(false); } return new InlineRenameLocationSet(this, locationSet); } public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) { return _refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocumentIDs, RenameSymbol, this.GetFinalSymbolName(replacementText), throwOnFailure: false); } public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) { return _refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocumentIDs, RenameSymbol, this.GetFinalSymbolName(replacementText), throwOnFailure: false); } } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 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. *******************************************************************************/ // // Novell.Directory.Ldap.LdapControl.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using Novell.Directory.LDAP.VQ.Asn1; using Novell.Directory.LDAP.VQ.Rfc2251; using Novell.Directory.LDAP.VQ.Utilclass; namespace Novell.Directory.LDAP.VQ { /// <summary> Encapsulates optional additional parameters or constraints to be applied to /// an Ldap operation. /// /// When included with LdapConstraints or LdapSearchConstraints /// on an LdapConnection or with a specific operation request, it is /// sent to the server along with operation requests. /// /// </summary> /// <seealso cref="LdapConnection.ResponseControls"> /// </seealso> /// <seealso cref="LdapConstraints.getControls"> /// </seealso> /// <seealso cref="LdapConstraints.setControls"> /// </seealso> public class LdapControl { /// <summary> Returns the identifier of the control. /// /// </summary> /// <returns> The object ID of the control. /// </returns> virtual public string ID { get { return new System.Text.StringBuilder(control.ControlType.stringValue()).ToString(); } } /// <summary> Returns whether the control is critical for the operation. /// /// </summary> /// <returns> Returns true if the control must be supported for an associated /// operation to be executed, and false if the control is not required for /// the operation. /// </returns> virtual public bool Critical { get { return control.Criticality.booleanValue(); } } internal static RespControlVector RegisteredControls { /* package */ get { return registeredControls; } } /// <summary> Returns the RFC 2251 Control object. /// /// </summary> /// <returns> An ASN.1 RFC 2251 Control. /// </returns> virtual internal RfcControl Asn1Object { /*package*/ get { return control; } } private static RespControlVector registeredControls; private RfcControl control; // An RFC 2251 Control /// <summary> Constructs a new LdapControl object using the specified values. /// /// </summary> /// <param name="oid"> The OID of the control, as a dotted string. /// /// </param> /// <param name="critical"> True if the Ldap operation should be discarded if /// the control is not supported. False if /// the operation can be processed without the control. /// /// </param> /// <param name="values"> The control-specific data. /// </param> [CLSCompliant(false)] public LdapControl(string oid, bool critical, sbyte[] values) { if ((object)oid == null) { throw new ArgumentException("An OID must be specified"); } if (values == null) { control = new RfcControl(new RfcLdapOID(oid), new Asn1Boolean(critical)); } else { control = new RfcControl(new RfcLdapOID(oid), new Asn1Boolean(critical), new Asn1OctetString(values)); } return; } /// <summary> Create an LdapControl from an existing control.</summary> protected internal LdapControl(RfcControl control) { this.control = control; } /// <summary> Returns a copy of the current LdapControl object. /// /// </summary> /// <returns> A copy of the current LdapControl object. /// </returns> public object Clone() { LdapControl cont; try { cont = (LdapControl)MemberwiseClone(); } catch (Exception ce) { throw new Exception("Internal error, cannot create clone"); } sbyte[] vals = getValue(); sbyte[] twin = null; if (vals != null) { //is this necessary? // Yes even though the contructor above allocates a // new Asn1OctetString, vals in that constuctor // is only copied by reference twin = new sbyte[vals.Length]; for (int i = 0; i < vals.Length; i++) { twin[i] = vals[i]; } cont.control = new RfcControl(new RfcLdapOID(ID), new Asn1Boolean(Critical), new Asn1OctetString(twin)); } return cont; } /// <summary> Returns the control-specific data of the object. /// /// </summary> /// <returns> The control-specific data of the object as a byte array, /// or null if the control has no data. /// </returns> [CLSCompliant(false)] public virtual sbyte[] getValue() { sbyte[] result = null; Asn1OctetString val = control.ControlValue; if (val != null) { result = val.byteValue(); } return result; } /// <summary> Sets the control-specific data of the object. This method is for /// use by an extension of LdapControl. /// </summary> [CLSCompliant(false)] protected internal virtual void setValue(sbyte[] controlValue) { control.ControlValue = new Asn1OctetString(controlValue); } /// <summary> Registers a class to be instantiated on receipt of a control with the /// given OID. /// /// Any previous registration for the OID is overridden. The /// controlClass must be an extension of LdapControl. /// /// </summary> /// <param name="oid"> The object identifier of the control. /// /// </param> /// <param name="controlClass"> A class which can instantiate an LdapControl. /// </param> public static void register(string oid, Type controlClass) { registeredControls.registerResponseControl(oid, controlClass); } static LdapControl() { registeredControls = new RespControlVector(5, 5); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using FluentAssertions.Common; using FluentAssertions.Execution; namespace FluentAssertions.Types { #pragma warning disable CS0659 // Ignore not overriding Object.GetHashCode() #pragma warning disable CA1065 // Ignore throwing NotSupportedException from Equals /// <summary> /// Contains assertions for the <see cref="PropertyInfo"/> objects returned by the parent <see cref="PropertyInfoSelector"/>. /// </summary> [DebuggerNonUserCode] public class PropertyInfoSelectorAssertions { /// <summary> /// Gets the object which value is being asserted. /// </summary> public IEnumerable<PropertyInfo> SubjectProperties { get; } /// <summary> /// Initializes a new instance of the <see cref="PropertyInfoSelectorAssertions"/> class, for a number of <see cref="PropertyInfo"/> objects. /// </summary> /// <param name="properties">The properties to assert.</param> /// <exception cref="ArgumentNullException"><paramref name="properties"/> is <c>null</c>.</exception> public PropertyInfoSelectorAssertions(params PropertyInfo[] properties) { Guard.ThrowIfArgumentIsNull(properties, nameof(properties)); SubjectProperties = properties; } /// <summary> /// Asserts that the selected properties are virtual. /// </summary> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <paramref name="because" />. /// </param> public AndConstraint<PropertyInfoSelectorAssertions> BeVirtual(string because = "", params object[] becauseArgs) { PropertyInfo[] nonVirtualProperties = GetAllNonVirtualPropertiesFromSelection(); Execute.Assertion .ForCondition(!nonVirtualProperties.Any()) .BecauseOf(because, becauseArgs) .FailWith( "Expected all selected properties to be virtual{reason}, but the following properties are not virtual:" + Environment.NewLine + GetDescriptionsFor(nonVirtualProperties)); return new AndConstraint<PropertyInfoSelectorAssertions>(this); } /// <summary> /// Asserts that the selected properties are not virtual. /// </summary> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <paramref name="because" />. /// </param> public AndConstraint<PropertyInfoSelectorAssertions> NotBeVirtual(string because = "", params object[] becauseArgs) { PropertyInfo[] virtualProperties = GetAllVirtualPropertiesFromSelection(); Execute.Assertion .ForCondition(!virtualProperties.Any()) .BecauseOf(because, becauseArgs) .FailWith( "Expected all selected properties not to be virtual{reason}, but the following properties are virtual:" + Environment.NewLine + GetDescriptionsFor(virtualProperties)); return new AndConstraint<PropertyInfoSelectorAssertions>(this); } /// <summary> /// Asserts that the selected properties have a setter. /// </summary> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <paramref name="because" />. /// </param> public AndConstraint<PropertyInfoSelectorAssertions> BeWritable(string because = "", params object[] becauseArgs) { PropertyInfo[] readOnlyProperties = GetAllReadOnlyPropertiesFromSelection(); Execute.Assertion .ForCondition(!readOnlyProperties.Any()) .BecauseOf(because, becauseArgs) .FailWith( "Expected all selected properties to have a setter{reason}, but the following properties do not:" + Environment.NewLine + GetDescriptionsFor(readOnlyProperties)); return new AndConstraint<PropertyInfoSelectorAssertions>(this); } /// <summary> /// Asserts that the selected properties do not have a setter. /// </summary> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <paramref name="because" />. /// </param> public AndConstraint<PropertyInfoSelectorAssertions> NotBeWritable(string because = "", params object[] becauseArgs) { PropertyInfo[] writableProperties = GetAllWritablePropertiesFromSelection(); Execute.Assertion .ForCondition(!writableProperties.Any()) .BecauseOf(because, becauseArgs) .FailWith( "Expected selected properties to not have a setter{reason}, but the following properties do:" + Environment.NewLine + GetDescriptionsFor(writableProperties)); return new AndConstraint<PropertyInfoSelectorAssertions>(this); } private PropertyInfo[] GetAllReadOnlyPropertiesFromSelection() { return SubjectProperties.Where(property => !property.CanWrite).ToArray(); } private PropertyInfo[] GetAllWritablePropertiesFromSelection() { return SubjectProperties.Where(property => property.CanWrite).ToArray(); } private PropertyInfo[] GetAllNonVirtualPropertiesFromSelection() { return SubjectProperties.Where(property => !property.IsVirtual()).ToArray(); } private PropertyInfo[] GetAllVirtualPropertiesFromSelection() { return SubjectProperties.Where(property => property.IsVirtual()).ToArray(); } /// <summary> /// Asserts that the selected properties are decorated with the specified <typeparamref name="TAttribute"/>. /// </summary> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <paramref name="because" />. /// </param> public AndConstraint<PropertyInfoSelectorAssertions> BeDecoratedWith<TAttribute>(string because = "", params object[] becauseArgs) where TAttribute : Attribute { PropertyInfo[] propertiesWithoutAttribute = GetPropertiesWithout<TAttribute>(); Execute.Assertion .ForCondition(!propertiesWithoutAttribute.Any()) .BecauseOf(because, becauseArgs) .FailWith( "Expected all selected properties to be decorated with {0}{reason}" + ", but the following properties are not:" + Environment.NewLine + GetDescriptionsFor(propertiesWithoutAttribute), typeof(TAttribute)); return new AndConstraint<PropertyInfoSelectorAssertions>(this); } /// <summary> /// Asserts that the selected properties are not decorated with the specified <typeparamref name="TAttribute"/>. /// </summary> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <paramref name="because" />. /// </param> public AndConstraint<PropertyInfoSelectorAssertions> NotBeDecoratedWith<TAttribute>(string because = "", params object[] becauseArgs) where TAttribute : Attribute { PropertyInfo[] propertiesWithAttribute = GetPropertiesWith<TAttribute>(); Execute.Assertion .ForCondition(!propertiesWithAttribute.Any()) .BecauseOf(because, becauseArgs) .FailWith( "Expected all selected properties not to be decorated with {0}{reason}" + ", but the following properties are:" + Environment.NewLine + GetDescriptionsFor(propertiesWithAttribute), typeof(TAttribute)); return new AndConstraint<PropertyInfoSelectorAssertions>(this); } private PropertyInfo[] GetPropertiesWithout<TAttribute>() where TAttribute : Attribute { return SubjectProperties.Where(property => !property.IsDecoratedWith<TAttribute>()).ToArray(); } private PropertyInfo[] GetPropertiesWith<TAttribute>() where TAttribute : Attribute { return SubjectProperties.Where(property => property.IsDecoratedWith<TAttribute>()).ToArray(); } private static string GetDescriptionsFor(IEnumerable<PropertyInfo> properties) { IEnumerable<string> descriptions = properties.Select(property => PropertyInfoAssertions.GetDescriptionFor(property)); return string.Join(Environment.NewLine, descriptions); } /// <summary> /// Returns the type of the subject the assertion applies on. /// </summary> #pragma warning disable CA1822 // Do not change signature of a public member protected string Context => "property info"; #pragma warning restore CA1822 /// <inheritdoc/> public override bool Equals(object obj) => throw new NotSupportedException("Calling Equals on Assertion classes is not supported."); } }
// 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.Cryptography.Xml { public sealed partial class CipherData { public CipherData() { } public CipherData(byte[] cipherValue) { } public CipherData(System.Security.Cryptography.Xml.CipherReference cipherReference) { } public System.Security.Cryptography.Xml.CipherReference CipherReference { get { throw null; } set { } } public byte[] CipherValue { get { throw null; } set { } } public System.Xml.XmlElement GetXml() { throw null; } public void LoadXml(System.Xml.XmlElement value) { } } public sealed partial class CipherReference : System.Security.Cryptography.Xml.EncryptedReference { public CipherReference() { } public CipherReference(string uri) { } public CipherReference(string uri, System.Security.Cryptography.Xml.TransformChain transformChain) { } public override System.Xml.XmlElement GetXml() { throw null; } public override void LoadXml(System.Xml.XmlElement value) { } } public partial class DataObject { public DataObject() { } public DataObject(string id, string mimeType, string encoding, System.Xml.XmlElement data) { } public System.Xml.XmlNodeList Data { get { throw null; } set { } } public string Encoding { get { throw null; } set { } } public string Id { get { throw null; } set { } } public string MimeType { get { throw null; } set { } } public System.Xml.XmlElement GetXml() { throw null; } public void LoadXml(System.Xml.XmlElement value) { } } public sealed partial class DataReference : System.Security.Cryptography.Xml.EncryptedReference { public DataReference() { } public DataReference(string uri) { } public DataReference(string uri, System.Security.Cryptography.Xml.TransformChain transformChain) { } } public partial class DSAKeyValue : System.Security.Cryptography.Xml.KeyInfoClause { public DSAKeyValue() { } public DSAKeyValue(System.Security.Cryptography.DSA key) { } public System.Security.Cryptography.DSA Key { get { throw null; } set { } } public override System.Xml.XmlElement GetXml() { throw null; } public override void LoadXml(System.Xml.XmlElement value) { } } public sealed partial class EncryptedData : System.Security.Cryptography.Xml.EncryptedType { public EncryptedData() { } public override System.Xml.XmlElement GetXml() { throw null; } public override void LoadXml(System.Xml.XmlElement value) { } } public sealed partial class EncryptedKey : System.Security.Cryptography.Xml.EncryptedType { public EncryptedKey() { } public string CarriedKeyName { get { throw null; } set { } } public string Recipient { get { throw null; } set { } } public System.Security.Cryptography.Xml.ReferenceList ReferenceList { get { throw null; } } public void AddReference(System.Security.Cryptography.Xml.DataReference dataReference) { } public void AddReference(System.Security.Cryptography.Xml.KeyReference keyReference) { } public override System.Xml.XmlElement GetXml() { throw null; } public override void LoadXml(System.Xml.XmlElement value) { } } public abstract partial class EncryptedReference { protected EncryptedReference() { } protected EncryptedReference(string uri) { } protected EncryptedReference(string uri, System.Security.Cryptography.Xml.TransformChain transformChain) { } protected internal bool CacheValid { get { throw null; } } protected string ReferenceType { get { throw null; } set { } } public System.Security.Cryptography.Xml.TransformChain TransformChain { get { throw null; } set { } } public string Uri { get { throw null; } set { } } public void AddTransform(System.Security.Cryptography.Xml.Transform transform) { } public virtual System.Xml.XmlElement GetXml() { throw null; } public virtual void LoadXml(System.Xml.XmlElement value) { } } public abstract partial class EncryptedType { protected EncryptedType() { } public virtual System.Security.Cryptography.Xml.CipherData CipherData { get { throw null; } set { } } public virtual string Encoding { get { throw null; } set { } } public virtual System.Security.Cryptography.Xml.EncryptionMethod EncryptionMethod { get { throw null; } set { } } public virtual System.Security.Cryptography.Xml.EncryptionPropertyCollection EncryptionProperties { get { throw null; } } public virtual string Id { get { throw null; } set { } } public System.Security.Cryptography.Xml.KeyInfo KeyInfo { get { throw null; } set { } } public virtual string MimeType { get { throw null; } set { } } public virtual string Type { get { throw null; } set { } } public void AddProperty(System.Security.Cryptography.Xml.EncryptionProperty ep) { } public abstract System.Xml.XmlElement GetXml(); public abstract void LoadXml(System.Xml.XmlElement value); } public partial class EncryptedXml { public const string XmlEncAES128KeyWrapUrl = "http://www.w3.org/2001/04/xmlenc#kw-aes128"; public const string XmlEncAES128Url = "http://www.w3.org/2001/04/xmlenc#aes128-cbc"; public const string XmlEncAES192KeyWrapUrl = "http://www.w3.org/2001/04/xmlenc#kw-aes192"; public const string XmlEncAES192Url = "http://www.w3.org/2001/04/xmlenc#aes192-cbc"; public const string XmlEncAES256KeyWrapUrl = "http://www.w3.org/2001/04/xmlenc#kw-aes256"; public const string XmlEncAES256Url = "http://www.w3.org/2001/04/xmlenc#aes256-cbc"; public const string XmlEncDESUrl = "http://www.w3.org/2001/04/xmlenc#des-cbc"; public const string XmlEncElementContentUrl = "http://www.w3.org/2001/04/xmlenc#Content"; public const string XmlEncElementUrl = "http://www.w3.org/2001/04/xmlenc#Element"; public const string XmlEncEncryptedKeyUrl = "http://www.w3.org/2001/04/xmlenc#EncryptedKey"; public const string XmlEncNamespaceUrl = "http://www.w3.org/2001/04/xmlenc#"; public const string XmlEncRSA15Url = "http://www.w3.org/2001/04/xmlenc#rsa-1_5"; public const string XmlEncRSAOAEPUrl = "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"; public const string XmlEncSHA256Url = "http://www.w3.org/2001/04/xmlenc#sha256"; public const string XmlEncSHA512Url = "http://www.w3.org/2001/04/xmlenc#sha512"; public const string XmlEncTripleDESKeyWrapUrl = "http://www.w3.org/2001/04/xmlenc#kw-tripledes"; public const string XmlEncTripleDESUrl = "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"; public EncryptedXml() { } public EncryptedXml(System.Xml.XmlDocument document) { } public EncryptedXml(System.Xml.XmlDocument document, System.Security.Policy.Evidence evidence) { } public System.Security.Policy.Evidence DocumentEvidence { get { throw null; } set { } } public System.Text.Encoding Encoding { get { throw null; } set { } } public System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } } public System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } } public string Recipient { get { throw null; } set { } } public System.Xml.XmlResolver Resolver { get { throw null; } set { } } public int XmlDSigSearchDepth { get { throw null; } set { } } public void AddKeyNameMapping(string keyName, object keyObject) { } public void ClearKeyNameMappings() { } public byte[] DecryptData(System.Security.Cryptography.Xml.EncryptedData encryptedData, System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm) { throw null; } public void DecryptDocument() { } public virtual byte[] DecryptEncryptedKey(System.Security.Cryptography.Xml.EncryptedKey encryptedKey) { throw null; } public static byte[] DecryptKey(byte[] keyData, System.Security.Cryptography.RSA rsa, bool useOAEP) { throw null; } public static byte[] DecryptKey(byte[] keyData, System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm) { throw null; } public System.Security.Cryptography.Xml.EncryptedData Encrypt(System.Xml.XmlElement inputElement, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public System.Security.Cryptography.Xml.EncryptedData Encrypt(System.Xml.XmlElement inputElement, string keyName) { throw null; } public byte[] EncryptData(byte[] plaintext, System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm) { throw null; } public byte[] EncryptData(System.Xml.XmlElement inputElement, System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm, bool content) { throw null; } public static byte[] EncryptKey(byte[] keyData, System.Security.Cryptography.RSA rsa, bool useOAEP) { throw null; } public static byte[] EncryptKey(byte[] keyData, System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm) { throw null; } public virtual byte[] GetDecryptionIV(System.Security.Cryptography.Xml.EncryptedData encryptedData, string symmetricAlgorithmUri) { throw null; } public virtual System.Security.Cryptography.SymmetricAlgorithm GetDecryptionKey(System.Security.Cryptography.Xml.EncryptedData encryptedData, string symmetricAlgorithmUri) { throw null; } public virtual System.Xml.XmlElement GetIdElement(System.Xml.XmlDocument document, string idValue) { throw null; } public void ReplaceData(System.Xml.XmlElement inputElement, byte[] decryptedData) { } public static void ReplaceElement(System.Xml.XmlElement inputElement, System.Security.Cryptography.Xml.EncryptedData encryptedData, bool content) { } } public partial class EncryptionMethod { public EncryptionMethod() { } public EncryptionMethod(string algorithm) { } public string KeyAlgorithm { get { throw null; } set { } } public int KeySize { get { throw null; } set { } } public System.Xml.XmlElement GetXml() { throw null; } public void LoadXml(System.Xml.XmlElement value) { } } public sealed partial class EncryptionProperty { public EncryptionProperty() { } public EncryptionProperty(System.Xml.XmlElement elementProperty) { } public string Id { get { throw null; } } public System.Xml.XmlElement PropertyElement { get { throw null; } set { } } public string Target { get { throw null; } } public System.Xml.XmlElement GetXml() { throw null; } public void LoadXml(System.Xml.XmlElement value) { } } public sealed partial class EncryptionPropertyCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { public EncryptionPropertyCollection() { } public int Count { get { throw null; } } public bool IsFixedSize { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } [System.Runtime.CompilerServices.IndexerName("ItemOf")] public System.Security.Cryptography.Xml.EncryptionProperty this[int index] { get { throw null; } set { } } public object SyncRoot { get { throw null; } } object System.Collections.IList.this[int index] { get { throw null; } set { } } public int Add(System.Security.Cryptography.Xml.EncryptionProperty value) { throw null; } public void Clear() { } public bool Contains(System.Security.Cryptography.Xml.EncryptionProperty value) { throw null; } public void CopyTo(System.Array array, int index) { } public void CopyTo(System.Security.Cryptography.Xml.EncryptionProperty[] array, int index) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } public int IndexOf(System.Security.Cryptography.Xml.EncryptionProperty value) { throw null; } public void Insert(int index, System.Security.Cryptography.Xml.EncryptionProperty value) { } public System.Security.Cryptography.Xml.EncryptionProperty Item(int index) { throw null; } public void Remove(System.Security.Cryptography.Xml.EncryptionProperty value) { } public void RemoveAt(int index) { } int System.Collections.IList.Add(object value) { throw null; } bool System.Collections.IList.Contains(object value) { throw null; } int System.Collections.IList.IndexOf(object value) { throw null; } void System.Collections.IList.Insert(int index, object value) { } void System.Collections.IList.Remove(object value) { } } public partial interface IRelDecryptor { System.IO.Stream Decrypt(System.Security.Cryptography.Xml.EncryptionMethod encryptionMethod, System.Security.Cryptography.Xml.KeyInfo keyInfo, System.IO.Stream toDecrypt); } public partial class KeyInfo : System.Collections.IEnumerable { public KeyInfo() { } public int Count { get { throw null; } } public string Id { get { throw null; } set { } } public void AddClause(System.Security.Cryptography.Xml.KeyInfoClause clause) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } public System.Collections.IEnumerator GetEnumerator(System.Type requestedObjectType) { throw null; } public System.Xml.XmlElement GetXml() { throw null; } public void LoadXml(System.Xml.XmlElement value) { } } public abstract partial class KeyInfoClause { protected KeyInfoClause() { } public abstract System.Xml.XmlElement GetXml(); public abstract void LoadXml(System.Xml.XmlElement element); } public partial class KeyInfoEncryptedKey : System.Security.Cryptography.Xml.KeyInfoClause { public KeyInfoEncryptedKey() { } public KeyInfoEncryptedKey(System.Security.Cryptography.Xml.EncryptedKey encryptedKey) { } public System.Security.Cryptography.Xml.EncryptedKey EncryptedKey { get { throw null; } set { } } public override System.Xml.XmlElement GetXml() { throw null; } public override void LoadXml(System.Xml.XmlElement value) { } } public partial class KeyInfoName : System.Security.Cryptography.Xml.KeyInfoClause { public KeyInfoName() { } public KeyInfoName(string keyName) { } public string Value { get { throw null; } set { } } public override System.Xml.XmlElement GetXml() { throw null; } public override void LoadXml(System.Xml.XmlElement value) { } } public partial class KeyInfoNode : System.Security.Cryptography.Xml.KeyInfoClause { public KeyInfoNode() { } public KeyInfoNode(System.Xml.XmlElement node) { } public System.Xml.XmlElement Value { get { throw null; } set { } } public override System.Xml.XmlElement GetXml() { throw null; } public override void LoadXml(System.Xml.XmlElement value) { } } public partial class KeyInfoRetrievalMethod : System.Security.Cryptography.Xml.KeyInfoClause { public KeyInfoRetrievalMethod() { } public KeyInfoRetrievalMethod(string strUri) { } public KeyInfoRetrievalMethod(string strUri, string typeName) { } public string Type { get { throw null; } set { } } public string Uri { get { throw null; } set { } } public override System.Xml.XmlElement GetXml() { throw null; } public override void LoadXml(System.Xml.XmlElement value) { } } public partial class KeyInfoX509Data : System.Security.Cryptography.Xml.KeyInfoClause { public KeyInfoX509Data() { } public KeyInfoX509Data(byte[] rgbCert) { } public KeyInfoX509Data(System.Security.Cryptography.X509Certificates.X509Certificate cert) { } public KeyInfoX509Data(System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Security.Cryptography.X509Certificates.X509IncludeOption includeOption) { } public System.Collections.ArrayList Certificates { get { throw null; } } public byte[] CRL { get { throw null; } set { } } public System.Collections.ArrayList IssuerSerials { get { throw null; } } public System.Collections.ArrayList SubjectKeyIds { get { throw null; } } public System.Collections.ArrayList SubjectNames { get { throw null; } } public void AddCertificate(System.Security.Cryptography.X509Certificates.X509Certificate certificate) { } public void AddIssuerSerial(string issuerName, string serialNumber) { } public void AddSubjectKeyId(byte[] subjectKeyId) { } public void AddSubjectKeyId(string subjectKeyId) { } public void AddSubjectName(string subjectName) { } public override System.Xml.XmlElement GetXml() { throw null; } public override void LoadXml(System.Xml.XmlElement element) { } } public sealed partial class KeyReference : System.Security.Cryptography.Xml.EncryptedReference { public KeyReference() { } public KeyReference(string uri) { } public KeyReference(string uri, System.Security.Cryptography.Xml.TransformChain transformChain) { } } public partial class Reference { public Reference() { } public Reference(System.IO.Stream stream) { } public Reference(string uri) { } public string DigestMethod { get { throw null; } set { } } public byte[] DigestValue { get { throw null; } set { } } public string Id { get { throw null; } set { } } public System.Security.Cryptography.Xml.TransformChain TransformChain { get { throw null; } set { } } public string Type { get { throw null; } set { } } public string Uri { get { throw null; } set { } } public void AddTransform(System.Security.Cryptography.Xml.Transform transform) { } public System.Xml.XmlElement GetXml() { throw null; } public void LoadXml(System.Xml.XmlElement value) { } } public sealed partial class ReferenceList : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { public ReferenceList() { } public int Count { get { throw null; } } public bool IsSynchronized { get { throw null; } } [System.Runtime.CompilerServices.IndexerName("ItemOf")] public System.Security.Cryptography.Xml.EncryptedReference this[int index] { get { throw null; } set { } } public object SyncRoot { get { throw null; } } bool System.Collections.IList.IsFixedSize { get { throw null; } } bool System.Collections.IList.IsReadOnly { get { throw null; } } object System.Collections.IList.this[int index] { get { throw null; } set { } } public int Add(object value) { throw null; } public void Clear() { } public bool Contains(object value) { throw null; } public void CopyTo(System.Array array, int index) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } public int IndexOf(object value) { throw null; } public void Insert(int index, object value) { } public System.Security.Cryptography.Xml.EncryptedReference Item(int index) { throw null; } public void Remove(object value) { } public void RemoveAt(int index) { } } public partial class RSAKeyValue : System.Security.Cryptography.Xml.KeyInfoClause { public RSAKeyValue() { } public RSAKeyValue(System.Security.Cryptography.RSA key) { } public System.Security.Cryptography.RSA Key { get { throw null; } set { } } public override System.Xml.XmlElement GetXml() { throw null; } public override void LoadXml(System.Xml.XmlElement value) { } } public partial class Signature { public Signature() { } public string Id { get { throw null; } set { } } public System.Security.Cryptography.Xml.KeyInfo KeyInfo { get { throw null; } set { } } public System.Collections.IList ObjectList { get { throw null; } set { } } public byte[] SignatureValue { get { throw null; } set { } } public System.Security.Cryptography.Xml.SignedInfo SignedInfo { get { throw null; } set { } } public void AddObject(System.Security.Cryptography.Xml.DataObject dataObject) { } public System.Xml.XmlElement GetXml() { throw null; } public void LoadXml(System.Xml.XmlElement value) { } } public partial class SignedInfo : System.Collections.ICollection, System.Collections.IEnumerable { public SignedInfo() { } public string CanonicalizationMethod { get { throw null; } set { } } public System.Security.Cryptography.Xml.Transform CanonicalizationMethodObject { get { throw null; } } public int Count { get { throw null; } } public string Id { get { throw null; } set { } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public System.Collections.ArrayList References { get { throw null; } } public string SignatureLength { get { throw null; } set { } } public string SignatureMethod { get { throw null; } set { } } public object SyncRoot { get { throw null; } } public void AddReference(System.Security.Cryptography.Xml.Reference reference) { } public void CopyTo(System.Array array, int index) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } public System.Xml.XmlElement GetXml() { throw null; } public void LoadXml(System.Xml.XmlElement value) { } } public partial class SignedXml { protected System.Security.Cryptography.Xml.Signature m_signature; protected string m_strSigningKeyName; public const string XmlDecryptionTransformUrl = "http://www.w3.org/2002/07/decrypt#XML"; public const string XmlDsigBase64TransformUrl = "http://www.w3.org/2000/09/xmldsig#base64"; public const string XmlDsigC14NTransformUrl = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; public const string XmlDsigC14NWithCommentsTransformUrl = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; public const string XmlDsigCanonicalizationUrl = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; public const string XmlDsigCanonicalizationWithCommentsUrl = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; public const string XmlDsigDSAUrl = "http://www.w3.org/2000/09/xmldsig#dsa-sha1"; public const string XmlDsigEnvelopedSignatureTransformUrl = "http://www.w3.org/2000/09/xmldsig#enveloped-signature"; public const string XmlDsigExcC14NTransformUrl = "http://www.w3.org/2001/10/xml-exc-c14n#"; public const string XmlDsigExcC14NWithCommentsTransformUrl = "http://www.w3.org/2001/10/xml-exc-c14n#WithComments"; public const string XmlDsigHMACSHA1Url = "http://www.w3.org/2000/09/xmldsig#hmac-sha1"; public const string XmlDsigMinimalCanonicalizationUrl = "http://www.w3.org/2000/09/xmldsig#minimal"; public const string XmlDsigNamespaceUrl = "http://www.w3.org/2000/09/xmldsig#"; public const string XmlDsigRSASHA1Url = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; public const string XmlDsigRSASHA256Url = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; public const string XmlDsigRSASHA384Url = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384"; public const string XmlDsigRSASHA512Url = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"; public const string XmlDsigSHA1Url = "http://www.w3.org/2000/09/xmldsig#sha1"; public const string XmlDsigSHA256Url = "http://www.w3.org/2001/04/xmlenc#sha256"; public const string XmlDsigSHA384Url = "http://www.w3.org/2001/04/xmldsig-more#sha384"; public const string XmlDsigSHA512Url = "http://www.w3.org/2001/04/xmlenc#sha512"; public const string XmlDsigXPathTransformUrl = "http://www.w3.org/TR/1999/REC-xpath-19991116"; public const string XmlDsigXsltTransformUrl = "http://www.w3.org/TR/1999/REC-xslt-19991116"; public const string XmlLicenseTransformUrl = "urn:mpeg:mpeg21:2003:01-REL-R-NS:licenseTransform"; public SignedXml() { } public SignedXml(System.Xml.XmlDocument document) { } public SignedXml(System.Xml.XmlElement elem) { } public System.Security.Cryptography.Xml.EncryptedXml EncryptedXml { get { throw null; } set { } } public System.Security.Cryptography.Xml.KeyInfo KeyInfo { get { throw null; } set { } } public System.Xml.XmlResolver Resolver { set { } } public System.Collections.ObjectModel.Collection<string> SafeCanonicalizationMethods { get { throw null; } } public System.Security.Cryptography.Xml.Signature Signature { get { throw null; } } public System.Func<System.Security.Cryptography.Xml.SignedXml, bool> SignatureFormatValidator { get { throw null; } set { } } public string SignatureLength { get { throw null; } } public string SignatureMethod { get { throw null; } } public byte[] SignatureValue { get { throw null; } } public System.Security.Cryptography.Xml.SignedInfo SignedInfo { get { throw null; } } public System.Security.Cryptography.AsymmetricAlgorithm SigningKey { get { throw null; } set { } } public string SigningKeyName { get { throw null; } set { } } public void AddObject(System.Security.Cryptography.Xml.DataObject dataObject) { } public void AddReference(System.Security.Cryptography.Xml.Reference reference) { } public bool CheckSignature() { throw null; } public bool CheckSignature(System.Security.Cryptography.AsymmetricAlgorithm key) { throw null; } public bool CheckSignature(System.Security.Cryptography.KeyedHashAlgorithm macAlg) { throw null; } public bool CheckSignature(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, bool verifySignatureOnly) { throw null; } public bool CheckSignatureReturningKey(out System.Security.Cryptography.AsymmetricAlgorithm signingKey) { signingKey = default(System.Security.Cryptography.AsymmetricAlgorithm); throw null; } public void ComputeSignature() { } public void ComputeSignature(System.Security.Cryptography.KeyedHashAlgorithm macAlg) { } public virtual System.Xml.XmlElement GetIdElement(System.Xml.XmlDocument document, string idValue) { throw null; } protected virtual System.Security.Cryptography.AsymmetricAlgorithm GetPublicKey() { throw null; } public System.Xml.XmlElement GetXml() { throw null; } public void LoadXml(System.Xml.XmlElement value) { } } public abstract partial class Transform { protected Transform() { } public string Algorithm { get { throw null; } set { } } public System.Xml.XmlElement Context { get { throw null; } set { } } public abstract System.Type[] InputTypes { get; } public abstract System.Type[] OutputTypes { get; } public System.Collections.Hashtable PropagatedNamespaces { get { throw null; } } public System.Xml.XmlResolver Resolver { set { } } public virtual byte[] GetDigestedOutput(System.Security.Cryptography.HashAlgorithm hash) { throw null; } protected abstract System.Xml.XmlNodeList GetInnerXml(); public abstract object GetOutput(); public abstract object GetOutput(System.Type type); public System.Xml.XmlElement GetXml() { throw null; } public abstract void LoadInnerXml(System.Xml.XmlNodeList nodeList); public abstract void LoadInput(object obj); } public partial class TransformChain { public TransformChain() { } public int Count { get { throw null; } } public System.Security.Cryptography.Xml.Transform this[int index] { get { throw null; } } public void Add(System.Security.Cryptography.Xml.Transform transform) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } } public partial class XmlDecryptionTransform : System.Security.Cryptography.Xml.Transform { public XmlDecryptionTransform() { } public System.Security.Cryptography.Xml.EncryptedXml EncryptedXml { get { throw null; } set { } } public override System.Type[] InputTypes { get { throw null; } } public override System.Type[] OutputTypes { get { throw null; } } public void AddExceptUri(string uri) { } protected override System.Xml.XmlNodeList GetInnerXml() { throw null; } public override object GetOutput() { throw null; } public override object GetOutput(System.Type type) { throw null; } protected virtual bool IsTargetElement(System.Xml.XmlElement inputElement, string idValue) { throw null; } public override void LoadInnerXml(System.Xml.XmlNodeList nodeList) { } public override void LoadInput(object obj) { } } public partial class XmlDsigBase64Transform : System.Security.Cryptography.Xml.Transform { public XmlDsigBase64Transform() { } public override System.Type[] InputTypes { get { throw null; } } public override System.Type[] OutputTypes { get { throw null; } } protected override System.Xml.XmlNodeList GetInnerXml() { throw null; } public override object GetOutput() { throw null; } public override object GetOutput(System.Type type) { throw null; } public override void LoadInnerXml(System.Xml.XmlNodeList nodeList) { } public override void LoadInput(object obj) { } } public partial class XmlDsigC14NTransform : System.Security.Cryptography.Xml.Transform { public XmlDsigC14NTransform() { } public XmlDsigC14NTransform(bool includeComments) { } public override System.Type[] InputTypes { get { throw null; } } public override System.Type[] OutputTypes { get { throw null; } } public override byte[] GetDigestedOutput(System.Security.Cryptography.HashAlgorithm hash) { throw null; } protected override System.Xml.XmlNodeList GetInnerXml() { throw null; } public override object GetOutput() { throw null; } public override object GetOutput(System.Type type) { throw null; } public override void LoadInnerXml(System.Xml.XmlNodeList nodeList) { } public override void LoadInput(object obj) { } } public partial class XmlDsigC14NWithCommentsTransform : System.Security.Cryptography.Xml.XmlDsigC14NTransform { public XmlDsigC14NWithCommentsTransform() { } } public partial class XmlDsigEnvelopedSignatureTransform : System.Security.Cryptography.Xml.Transform { public XmlDsigEnvelopedSignatureTransform() { } public XmlDsigEnvelopedSignatureTransform(bool includeComments) { } public override System.Type[] InputTypes { get { throw null; } } public override System.Type[] OutputTypes { get { throw null; } } protected override System.Xml.XmlNodeList GetInnerXml() { throw null; } public override object GetOutput() { throw null; } public override object GetOutput(System.Type type) { throw null; } public override void LoadInnerXml(System.Xml.XmlNodeList nodeList) { } public override void LoadInput(object obj) { } } public partial class XmlDsigExcC14NTransform : System.Security.Cryptography.Xml.Transform { public XmlDsigExcC14NTransform() { } public XmlDsigExcC14NTransform(bool includeComments) { } public XmlDsigExcC14NTransform(bool includeComments, string inclusiveNamespacesPrefixList) { } public XmlDsigExcC14NTransform(string inclusiveNamespacesPrefixList) { } public string InclusiveNamespacesPrefixList { get { throw null; } set { } } public override System.Type[] InputTypes { get { throw null; } } public override System.Type[] OutputTypes { get { throw null; } } public override byte[] GetDigestedOutput(System.Security.Cryptography.HashAlgorithm hash) { throw null; } protected override System.Xml.XmlNodeList GetInnerXml() { throw null; } public override object GetOutput() { throw null; } public override object GetOutput(System.Type type) { throw null; } public override void LoadInnerXml(System.Xml.XmlNodeList nodeList) { } public override void LoadInput(object obj) { } } public partial class XmlDsigExcC14NWithCommentsTransform : System.Security.Cryptography.Xml.XmlDsigExcC14NTransform { public XmlDsigExcC14NWithCommentsTransform() { } public XmlDsigExcC14NWithCommentsTransform(string inclusiveNamespacesPrefixList) { } } public partial class XmlDsigXPathTransform : System.Security.Cryptography.Xml.Transform { public XmlDsigXPathTransform() { } public override System.Type[] InputTypes { get { throw null; } } public override System.Type[] OutputTypes { get { throw null; } } protected override System.Xml.XmlNodeList GetInnerXml() { throw null; } public override object GetOutput() { throw null; } public override object GetOutput(System.Type type) { throw null; } public override void LoadInnerXml(System.Xml.XmlNodeList nodeList) { } public override void LoadInput(object obj) { } } public partial class XmlDsigXsltTransform : System.Security.Cryptography.Xml.Transform { public XmlDsigXsltTransform() { } public XmlDsigXsltTransform(bool includeComments) { } public override System.Type[] InputTypes { get { throw null; } } public override System.Type[] OutputTypes { get { throw null; } } protected override System.Xml.XmlNodeList GetInnerXml() { throw null; } public override object GetOutput() { throw null; } public override object GetOutput(System.Type type) { throw null; } public override void LoadInnerXml(System.Xml.XmlNodeList nodeList) { } public override void LoadInput(object obj) { } } public partial class XmlLicenseTransform : System.Security.Cryptography.Xml.Transform { public XmlLicenseTransform() { } public System.Security.Cryptography.Xml.IRelDecryptor Decryptor { get { throw null; } set { } } public override System.Type[] InputTypes { get { throw null; } } public override System.Type[] OutputTypes { get { throw null; } } protected override System.Xml.XmlNodeList GetInnerXml() { throw null; } public override object GetOutput() { throw null; } public override object GetOutput(System.Type type) { throw null; } public override void LoadInnerXml(System.Xml.XmlNodeList nodeList) { } public override void LoadInput(object obj) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using OLEDB.Test.ModuleCore; namespace System.Xml.Tests { public partial class TCReadElementContentAsBase64 : TCXMLReaderBaseGeneral { // Type is System.Xml.Tests.TCReadElementContentAsBase64 // Test Case public override void AddChildren() { // for function TestReadBase64_1 { this.AddChild(new CVariation(TestReadBase64_1) { Attribute = new Variation("ReadBase64 Element with all valid value") }); } // for function TestReadBase64_2 { this.AddChild(new CVariation(TestReadBase64_2) { Attribute = new Variation("ReadBase64 Element with all valid Num value") { Pri = 0 } }); } // for function TestReadBase64_3 { this.AddChild(new CVariation(TestReadBase64_3) { Attribute = new Variation("ReadBase64 Element with all valid Text value") }); } // for function TestReadBase64_5 { this.AddChild(new CVariation(TestReadBase64_5) { Attribute = new Variation("ReadBase64 Element with all valid value (from concatenation), Pri=0") }); } // for function TestReadBase64_6 { this.AddChild(new CVariation(TestReadBase64_6) { Attribute = new Variation("ReadBase64 Element with Long valid value (from concatenation), Pri=0") }); } // for function ReadBase64_7 { this.AddChild(new CVariation(ReadBase64_7) { Attribute = new Variation("ReadBase64 with count > buffer size") }); } // for function ReadBase64_8 { this.AddChild(new CVariation(ReadBase64_8) { Attribute = new Variation("ReadBase64 with count < 0") }); } // for function ReadBase64_9 { this.AddChild(new CVariation(ReadBase64_9) { Attribute = new Variation("ReadBase64 with index > buffer size") }); } // for function ReadBase64_10 { this.AddChild(new CVariation(ReadBase64_10) { Attribute = new Variation("ReadBase64 with index < 0") }); } // for function ReadBase64_11 { this.AddChild(new CVariation(ReadBase64_11) { Attribute = new Variation("ReadBase64 with index + count exceeds buffer") }); } // for function ReadBase64_12 { this.AddChild(new CVariation(ReadBase64_12) { Attribute = new Variation("ReadBase64 index & count =0") }); } // for function TestReadBase64_13 { this.AddChild(new CVariation(TestReadBase64_13) { Attribute = new Variation("ReadBase64 Element multiple into same buffer (using offset), Pri=0") }); } // for function TestReadBase64_14 { this.AddChild(new CVariation(TestReadBase64_14) { Attribute = new Variation("ReadBase64 with buffer == null") }); } // for function TestReadBase64_15 { this.AddChild(new CVariation(TestReadBase64_15) { Attribute = new Variation("ReadBase64 after failure") }); } // for function TestReadBase64_16 { this.AddChild(new CVariation(TestReadBase64_16) { Attribute = new Variation("Read after partial ReadBase64") { Pri = 0 } }); } // for function TestReadBase64_17 { this.AddChild(new CVariation(TestReadBase64_17) { Attribute = new Variation("Current node on multiple calls") }); } // for function TestTextReadBase64_23 { this.AddChild(new CVariation(TestTextReadBase64_23) { Attribute = new Variation("ReadBase64 with incomplete sequence") }); } // for function TestTextReadBase64_24 { this.AddChild(new CVariation(TestTextReadBase64_24) { Attribute = new Variation("ReadBase64 when end tag doesn't exist") }); } // for function TestTextReadBase64_26 { this.AddChild(new CVariation(TestTextReadBase64_26) { Attribute = new Variation("ReadBase64 with whitespace in the middle") }); } // for function TestTextReadBase64_27 { this.AddChild(new CVariation(TestTextReadBase64_27) { Attribute = new Variation("ReadBase64 with = in the middle") }); } // for function ReadBase64BufferOverflowWorksProperly { this.AddChild(new CVariation(ReadBase64RunsIntoOverflow) { Attribute = new Variation("ReadBase64 runs into an Overflow") { Params = new object[] { "1000000" } } }); this.AddChild(new CVariation(ReadBase64RunsIntoOverflow) { Attribute = new Variation("ReadBase64 runs into an Overflow") { Params = new object[] { "10000" } } }); this.AddChild(new CVariation(ReadBase64RunsIntoOverflow) { Attribute = new Variation("ReadBase64 runs into an Overflow") { Params = new object[] { "10000000" } } }); } // for function TestReadBase64ReadsTheContent { this.AddChild(new CVariation(TestReadBase64ReadsTheContent) { Attribute = new Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes") }); } // for function ReadValueChunkWorksProperlyWithSubtreeReaderInsertedAttributes { this.AddChild(new CVariation(SubtreeReaderInsertedAttributesWorkWithReadContentAsBase64) { Attribute = new Variation("SubtreeReader inserted attributes don't work with ReadContentAsBase64") }); } // for function TestReadBase64_28 { this.AddChild(new CVariation(TestReadBase64_28) { Attribute = new Variation("call ReadContentAsBase64 on two or more nodes") }); } // for function TestReadBase64_29 { this.AddChild(new CVariation(TestReadBase64_29) { Attribute = new Variation("read Base64 over invalid text node") }); } // for function TestReadBase64_30 { this.AddChild(new CVariation(TestReadBase64_30) { Attribute = new Variation("goto to text node, ask got.Value, readcontentasBase64") }); } // for function TestReadBase64_31 { this.AddChild(new CVariation(TestReadBase64_31) { Attribute = new Variation("goto to text node, readcontentasBase64, ask got.Value") }); } // for function TestReadBase64_32 { this.AddChild(new CVariation(TestReadBase64_32) { Attribute = new Variation("goto to huge text node, read several chars with ReadContentAsBase64 and Move forward with .Read()") }); } // for function TestReadBase64_33 { this.AddChild(new CVariation(TestReadBase64_33) { Attribute = new Variation("goto to huge text node with invalid chars, read several chars with ReadContentAsBase64 and Move forward with .Read()") }); } // for function TestReadBase64_34 { this.AddChild(new CVariation(TestReadBase64_34) { Attribute = new Variation("ReadContentAsBase64 on an xmlns attribute") { Param = "<foo xmlns='default'> <bar id='1'/> </foo>" } }); this.AddChild(new CVariation(TestReadBase64_34) { Attribute = new Variation("ReadContentAsBase64 on an xml:lang attribute") { Param = "<foo xml:lang='default'> <bar id='1'/> </foo>" } }); this.AddChild(new CVariation(TestReadBase64_34) { Attribute = new Variation("ReadContentAsBase64 on an xmlns:k attribute") { Param = "<k:foo xmlns:k='default'> <k:bar id='1'/> </k:foo>" } }); this.AddChild(new CVariation(TestReadBase64_34) { Attribute = new Variation("ReadContentAsBase64 on an xml:space attribute") { Param = "<foo xml:space='default'> <bar id='1'/> </foo>" } }); } // for function TestReadReadBase64_35 { this.AddChild(new CVariation(TestReadReadBase64_35) { Attribute = new Variation("call ReadContentAsBase64 on two or more nodes and whitespace") }); } // for function TestReadReadBase64_36 { this.AddChild(new CVariation(TestReadReadBase64_36) { Attribute = new Variation("call ReadContentAsBase64 on two or more nodes and whitespace after call Value") }); } } } }
// // MessageBar.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Gtk; using Hyena.Gui; using Hyena.Gui.Theming; namespace Hyena.Widgets { public class MessageBar : Alignment { private HBox box; private HBox button_box; private AnimatedImage image; private WrapLabel label; private Button close_button; private Window win; private Theme theme; public event EventHandler CloseClicked { add { close_button.Clicked += value; } remove { close_button.Clicked -= value; } } public MessageBar () : base (0.0f, 0.5f, 1.0f, 0.0f) { win = new Window (WindowType.Popup); win.Name = "gtk-tooltips"; win.EnsureStyle (); win.StyleSet += delegate { Style = win.Style; }; HBox shell_box = new HBox (); shell_box.Spacing = 10; box = new HBox (); box.Spacing = 10; image = new AnimatedImage (); try { image.Pixbuf = Gtk.IconTheme.Default.LoadIcon ("process-working", 22, IconLookupFlags.NoSvg); image.FrameHeight = 22; image.FrameWidth = 22; Spinning = false; image.Load (); } catch { } label = new WrapLabel (); label.Show (); box.PackStart (image, false, false, 0); box.PackStart (label, true, true, 0); box.Show (); button_box = new HBox (); button_box.Spacing = 3; close_button = new Button (new Image (Stock.Close, IconSize.Menu)); close_button.Relief = ReliefStyle.None; close_button.Clicked += delegate { Hide (); }; close_button.ShowAll (); close_button.Hide (); shell_box.PackStart (box, true, true, 0); shell_box.PackStart (button_box, false, false, 0); shell_box.PackStart (close_button, false, false, 0); shell_box.Show (); Add (shell_box); EnsureStyle (); BorderWidth = 3; } protected override void OnShown () { base.OnShown (); image.Show (); } protected override void OnHidden () { base.OnHidden (); image.Hide (); } protected override void OnRealized () { base.OnRealized (); theme = Hyena.Gui.Theming.ThemeEngine.CreateTheme (this); } protected override void OnSizeAllocated (Gdk.Rectangle allocation) { base.OnSizeAllocated (allocation); QueueDraw (); } protected override bool OnExposeEvent (Gdk.EventExpose evnt) { if (!IsDrawable) { return false; } Cairo.Context cr = Gdk.CairoHelper.Create (evnt.Window); try { Gdk.Color color = Style.Background (StateType.Normal); theme.DrawFrame (cr, Allocation, CairoExtensions.GdkColorToCairoColor (color)); return base.OnExposeEvent (evnt); } finally { CairoExtensions.DisposeContext (cr); } } private bool changing_style = false; protected override void OnStyleSet (Gtk.Style previousStyle) { if (changing_style) { return; } changing_style = true; Style = win.Style; label.Style = Style; changing_style = false; } public void RemoveButton (Button button) { button_box.Remove (button); } public void ClearButtons () { foreach (Widget child in button_box.Children) { button_box.Remove (child); } } public void AddButton (Button button) { button_box.Show (); button.Show (); button_box.PackStart (button, false, false, 0); } public bool ShowCloseButton { set { close_button.Visible = value; QueueDraw (); } } public string Message { set { label.Markup = value; QueueDraw (); } } public Gdk.Pixbuf Pixbuf { set { image.InactivePixbuf = value; QueueDraw (); } } public bool Spinning { get { return image.Active; } set { image.Active = value; } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Runtime.InteropServices.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Runtime.InteropServices { public enum AssemblyRegistrationFlags { None = 0, SetCodeBase = 1, } public enum CALLCONV { CC_CDECL = 1, CC_MSCPASCAL = 2, CC_PASCAL = 2, CC_MACPASCAL = 3, CC_STDCALL = 4, CC_RESERVED = 5, CC_SYSCALL = 6, CC_MPWCDECL = 7, CC_MPWPASCAL = 8, CC_MAX = 9, } public enum CallingConvention { Winapi = 1, Cdecl = 2, StdCall = 3, ThisCall = 4, FastCall = 5, } public enum CharSet { None = 1, Ansi = 2, Unicode = 3, Auto = 4, } public enum ClassInterfaceType { None = 0, AutoDispatch = 1, AutoDual = 2, } public enum ComInterfaceType { InterfaceIsDual = 0, InterfaceIsIUnknown = 1, InterfaceIsIDispatch = 2, } public enum ComMemberType { Method = 0, PropGet = 1, PropSet = 2, } public enum CustomQueryInterfaceMode { Ignore = 0, Allow = 1, } public enum CustomQueryInterfaceResult { Handled = 0, NotHandled = 1, Failed = 2, } public enum DESCKIND { DESCKIND_NONE = 0, DESCKIND_FUNCDESC = 1, DESCKIND_VARDESC = 2, DESCKIND_TYPECOMP = 3, DESCKIND_IMPLICITAPPOBJ = 4, DESCKIND_MAX = 5, } public enum ExporterEventKind { NOTIF_TYPECONVERTED = 0, NOTIF_CONVERTWARNING = 1, ERROR_REFTOINVALIDASSEMBLY = 2, } public enum FUNCFLAGS : short { FUNCFLAG_FRESTRICTED = 1, FUNCFLAG_FSOURCE = 2, FUNCFLAG_FBINDABLE = 4, FUNCFLAG_FREQUESTEDIT = 8, FUNCFLAG_FDISPLAYBIND = 16, FUNCFLAG_FDEFAULTBIND = 32, FUNCFLAG_FHIDDEN = 64, FUNCFLAG_FUSESGETLASTERROR = 128, FUNCFLAG_FDEFAULTCOLLELEM = 256, FUNCFLAG_FUIDEFAULT = 512, FUNCFLAG_FNONBROWSABLE = 1024, FUNCFLAG_FREPLACEABLE = 2048, FUNCFLAG_FIMMEDIATEBIND = 4096, } public enum FUNCKIND { FUNC_VIRTUAL = 0, FUNC_PUREVIRTUAL = 1, FUNC_NONVIRTUAL = 2, FUNC_STATIC = 3, FUNC_DISPATCH = 4, } public enum GCHandleType { Weak = 0, WeakTrackResurrection = 1, Normal = 2, Pinned = 3, } public enum IDispatchImplType { SystemDefinedImpl = 0, InternalImpl = 1, CompatibleImpl = 2, } public enum IDLFLAG : short { IDLFLAG_NONE = 0, IDLFLAG_FIN = 1, IDLFLAG_FOUT = 2, IDLFLAG_FLCID = 4, IDLFLAG_FRETVAL = 8, } public enum IMPLTYPEFLAGS { IMPLTYPEFLAG_FDEFAULT = 1, IMPLTYPEFLAG_FSOURCE = 2, IMPLTYPEFLAG_FRESTRICTED = 4, IMPLTYPEFLAG_FDEFAULTVTABLE = 8, } public enum ImporterEventKind { NOTIF_TYPECONVERTED = 0, NOTIF_CONVERTWARNING = 1, ERROR_REFTOINVALIDTYPELIB = 2, } public enum INVOKEKIND { INVOKE_FUNC = 1, INVOKE_PROPERTYGET = 2, INVOKE_PROPERTYPUT = 4, INVOKE_PROPERTYPUTREF = 8, } public enum LayoutKind { Sequential = 0, Explicit = 2, Auto = 3, } public enum LIBFLAGS : short { LIBFLAG_FRESTRICTED = 1, LIBFLAG_FCONTROL = 2, LIBFLAG_FHIDDEN = 4, LIBFLAG_FHASDISKIMAGE = 8, } public delegate IntPtr ObjectCreationDelegate(IntPtr aggregator); public enum PARAMFLAG : short { PARAMFLAG_NONE = 0, PARAMFLAG_FIN = 1, PARAMFLAG_FOUT = 2, PARAMFLAG_FLCID = 4, PARAMFLAG_FRETVAL = 8, PARAMFLAG_FOPT = 16, PARAMFLAG_FHASDEFAULT = 32, PARAMFLAG_FHASCUSTDATA = 64, } public enum RegistrationClassContext { InProcessServer = 1, InProcessHandler = 2, LocalServer = 4, InProcessServer16 = 8, RemoteServer = 16, InProcessHandler16 = 32, Reserved1 = 64, Reserved2 = 128, Reserved3 = 256, Reserved4 = 512, NoCodeDownload = 1024, Reserved5 = 2048, NoCustomMarshal = 4096, EnableCodeDownload = 8192, NoFailureLog = 16384, DisableActivateAsActivator = 32768, EnableActivateAsActivator = 65536, FromDefaultContext = 131072, } public enum RegistrationConnectionType { SingleUse = 0, MultipleUse = 1, MultiSeparate = 2, Suspended = 4, Surrogate = 8, } public enum SYSKIND { SYS_WIN16 = 0, SYS_WIN32 = 1, SYS_MAC = 2, } public enum TYPEFLAGS : short { TYPEFLAG_FAPPOBJECT = 1, TYPEFLAG_FCANCREATE = 2, TYPEFLAG_FLICENSED = 4, TYPEFLAG_FPREDECLID = 8, TYPEFLAG_FHIDDEN = 16, TYPEFLAG_FCONTROL = 32, TYPEFLAG_FDUAL = 64, TYPEFLAG_FNONEXTENSIBLE = 128, TYPEFLAG_FOLEAUTOMATION = 256, TYPEFLAG_FRESTRICTED = 512, TYPEFLAG_FAGGREGATABLE = 1024, TYPEFLAG_FREPLACEABLE = 2048, TYPEFLAG_FDISPATCHABLE = 4096, TYPEFLAG_FREVERSEBIND = 8192, TYPEFLAG_FPROXY = 16384, } public enum TYPEKIND { TKIND_ENUM = 0, TKIND_RECORD = 1, TKIND_MODULE = 2, TKIND_INTERFACE = 3, TKIND_DISPATCH = 4, TKIND_COCLASS = 5, TKIND_ALIAS = 6, TKIND_UNION = 7, TKIND_MAX = 8, } public enum TypeLibExporterFlags { None = 0, OnlyReferenceRegistered = 1, CallerResolvedReferences = 2, OldNames = 4, ExportAs32Bit = 16, ExportAs64Bit = 32, } public enum TypeLibFuncFlags { FRestricted = 1, FSource = 2, FBindable = 4, FRequestEdit = 8, FDisplayBind = 16, FDefaultBind = 32, FHidden = 64, FUsesGetLastError = 128, FDefaultCollelem = 256, FUiDefault = 512, FNonBrowsable = 1024, FReplaceable = 2048, FImmediateBind = 4096, } public enum TypeLibImporterFlags { None = 0, PrimaryInteropAssembly = 1, UnsafeInterfaces = 2, SafeArrayAsSystemArray = 4, TransformDispRetVals = 8, PreventClassMembers = 16, SerializableValueClasses = 32, ImportAsX86 = 256, ImportAsX64 = 512, ImportAsItanium = 1024, ImportAsAgnostic = 2048, ReflectionOnlyLoading = 4096, NoDefineVersionResource = 8192, } public enum TypeLibTypeFlags { FAppObject = 1, FCanCreate = 2, FLicensed = 4, FPreDeclId = 8, FHidden = 16, FControl = 32, FDual = 64, FNonExtensible = 128, FOleAutomation = 256, FRestricted = 512, FAggregatable = 1024, FReplaceable = 2048, FDispatchable = 4096, FReverseBind = 8192, } public enum TypeLibVarFlags { FReadOnly = 1, FSource = 2, FBindable = 4, FRequestEdit = 8, FDisplayBind = 16, FDefaultBind = 32, FHidden = 64, FRestricted = 128, FDefaultCollelem = 256, FUiDefault = 512, FNonBrowsable = 1024, FReplaceable = 2048, FImmediateBind = 4096, } public enum UnmanagedType { Bool = 2, I1 = 3, U1 = 4, I2 = 5, U2 = 6, I4 = 7, U4 = 8, I8 = 9, U8 = 10, R4 = 11, R8 = 12, Currency = 15, BStr = 19, LPStr = 20, LPWStr = 21, LPTStr = 22, ByValTStr = 23, IUnknown = 25, IDispatch = 26, Struct = 27, Interface = 28, SafeArray = 29, ByValArray = 30, SysInt = 31, SysUInt = 32, VBByRefStr = 34, AnsiBStr = 35, TBStr = 36, VariantBool = 37, FunctionPtr = 38, AsAny = 40, LPArray = 42, LPStruct = 43, CustomMarshaler = 44, Error = 45, } public enum VarEnum { VT_EMPTY = 0, VT_NULL = 1, VT_I2 = 2, VT_I4 = 3, VT_R4 = 4, VT_R8 = 5, VT_CY = 6, VT_DATE = 7, VT_BSTR = 8, VT_DISPATCH = 9, VT_ERROR = 10, VT_BOOL = 11, VT_VARIANT = 12, VT_UNKNOWN = 13, VT_DECIMAL = 14, VT_I1 = 16, VT_UI1 = 17, VT_UI2 = 18, VT_UI4 = 19, VT_I8 = 20, VT_UI8 = 21, VT_INT = 22, VT_UINT = 23, VT_VOID = 24, VT_HRESULT = 25, VT_PTR = 26, VT_SAFEARRAY = 27, VT_CARRAY = 28, VT_USERDEFINED = 29, VT_LPSTR = 30, VT_LPWSTR = 31, VT_RECORD = 36, VT_FILETIME = 64, VT_BLOB = 65, VT_STREAM = 66, VT_STORAGE = 67, VT_STREAMED_OBJECT = 68, VT_STORED_OBJECT = 69, VT_BLOB_OBJECT = 70, VT_CF = 71, VT_CLSID = 72, VT_VECTOR = 4096, VT_ARRAY = 8192, VT_BYREF = 16384, } public enum VARFLAGS : short { VARFLAG_FREADONLY = 1, VARFLAG_FSOURCE = 2, VARFLAG_FBINDABLE = 4, VARFLAG_FREQUESTEDIT = 8, VARFLAG_FDISPLAYBIND = 16, VARFLAG_FDEFAULTBIND = 32, VARFLAG_FHIDDEN = 64, VARFLAG_FRESTRICTED = 128, VARFLAG_FDEFAULTCOLLELEM = 256, VARFLAG_FUIDEFAULT = 512, VARFLAG_FNONBROWSABLE = 1024, VARFLAG_FREPLACEABLE = 2048, VARFLAG_FIMMEDIATEBIND = 4096, } }
// 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.Net.Test.Common; using System.Threading; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { using Configuration = System.Net.Test.Common.Configuration; public class DnsEndPointTest : DualModeBase { private void OnConnectAsyncCompleted(object sender, SocketAsyncEventArgs args) { ManualResetEvent complete = (ManualResetEvent)args.UserToken; complete.Set(); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void Socket_ConnectDnsEndPoint_Success(SocketImplementationType type) { int port; using (SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port)) using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new DnsEndPoint("localhost", port)); } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void Socket_ConnectDnsEndPoint_SetSocketProperties_Success(SocketImplementationType type) { int port; using (SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port)) using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { sock.LingerState = new LingerOption(false, 0); sock.NoDelay = true; sock.ReceiveBufferSize = 1024; sock.ReceiveTimeout = 100; sock.SendBufferSize = 1024; sock.SendTimeout = 100; sock.Connect(new DnsEndPoint("localhost", port)); } } [OuterLoop] // TODO: Issue #11345 [Fact] public void Socket_ConnectDnsEndPoint_Failure() { using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { SocketException ex = Assert.ThrowsAny<SocketException>(() => { sock.Connect(new DnsEndPoint(Configuration.Sockets.InvalidHost, UnusedPort)); }); SocketError errorCode = ex.SocketErrorCode; Assert.True((errorCode == SocketError.HostNotFound) || (errorCode == SocketError.NoData), $"SocketErrorCode: {errorCode}"); ex = Assert.ThrowsAny<SocketException>(() => { sock.Connect(new DnsEndPoint("localhost", UnusedPort)); }); Assert.Equal(SocketError.ConnectionRefused, ex.SocketErrorCode); } } [OuterLoop] // TODO: Issue #11345 [Fact] public void Socket_SendToDnsEndPoint_ArgumentException() { using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { AssertExtensions.Throws<ArgumentException>("remoteEP", () => { sock.SendTo(new byte[10], new DnsEndPoint("localhost", UnusedPort)); }); } } [OuterLoop] // TODO: Issue #11345 [Fact] public void Socket_ReceiveFromDnsEndPoint_ArgumentException() { using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { int port = sock.BindToAnonymousPort(IPAddress.Loopback); EndPoint endpoint = new DnsEndPoint("localhost", port); AssertExtensions.Throws<ArgumentException>("remoteEP", () => { sock.ReceiveFrom(new byte[10], ref endpoint); }); } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void Socket_BeginConnectDnsEndPoint_Success(SocketImplementationType type) { int port; using (SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port)) using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IAsyncResult result = sock.BeginConnect(new DnsEndPoint("localhost", port), null, null); sock.EndConnect(result); Assert.Throws<InvalidOperationException>(() => sock.EndConnect(result)); // validate can't call end twice } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void Socket_BeginConnectDnsEndPoint_SetSocketProperties_Success(SocketImplementationType type) { int port; using (SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port)) using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { sock.LingerState = new LingerOption(false, 0); sock.NoDelay = true; sock.ReceiveBufferSize = 1024; sock.ReceiveTimeout = 100; sock.SendBufferSize = 1024; sock.SendTimeout = 100; IAsyncResult result = sock.BeginConnect(new DnsEndPoint("localhost", port), null, null); sock.EndConnect(result); } } [OuterLoop] // TODO: Issue #11345 [Fact] public void Socket_BeginConnectDnsEndPoint_Failure() { using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { SocketException ex = Assert.ThrowsAny<SocketException>(() => { IAsyncResult result = sock.BeginConnect(new DnsEndPoint(Configuration.Sockets.InvalidHost, UnusedPort), null, null); sock.EndConnect(result); }); SocketError errorCode = ex.SocketErrorCode; Assert.True((errorCode == SocketError.HostNotFound) || (errorCode == SocketError.NoData), "SocketErrorCode: {0}" + errorCode); ex = Assert.ThrowsAny<SocketException>(() => { IAsyncResult result = sock.BeginConnect(new DnsEndPoint("localhost", UnusedPort), null, null); sock.EndConnect(result); }); Assert.Equal(SocketError.ConnectionRefused, ex.SocketErrorCode); } } [OuterLoop] // TODO: Issue #11345 [Fact] public void Socket_BeginSendToDnsEndPoint_ArgumentException() { using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { AssertExtensions.Throws<ArgumentException>("remoteEP", () => { sock.BeginSendTo(new byte[10], 0, 0, SocketFlags.None, new DnsEndPoint("localhost", UnusedPort), null, null); }); } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [Trait("IPv4", "true")] public void Socket_ConnectAsyncDnsEndPoint_Success(SocketImplementationType type) { Assert.True(Capability.IPv4Support()); int port; using (SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port)) using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (ManualResetEvent complete = new ManualResetEvent(false)) { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("localhost", port); args.Completed += OnConnectAsyncCompleted; args.UserToken = complete; bool willRaiseEvent = sock.ConnectAsync(args); if (willRaiseEvent) { Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection"); } Assert.Equal(SocketError.Success, args.SocketError); Assert.Null(args.ConnectByNameError); } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [Trait("IPv4", "true")] public void Socket_ConnectAsyncDnsEndPoint_SetSocketProperties_Success(SocketImplementationType type) { Assert.True(Capability.IPv4Support()); int port; using (SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port)) using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (ManualResetEvent complete = new ManualResetEvent(false)) { sock.LingerState = new LingerOption(false, 0); sock.NoDelay = true; sock.ReceiveBufferSize = 1024; sock.ReceiveTimeout = 100; sock.SendBufferSize = 1024; sock.SendTimeout = 100; SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("localhost", port); args.Completed += OnConnectAsyncCompleted; args.UserToken = complete; bool willRaiseEvent = sock.ConnectAsync(args); if (willRaiseEvent) { Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection"); } Assert.Equal(SocketError.Success, args.SocketError); Assert.Null(args.ConnectByNameError); } } [OuterLoop] // TODO: Issue #11345 [Fact] [Trait("IPv4", "true")] public void Socket_ConnectAsyncDnsEndPoint_HostNotFound() { Assert.True(Capability.IPv4Support()); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint(Configuration.Sockets.InvalidHost, UnusedPort); args.Completed += OnConnectAsyncCompleted; using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (ManualResetEvent complete = new ManualResetEvent(false)) { args.UserToken = complete; bool willRaiseEvent = sock.ConnectAsync(args); if (willRaiseEvent) { Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection"); } AssertHostNotFoundOrNoData(args); } } [OuterLoop] // TODO: Issue #11345 [Fact] [Trait("IPv4", "true")] public void Socket_ConnectAsyncDnsEndPoint_ConnectionRefused() { Assert.True(Capability.IPv4Support()); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("localhost", UnusedPort); args.Completed += OnConnectAsyncCompleted; using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (ManualResetEvent complete = new ManualResetEvent(false)) { args.UserToken = complete; bool willRaiseEvent = sock.ConnectAsync(args); if (willRaiseEvent) { Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection"); } Assert.Equal(SocketError.ConnectionRefused, args.SocketError); Assert.True(args.ConnectByNameError is SocketException); Assert.Equal(SocketError.ConnectionRefused, ((SocketException)args.ConnectByNameError).SocketErrorCode); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(LocalhostIsBothIPv4AndIPv6))] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [Trait("IPv4", "true")] [Trait("IPv6", "true")] public void Socket_StaticConnectAsync_Success(SocketImplementationType type) { Assert.True(Capability.IPv4Support() && Capability.IPv6Support()); int port4, port6; using (SocketTestServer server4 = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port4)) using (SocketTestServer server6 = SocketTestServer.SocketTestServerFactory(type, IPAddress.IPv6Loopback, out port6)) { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("localhost", port4); args.Completed += OnConnectAsyncCompleted; ManualResetEvent complete = new ManualResetEvent(false); args.UserToken = complete; Assert.True(Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args)); Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection"); Assert.Equal(SocketError.Success, args.SocketError); Assert.Null(args.ConnectByNameError); Assert.NotNull(args.ConnectSocket); Assert.True(args.ConnectSocket.AddressFamily == AddressFamily.InterNetwork); Assert.True(args.ConnectSocket.Connected); args.ConnectSocket.Dispose(); args.RemoteEndPoint = new DnsEndPoint("localhost", port6); complete.Reset(); Assert.True(Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args)); Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection"); Assert.Equal(SocketError.Success, args.SocketError); Assert.Null(args.ConnectByNameError); Assert.NotNull(args.ConnectSocket); Assert.True(args.ConnectSocket.AddressFamily == AddressFamily.InterNetworkV6); Assert.True(args.ConnectSocket.Connected); args.ConnectSocket.Dispose(); } } [OuterLoop] // TODO: Issue #11345 [Fact] public void Socket_StaticConnectAsync_HostNotFound() { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint(Configuration.Sockets.InvalidHost, UnusedPort); args.Completed += OnConnectAsyncCompleted; ManualResetEvent complete = new ManualResetEvent(false); args.UserToken = complete; bool willRaiseEvent = Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args); if (!willRaiseEvent) { OnConnectAsyncCompleted(null, args); } Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection"); AssertHostNotFoundOrNoData(args); Assert.Null(args.ConnectSocket); complete.Dispose(); } [OuterLoop] // TODO: Issue #11345 [Fact] public void Socket_StaticConnectAsync_ConnectionRefused() { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("localhost", UnusedPort); args.Completed += OnConnectAsyncCompleted; ManualResetEvent complete = new ManualResetEvent(false); args.UserToken = complete; bool willRaiseEvent = Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args); if (!willRaiseEvent) { OnConnectAsyncCompleted(null, args); } Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection"); Assert.Equal(SocketError.ConnectionRefused, args.SocketError); Assert.True(args.ConnectByNameError is SocketException); Assert.Equal(SocketError.ConnectionRefused, ((SocketException)args.ConnectByNameError).SocketErrorCode); Assert.Null(args.ConnectSocket); complete.Dispose(); } private static void CallbackThatShouldNotBeCalled(object sender, SocketAsyncEventArgs args) { throw new ShouldNotBeInvokedException(); } [OuterLoop] // TODO: Issue #11345 [Fact] [Trait("IPv6", "true")] public void Socket_StaticConnectAsync_SyncFailure() { Assert.True(Capability.IPv6Support()); // IPv6 required because we use AF.InterNetworkV6 SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("127.0.0.1", UnusedPort, AddressFamily.InterNetworkV6); args.Completed += CallbackThatShouldNotBeCalled; Assert.False(Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args)); Assert.Equal(SocketError.NoData, args.SocketError); Assert.Null(args.ConnectSocket); } private static void AssertHostNotFoundOrNoData(SocketAsyncEventArgs args) { SocketError errorCode = args.SocketError; Assert.True((errorCode == SocketError.HostNotFound) || (errorCode == SocketError.NoData), "SocketError: " + errorCode); Assert.True(args.ConnectByNameError is SocketException); errorCode = ((SocketException)args.ConnectByNameError).SocketErrorCode; Assert.True((errorCode == SocketError.HostNotFound) || (errorCode == SocketError.NoData), "SocketError: " + errorCode); } } }
// Copyright (c) 2012 DotNetAnywhere // // 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.Runtime.CompilerServices; #if LOCALTEST namespace System_.Text { #else namespace System.Text { #endif public sealed class StringBuilder { private const int defaultMaxCapacity = int.MaxValue; private const int defaultInitialCapacity = 16; private int length; private int capacity; private char[] data; #region Constructors public StringBuilder() : this(defaultInitialCapacity, defaultMaxCapacity) { } public StringBuilder(int initialCapacity) : this(initialCapacity, defaultMaxCapacity) { } public StringBuilder(int initialCapacity, int maxCapacity) { this.capacity = Math.Max(initialCapacity, 2); this.length = 0; this.data = new char[this.capacity]; } public StringBuilder(string value) : this((value != null) ? value.Length : defaultInitialCapacity, defaultMaxCapacity) { if (value != null) { this.Append(value); } } public StringBuilder(string value, int initialCapacity) : this(initialCapacity, defaultMaxCapacity) { if (value != null) { this.Append(value); } } public StringBuilder(string value, int startIndex, int length, int initialCapacity) : this(initialCapacity, defaultMaxCapacity) { if (value == null) { value = string.Empty; } if (startIndex < 0 || length < 0 || startIndex + length > value.Length) { throw new ArgumentOutOfRangeException(); } this.Append(value, startIndex, length); } #endregion public override string ToString() { return new string(this.data, 0, this.length); } public string ToString(int startIndex, int length) { if (startIndex < 0 || length < 0 || startIndex + length > this.length) { throw new ArgumentOutOfRangeException(); } return new string(this.data, startIndex, length); } private void EnsureSpace(int space) { if (this.length + space > this.capacity) { do { this.capacity <<= 1; } while (this.capacity < this.length + space); char[] newData = new char[capacity]; Array.Copy(this.data, 0, newData, 0, this.length); this.data = newData; } } public int Length { get { return this.length; } set { if (value < 0) { throw new ArgumentOutOfRangeException(); } if (value > this.length) { this.EnsureSpace(this.length - value); for (int i = this.length; i < value; i++) { this.data[i] = '\x0000'; } } this.length = value; } } public int Capacity { get { return this.capacity; } } [IndexerName("Chars")] public char this[int index] { get { if (index < 0 || index >= this.length) { throw new IndexOutOfRangeException(); } return this.data[index]; } set { if (index < 0 || index >= this.length) { throw new IndexOutOfRangeException(); } this.data[index] = value; } } public void CopyTo(int srcIndex, char[] dst, int dstIndex, int count) { if (dst == null) { throw new ArgumentNullException("destination"); } if (srcIndex < 0 || count < 0 || dstIndex < 0 || srcIndex + count > this.length || dstIndex + count > dst.Length) { throw new ArgumentOutOfRangeException(); } Array.Copy(this.data, srcIndex, dst, dstIndex, count); } public void EnsureCapacity(int capacity) { if (this.capacity < capacity) { // This is not quite right, as it will often over-allocate memory this.EnsureSpace(capacity - this.capacity); } } public StringBuilder Remove(int startIndex, int length) { if (startIndex < 0 || length < 0 || startIndex + length > this.length) { throw new ArgumentOutOfRangeException(); } Array.Copy(this.data, startIndex + length, this.data, startIndex, this.length - length - startIndex); this.length -= length; return this; } #region Append Methods public StringBuilder Append(string value) { int len = value.Length; this.EnsureSpace(len); for (int i = 0; i < len; i++) { this.data[this.length++] = value[i]; } return this; } public StringBuilder Append(string value, int startIndex, int count) { if (value == null) { return this; } if (startIndex < 0 || count < 0 || value.Length < startIndex + count) { throw new ArgumentOutOfRangeException(); } this.EnsureSpace(count); for (int i = 0; i < count; i++) { this.data[this.length++] = value[startIndex + i]; } return this; } public StringBuilder Append(char value) { EnsureSpace(1); data[length++] = value; return this; } public StringBuilder Append(char value, int repeatCount) { if (repeatCount < 0) { throw new ArgumentOutOfRangeException(); } EnsureSpace(repeatCount); for (int i = 0; i < repeatCount; i++) { this.data[this.length++] = value; } return this; } public StringBuilder Append(char[] value) { if (value == null) { return this; } int addLen = value.Length; this.EnsureSpace(addLen); Array.Copy(value, 0, this.data, this.length, addLen); this.length += addLen; return this; } public StringBuilder Append(char[] value, int startIndex, int charCount) { if (value == null) { return this; } if (charCount < 0 || startIndex < 0 || value.Length < (startIndex + charCount)) { throw new ArgumentOutOfRangeException(); } this.EnsureSpace(charCount); Array.Copy(value, startIndex, this.data, this.length, charCount); this.length += charCount; return this; } public StringBuilder Append(object value) { if (value == null) { return this; } return Append(value.ToString()); } public StringBuilder Append(bool value) { return Append(value.ToString()); } public StringBuilder Append(byte value) { return Append(value.ToString()); } public StringBuilder Append(decimal value) { return Append(value.ToString()); } public StringBuilder Append(double value) { return Append(value.ToString()); } public StringBuilder Append(short value) { return Append(value.ToString()); } public StringBuilder Append(int value) { return Append(value.ToString()); } public StringBuilder Append(long value) { return Append(value.ToString()); } public StringBuilder Append(sbyte value) { return Append(value.ToString()); } public StringBuilder Append(float value) { return Append(value.ToString()); } public StringBuilder Append(ushort value) { return Append(value.ToString()); } public StringBuilder Append(uint value) { return Append(value.ToString()); } public StringBuilder Append(ulong value) { return Append(value.ToString()); } #endregion #region AppendFormat Methods public StringBuilder AppendFormat(string format, object obj0) { StringHelper.FormatHelper(this, null, format, obj0); return this; } public StringBuilder AppendFormat(string format, object obj0, object obj1) { StringHelper.FormatHelper(this, null, format, obj0, obj1); return this; } public StringBuilder AppendFormat(string format, object obj0, object obj1, object obj2) { StringHelper.FormatHelper(this, null, format, obj0, obj1, obj2); return this; } public StringBuilder AppendFormat(string format, params object[] objs) { StringHelper.FormatHelper(this, null, format, objs); return this; } public StringBuilder AppendFormat(IFormatProvider provider, string format, params object[] objs) { StringHelper.FormatHelper(this, provider, format, objs); return this; } #endregion #region AppendLine Methods public StringBuilder AppendLine() { return this.Append(Environment.NewLine); } public StringBuilder AppendLine(string value) { return this.Append(value).Append(Environment.NewLine); } #endregion #region Insert Methods public StringBuilder Insert(int index, string value) { if (index < 0 || index > this.length) { throw new ArgumentOutOfRangeException(); } if (string.IsNullOrEmpty(value)) { return this; } int len = value.Length; EnsureSpace(len); Array.Copy(this.data, index, this.data, index + len, this.length - index); for (int i = 0; i < len; i++) { this.data[index + i] = value[i]; } this.length += len; return this; } public StringBuilder Insert(int index, bool value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, byte value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, char value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, char[] value) { return this.Insert(index, new string(value)); } public StringBuilder Insert(int index, decimal value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, double value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, short value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, int value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, long value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, object value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, sbyte value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, float value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, ushort value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, uint value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, ulong value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, string value, int count) { if (count < 0) { throw new ArgumentOutOfRangeException(); } if (count == 0 || string.IsNullOrEmpty(value)) { return this; } StringBuilder toInsert = new StringBuilder(value.Length * count); for (; count > 0; count--) { toInsert.Append(value); } return this.Insert(index, toInsert.ToString()); } public StringBuilder Insert(int index, char[] value, int startIndex, int charCount) { if (value == null && (startIndex != 0 || charCount != 0)) { throw new ArgumentNullException("value"); } if (startIndex < 0 || charCount < 0 || startIndex + charCount > value.Length) { throw new ArgumentOutOfRangeException(); } return this.Insert(index, new string(value, startIndex, charCount)); } #endregion #region Replace Methods public StringBuilder Replace(char oldChar, char newChar) { return this.Replace(oldChar, newChar, 0, this.length); } public StringBuilder Replace(string oldValue, string newValue) { return this.Replace(oldValue, newValue, 0, this.length); } public StringBuilder Replace(char oldChar, char newChar, int startIndex, int count) { if (startIndex < 0 || count < 0 || startIndex + count > this.length) { throw new ArgumentOutOfRangeException(); } for (int i = 0; i < count; i++) { if (this.data[startIndex + i] == oldChar) { this.data[startIndex + i] = newChar; } } return this; } public StringBuilder Replace(string oldValue, string newValue, int startIndex, int count) { string subStr = this.ToString(startIndex, count); subStr = subStr.Replace(oldValue, newValue); this.Remove(startIndex, count); this.Insert(startIndex, subStr); return this; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\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 ExtractSByte1() { var test = new SimpleUnaryOpTest__ExtractSByte1(); try { if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // 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(); if (Sse2.IsSupported) { // 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(); if (Sse2.IsSupported) { // 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(); } } catch (PlatformNotSupportedException) { test.Succeeded = true; } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ExtractSByte1 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(SByte); private const int RetElementCount = VectorSize / sizeof(SByte); private static SByte[] _data = new SByte[Op1ElementCount]; private static Vector128<SByte> _clsVar; private Vector128<SByte> _fld; private SimpleUnaryOpTest__DataTable<SByte, SByte> _dataTable; static SimpleUnaryOpTest__ExtractSByte1() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)(random.Next(0, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar), ref Unsafe.As<SByte, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ExtractSByte1() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)(random.Next(0, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld), ref Unsafe.As<SByte, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)(random.Next(0, sbyte.MaxValue)); } _dataTable = new SimpleUnaryOpTest__DataTable<SByte, SByte>(_data, new SByte[RetElementCount], VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.Extract( Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse41.Extract( Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse41.Extract( Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<SByte>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (SByte)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<SByte>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (SByte)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<SByte>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (SByte)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse41.Extract( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr); var result = Sse41.Extract(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)); var result = Sse41.Extract(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)); var result = Sse41.Extract(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ExtractSByte1(); var result = Sse41.Extract(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse41.Extract(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<SByte> firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "") { if ((result[0] != firstOp[1])) { Succeeded = false; } if (!Succeeded) { Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.Extract)}<SByte>(Vector128<SByte><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; using log4net; using Axiom.Graphics; using Axiom.MathLib; using Axiom.Collections; namespace Axiom.Core { ///<summary> /// A GeometryBucket is a the lowest level bucket where geometry with /// the same vertex & index format is stored. It also acts as the /// renderable. ///</summary> public class GeometryBucket : IRenderable, IDisposable { #region Fields and Properties // Create a logger for use in this class private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(GeometryBucket)); // Geometry which has been queued up pre-build (not for deallocation) protected List<QueuedGeometry> queuedGeometry; // Pointer to parent bucket protected MaterialBucket parent; // String identifying the vertex / index format protected string formatString; // Vertex information, includes current number of vertices // committed to be a part of this bucket protected VertexData vertexData; // Index information, includes index type which limits the max // number of vertices which are allowed in one bucket protected IndexData indexData; // Size of indexes protected IndexType indexType; // Maximum vertex indexable protected int maxVertexIndex; protected Hashtable customParams = new Hashtable(); public MaterialBucket Parent { get { return parent; } } // Get the vertex data for this geometry public VertexData VertexData { get { return vertexData; } } // Get the index data for this geometry public IndexData IndexData { get { return indexData; } } // @copydoc Renderable::getMaterial public Material Material { get { return parent.Material; } } public Technique Technique { get { return parent.CurrentTechnique; } } public Quaternion WorldOrientation { get { return Quaternion.Identity; } } public Vector3 WorldPosition { get { return parent.Parent.Parent.Center; } } public List<Light> Lights { get { return parent.Parent.Parent.Lights; } } public bool CastsShadows { get { return parent.Parent.Parent.CastShadows; } } #endregion Fields and Properties #region Constructors public GeometryBucket(MaterialBucket parent, string formatString, VertexData vData, IndexData iData) { // Clone the structure from the example this.parent = parent; this.formatString = formatString; vertexData = vData.Clone(false); indexData = iData.Clone(false); vertexData.vertexCount = 0; vertexData.vertexStart = 0; indexData.indexCount = 0; indexData.indexStart = 0; indexType = indexData.indexBuffer.Type; queuedGeometry = new List<QueuedGeometry>(); // Derive the max vertices if (indexType == IndexType.Size32) maxVertexIndex = int.MaxValue; else maxVertexIndex = ushort.MaxValue; // Check to see if we have blend indices / blend weights // remove them if so, they can try to blend non-existent bones! VertexElement blendIndices = vertexData.vertexDeclaration.FindElementBySemantic(VertexElementSemantic.BlendIndices); VertexElement blendWeights = vertexData.vertexDeclaration.FindElementBySemantic(VertexElementSemantic.BlendWeights); if (blendIndices != null && blendWeights != null) { Debug.Assert(blendIndices.Source == blendWeights.Source, "Blend indices and weights should be in the same buffer"); // Get the source ushort source = blendIndices.Source; Debug.Assert(blendIndices.Size + blendWeights.Size == vertexData.vertexBufferBinding.GetBuffer(source).VertexSize, "Blend indices and blend buffers should have buffer to themselves!"); // Unset the buffer vertexData.vertexBufferBinding.UnsetBinding(source); // Remove the elements vertexData.vertexDeclaration.RemoveElement(VertexElementSemantic.BlendIndices); vertexData.vertexDeclaration.RemoveElement(VertexElementSemantic.BlendWeights); } } #endregion Constructors #region Public Methods public float GetSquaredViewDepth(Camera cam) { return parent.Parent.SquaredDistance; } public void GetRenderOperation(RenderOperation op) { op.indexData = indexData; op.operationType = OperationType.TriangleList; //op.srcRenderable = this; op.useIndices = true; op.vertexData = vertexData; } public void GetWorldTransforms(Matrix4[] xform) { // Should be the identity transform, but lets allow transformation of the // nodes the regions are attached to for kicks xform[0] = parent.Parent.Parent.ParentNodeFullTransform; } public bool Assign(QueuedGeometry qgeom) { // do we have enough space if(vertexData.vertexCount + qgeom.geometry.vertexData.vertexCount > maxVertexIndex) return false; queuedGeometry.Add(qgeom); vertexData.vertexCount += qgeom.geometry.vertexData.vertexCount; indexData.indexCount += qgeom.geometry.indexData.indexCount; return true; } public void Build(bool stencilShadows, bool logDetails) { // Ok, here's where we transfer the vertices and indexes to the shared buffers VertexDeclaration dcl = vertexData.vertexDeclaration; VertexBufferBinding binds = vertexData.vertexBufferBinding; // create index buffer, and lock if (logDetails) log.InfoFormat("GeometryBucket.Build: Creating index buffer indexType {0} indexData.indexCount {1}", indexType, indexData.indexCount); indexData.indexBuffer = HardwareBufferManager.Instance.CreateIndexBuffer(indexType, indexData.indexCount, BufferUsage.StaticWriteOnly); IntPtr indexBufferIntPtr = indexData.indexBuffer.Lock(BufferLocking.Discard); // create all vertex buffers, and lock ushort b; ushort posBufferIdx = dcl.FindElementBySemantic(VertexElementSemantic.Position).Source; List<List<VertexElement>> bufferElements = new List<List<VertexElement>>(); unsafe { byte *[] destBufferPtrs = new byte*[binds.BindingCount]; for (b = 0; b < binds.BindingCount; ++b) { int vertexCount = vertexData.vertexCount; if (logDetails) log.InfoFormat("GeometryBucket.Build b {0}, binds.BindingCount {1}, vertexCount {2}, dcl.GetVertexSize(b) {3}", b, binds.BindingCount, vertexCount, dcl.GetVertexSize(b)); // Need to double the vertex count for the position buffer // if we're doing stencil shadows if(stencilShadows && b == posBufferIdx) { vertexCount = vertexCount * 2; if(vertexCount > maxVertexIndex) throw new Exception("Index range exceeded when using stencil shadows, consider " + "reducing your region size or reducing poly count"); } HardwareVertexBuffer vbuf = HardwareBufferManager.Instance.CreateVertexBuffer(dcl.GetVertexSize(b), vertexCount, BufferUsage.StaticWriteOnly); binds.SetBinding(b, vbuf); IntPtr pLock = vbuf.Lock(BufferLocking.Discard); destBufferPtrs[b] = (byte *)pLock.ToPointer(); // Pre-cache vertex elements per buffer bufferElements.Add(dcl.FindElementBySource(b)); } // iterate over the geometry items int indexOffset = 0; IEnumerator iter = queuedGeometry.GetEnumerator(); Vector3 regionCenter = parent.Parent.Parent.Center; int *pDestInt = (int *)indexBufferIntPtr.ToPointer(); ushort *pDestUShort = (ushort *)indexBufferIntPtr.ToPointer(); foreach (QueuedGeometry geom in queuedGeometry) { // copy indexes across with offset IndexData srcIdxData = geom.geometry.indexData; IntPtr srcIntPtr = srcIdxData.indexBuffer.Lock(BufferLocking.ReadOnly); if(indexType == IndexType.Size32) { int *pSrcInt = (int *)srcIntPtr.ToPointer(); for (int i=0; i<srcIdxData.indexCount; i++) *pDestInt++ = (*pSrcInt++) + indexOffset; } else { ushort *pSrcUShort = (ushort *)(srcIntPtr.ToPointer()); for (int i=0; i<srcIdxData.indexCount; i++) *pDestUShort++ = (ushort)((*pSrcUShort++) + indexOffset); } srcIdxData.indexBuffer.Unlock(); // Now deal with vertex buffers // we can rely on buffer counts / formats being the same VertexData srcVData = geom.geometry.vertexData; VertexBufferBinding srcBinds = srcVData.vertexBufferBinding; for(b = 0; b < binds.BindingCount; ++b) // Iterate over vertices destBufferPtrs[b] = CopyVertices(srcBinds.GetBuffer(b), destBufferPtrs[b], bufferElements[b], geom, regionCenter); indexOffset += geom.geometry.vertexData.vertexCount; } } // unlock everything indexData.indexBuffer.Unlock(); for(b = 0; b < binds.BindingCount; ++b) binds.GetBuffer(b).Unlock(); // If we're dealing with stencil shadows, copy the position data from // the early half of the buffer to the latter part if(stencilShadows) { unsafe { HardwareVertexBuffer buf = binds.GetBuffer(posBufferIdx); IntPtr src = buf.Lock(BufferLocking.Normal); byte * pSrc = (byte *)src.ToPointer(); // Point dest at second half (remember vertexcount is original count) byte * pDst = pSrc + buf.VertexSize * vertexData.vertexCount; int count = buf.VertexSize * buf.VertexCount; while(count-- > 0) *pDst++ = *pSrc++; buf.Unlock(); // Also set up hardware W buffer if appropriate RenderSystem rend = Root.Instance.RenderSystem; if(null != rend && rend.Caps.CheckCap(Capabilities.VertexPrograms)) { buf = HardwareBufferManager.Instance.CreateVertexBuffer(sizeof(float), vertexData.vertexCount * 2, BufferUsage.StaticWriteOnly, false); // Fill the first half with 1.0, second half with 0.0 float * pW = (float *)buf.Lock(BufferLocking.Discard).ToPointer(); for(int v = 0; v < vertexData.vertexCount; ++v) *pW++ = 1.0f; for(int v = 0; v < vertexData.vertexCount; ++v) *pW++ = 0.0f; buf.Unlock(); vertexData.hardwareShadowVolWBuffer = buf; } } } } public void Dump() { log.DebugFormat("---------------"); log.DebugFormat("Geometry Bucket"); log.DebugFormat("Format string: {0}", formatString); log.DebugFormat("Geometry items: {0}", queuedGeometry.Count); log.DebugFormat("Vertex count: {0}", vertexData.vertexCount); log.DebugFormat("Index count: {0}", indexData.indexCount); } #endregion #region Protected Methods protected unsafe byte *CopyVertices(HardwareVertexBuffer srcBuf, byte *pDst, List<VertexElement> elems, QueuedGeometry geom, Vector3 regionCenter) { // lock source IntPtr src = srcBuf.Lock(BufferLocking.ReadOnly); int bufInc = srcBuf.VertexSize; byte * pSrc = (byte *)src.ToPointer(); float * pSrcReal; float * pDstReal; Vector3 temp = Vector3.Zero; // Calculate elem sizes outside the loop int [] elemSizes = new int[elems.Count]; for (int i=0; i<elems.Count; i++) elemSizes[i] = VertexElement.GetTypeSize(elems[i].Type); // Move the position offset calculation outside the loop Vector3 positionDelta = geom.position - regionCenter; for(int v = 0; v < geom.geometry.vertexData.vertexCount; ++v) { // iterate over vertex elements for (int i=0; i<elems.Count; i++) { VertexElement elem = elems[i]; pSrcReal = (float *)(pSrc + elem.Offset); pDstReal = (float *)(pDst + elem.Offset); switch(elem.Semantic) { case VertexElementSemantic.Position: temp.x = *pSrcReal++; temp.y = *pSrcReal++; temp.z = *pSrcReal++; // transform temp = (geom.orientation * (temp * geom.scale)); *pDstReal++ = temp.x + positionDelta.x; *pDstReal++ = temp.y + positionDelta.y; *pDstReal++ = temp.z + positionDelta.z; break; case VertexElementSemantic.Normal: case VertexElementSemantic.Tangent: case VertexElementSemantic.Binormal: temp.x = *pSrcReal++; temp.y = *pSrcReal++; temp.z = *pSrcReal++; // rotation only temp = geom.orientation * temp; *pDstReal++ = temp.x; *pDstReal++ = temp.y; *pDstReal++ = temp.z; break; default: // just raw copy int size = elemSizes[i]; // Optimize the loop for the case that // these things are in units of 4 if ((size & 0x3) == 0x0) { int cnt = size / 4; while (cnt-- > 0) *pDstReal++ = *pSrcReal++; } else { // Fall back to the byte-by-byte copy byte * pbSrc = (byte*)pSrcReal; byte * pbDst = (byte*)pDstReal; while(size-- > 0) *pbDst++ = *pbSrc++; } break; } } // Increment both pointers pDst += bufInc; pSrc += bufInc; } srcBuf.Unlock(); return pDst; } #endregion #region IRenderable members /// TODO: Talk to Jeff about these parameters public bool NormalizeNormals { get { return false; } } public ushort NumWorldTransforms { get { return parent.Parent.Parent.NumWorldTransforms; } } public bool UseIdentityProjection { get { return false; } } public bool UseIdentityView { get { return false; } } public SceneDetailLevel RenderDetail { get { return SceneDetailLevel.Solid; } } public Vector4 GetCustomParameter(int index) { if(customParams[index] == null) { throw new Exception("A parameter was not found at the given index"); } else { return (Vector4)customParams[index]; } } public void SetCustomParameter(int index, Vector4 val) { customParams[index] = val; } public void UpdateCustomGpuParameter(GpuProgramParameters.AutoConstantEntry entry, GpuProgramParameters gpuParams) { if(customParams[entry.data] != null) { gpuParams.SetConstant(entry.index, (Vector4)customParams[entry.data]); } } /// <summary> /// Dispose the hardware index and vertex buffers /// </summary> public virtual void Dispose() { indexData.indexBuffer.Dispose(); VertexBufferBinding bindings = vertexData.vertexBufferBinding; for(ushort b = 0; b < bindings.BindingCount; ++b) bindings.GetBuffer(b).Dispose(); } #endregion } }
// // 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 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using Microsoft.PackageManagement.Internal.Utility.Platform; namespace Microsoft.PackageManagement.MetaProvider.PowerShell.Internal { using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Threading; using Microsoft.PackageManagement.Internal.Utility.Extensions; using Microsoft.PackageManagement.Internal.Utility.Platform; using Messages = Microsoft.PackageManagement.MetaProvider.PowerShell.Resources.Messages; using System.Collections.Concurrent; public class PowerShellProviderBase : IDisposable { private object _lock = new Object(); protected PSModuleInfo _module; private PowerShell _powershell; private ManualResetEvent _reentrancyLock = new ManualResetEvent(true); private readonly Dictionary<string, CommandInfo> _allCommands = new Dictionary<string, CommandInfo>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, CommandInfo> _methods = new Dictionary<string, CommandInfo>(StringComparer.OrdinalIgnoreCase); public PowerShellProviderBase(PowerShell ps, PSModuleInfo module) { if (module == null) { throw new ArgumentNullException("module"); } _powershell = ps; _module = module; // combine all the cmdinfos we care about // but normalize the keys as we go (remove any '-' '_' chars) foreach (var k in _module.ExportedAliases.Keys) { _allCommands.AddOrSet(k.Replace("-", "").Replace("_", ""), _module.ExportedAliases[k]); } foreach (var k in _module.ExportedCmdlets.Keys) { _allCommands.AddOrSet(k.Replace("-", "").Replace("_", ""), _module.ExportedCmdlets[k]); } foreach (var k in _module.ExportedFunctions.Keys) { _allCommands.AddOrSet(k.Replace("-", "").Replace("_", ""), _module.ExportedFunctions[k]); } } public string ModulePath { get { return _module.Path; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (_powershell != null) { _powershell.Dispose(); _powershell = null; } if (_reentrancyLock != null) { _reentrancyLock.Dispose(); _reentrancyLock = null; } _module = null; } } internal CommandInfo GetMethod(string methodName) { return _methods.GetOrAdd(methodName, () => { if (_allCommands.ContainsKey(methodName)) { return _allCommands[methodName]; } // try simple plurals to single if (methodName.EndsWith("s", StringComparison.OrdinalIgnoreCase)) { var meth = methodName.Substring(0, methodName.Length - 1); if (_allCommands.ContainsKey(meth)) { return _allCommands[meth]; } } // try words like Dependencies to Dependency if (methodName.EndsWith("cies", StringComparison.OrdinalIgnoreCase)) { var meth = methodName.Substring(0, methodName.Length - 4) + "cy"; if (_allCommands.ContainsKey(meth)) { return _allCommands[meth]; } } // try IsFoo to Test-IsFoo if (methodName.IndexOf("Is", StringComparison.OrdinalIgnoreCase) == 0) { var meth = "test" + methodName; if (_allCommands.ContainsKey(meth)) { return _allCommands[meth]; } } if (methodName.IndexOf("add", StringComparison.OrdinalIgnoreCase) == 0) { // try it with 'register' instead var result = GetMethod("register" + methodName.Substring(3)); if (result != null) { return result; } } if (methodName.IndexOf("remove", StringComparison.OrdinalIgnoreCase) == 0) { // try it with 'register' instead var result = GetMethod("unregister" + methodName.Substring(6)); if (result != null) { return result; } } // can't find one, return null. return null; }); // hmm, it is possible to get the parameter types to match better when binding. // module.ExportedFunctions.FirstOrDefault().Value.Parameters.Values.First().ParameterType } internal object CallPowerShellWithoutRequest(string method, params object[] args) { var cmdInfo = GetMethod(method); if (cmdInfo == null) { return null; } var result = _powershell.InvokeFunction<object>(cmdInfo.Name, null, null, args); if (result == null) { // failure! throw new Exception(Messages.PowershellScriptFunctionReturnsNull.format(_module.Name, method)); } return result; } // lock is on this instance only internal void ReportErrors(PsRequest request, IEnumerable<ErrorRecord> errors) { foreach (var error in errors) { request.Error(error.FullyQualifiedErrorId, error.CategoryInfo.Category.ToString(), error.TargetObject == null ? null : error.TargetObject.ToString(), error.ErrorDetails == null ? error.Exception.Message : error.ErrorDetails.Message); if (!string.IsNullOrWhiteSpace(error.Exception.StackTrace)) { // give a debug hint if we have a script stack trace. How nice of us. // the exception stack trace gives better stack than the script stack trace request.Debug(Constants.ScriptStackTrace, error.Exception.StackTrace); } } } private IAsyncResult _stopResult; private object _stopLock = new object(); internal void CancelRequest() { if (!_reentrancyLock.WaitOne(0)) { // it's running right now. #if DEBUG NativeMethods.OutputDebugString("[Cmdlet:debugging] -- Stopping powershell script."); #endif lock (_stopLock) { if (_stopResult == null) { _stopResult = _powershell.BeginStop(ar => { }, null); } } } } internal object CallPowerShell(PsRequest request, params object[] args) { // the lock ensures that we're not re-entrant into the same powershell runspace lock (_lock) { if (!_reentrancyLock.WaitOne(0)) { // this lock is set to false, meaning we're still in a call **ON THIS THREAD** // this is bad karma -- powershell won't let us call into the runspace again // we're going to throw an error here because this indicates that the currently // running powershell call is calling back into PM, and it has called back // into this provider. That's just bad bad bad. throw new Exception("Reentrancy Violation in powershell module"); } try { // otherwise, this is the first time we've been here during this call. _reentrancyLock.Reset(); _powershell.SetVariable("request", request); _powershell.Streams.ClearStreams(); object finalValue = null; ConcurrentBag<ErrorRecord> errors = new ConcurrentBag<ErrorRecord>(); request.Debug("INVOKING PowerShell Fn {0} with args {1} that has length {2}", request.CommandInfo.Name, String.Join(", ", args), args.Length); var result = _powershell.InvokeFunction<object>(request.CommandInfo.Name, (sender, e) => output_DataAdded(sender, e, request, ref finalValue), (sender, e) => error_DataAdded(sender, e, request, errors), args); if (result == null) { // result is null but it does not mean that the call fails because the command may return nothing request.Debug(Messages.PowershellScriptFunctionReturnsNull.format(_module.Name, request.CommandInfo.Name)); } if (errors.Count > 0) { // report the error if there are any ReportErrors(request, errors); _powershell.Streams.Error.Clear(); } return finalValue; } catch (CmdletInvocationException cie) { var error = cie.ErrorRecord; request.Error(error.FullyQualifiedErrorId, error.CategoryInfo.Category.ToString(), error.TargetObject == null ? null : error.TargetObject.ToString(), error.ErrorDetails == null ? error.Exception.Message : error.ErrorDetails.Message); } finally { lock (_stopLock) { if (_stopResult != null){ _powershell.EndStop(_stopResult); _stopResult = null; } } _powershell.Clear(); _powershell.SetVariable("request", null); // it's ok if someone else calls into this module now. request.Debug("Done calling powershell", request.CommandInfo.Name, _module.Name); _reentrancyLock.Set(); } return null; } } private void error_DataAdded(object sender, DataAddedEventArgs e, PsRequest request, ConcurrentBag<ErrorRecord> errors) { PSDataCollection<ErrorRecord> errorStream = sender as PSDataCollection<ErrorRecord>; if (errorStream == null) { return; } var error = errorStream[e.Index]; if (error != null) { // add the error so we can report them later errors.Add(error); } } private void output_DataAdded(object sender, DataAddedEventArgs e, PsRequest request, ref object finalValue) { PSDataCollection<PSObject> outputstream = sender as PSDataCollection<PSObject>; if (outputstream == null) { return; } PSObject psObject = outputstream[e.Index]; if (psObject != null) { var value = psObject.ImmediateBaseObject; var y = value as Yieldable; if (y != null) { // yield it to stream the result gradually y.YieldResult(request); } else { finalValue = value; return; } } } } }
#region Foreign-License // .Net40 Kludge #endregion #if !CLR4 using System.Threading; using System.Diagnostics; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Runtime.Serialization; namespace System { /// <summary> /// Lazy /// </summary> /// <typeparam name="T"></typeparam> [Serializable, DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}"), DebuggerTypeProxy(typeof(System_LazyDebugView<>)), ComVisible(false), HostProtection(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)] public class Lazy<T> { private volatile object _boxed; [NonSerialized] private readonly object _threadSafeObj; [NonSerialized] private Func<T> m_valueFactory; private static Func<T> PUBLICATION_ONLY_OR_ALREADY_INITIALIZED = (() => default(T)); static Lazy() { } //[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] /// <summary> /// Initializes a new instance of the <see cref="Lazy&lt;T&gt;"/> class. /// </summary> public Lazy() : this(LazyThreadSafetyMode.ExecutionAndPublication) { } /// <summary> /// Initializes a new instance of the <see cref="Lazy&lt;T&gt;"/> class. /// </summary> /// <param name="isThreadSafe">if set to <c>true</c> [is thread safe].</param> public Lazy(bool isThreadSafe) : this(isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None) { } //[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] /// <summary> /// Initializes a new instance of the <see cref="Lazy&lt;T&gt;"/> class. /// </summary> /// <param name="valueFactory">The value factory.</param> public Lazy(Func<T> valueFactory) : this(valueFactory, LazyThreadSafetyMode.ExecutionAndPublication) { } /// <summary> /// Initializes a new instance of the <see cref="Lazy&lt;T&gt;"/> class. /// </summary> /// <param name="mode">The mode.</param> public Lazy(LazyThreadSafetyMode mode) { _threadSafeObj = GetObjectFromMode(mode); } /// <summary> /// Initializes a new instance of the <see cref="Lazy&lt;T&gt;"/> class. /// </summary> /// <param name="valueFactory">The value factory.</param> /// <param name="isThreadSafe">if set to <c>true</c> [is thread safe].</param> public Lazy(Func<T> valueFactory, bool isThreadSafe) : this(valueFactory, isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None) { } /// <summary> /// Initializes a new instance of the <see cref="Lazy&lt;T&gt;"/> class. /// </summary> /// <param name="valueFactory">The value factory.</param> /// <param name="mode">The mode.</param> public Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode) { if (valueFactory == null) throw new ArgumentNullException("valueFactory"); _threadSafeObj = GetObjectFromMode(mode); m_valueFactory = valueFactory; } private Boxed CreateValue() { Boxed boxed = null; LazyThreadSafetyMode mode = Mode; if (m_valueFactory != null) { try { if ((mode != LazyThreadSafetyMode.PublicationOnly) && (m_valueFactory == PUBLICATION_ONLY_OR_ALREADY_INITIALIZED)) throw new InvalidOperationException(EnvironmentEx2.GetResourceString("Lazy_Value_RecursiveCallsToValue")); var valueFactory = m_valueFactory; if (mode != LazyThreadSafetyMode.PublicationOnly) m_valueFactory = PUBLICATION_ONLY_OR_ALREADY_INITIALIZED; return new Boxed(valueFactory()); } catch (Exception exception) { if (mode != LazyThreadSafetyMode.PublicationOnly) _boxed = new LazyInternalExceptionHolder(exception.PrepareForRethrow()); throw; } } try { boxed = new Boxed((T)Activator.CreateInstance(typeof(T))); } catch (MissingMethodException) { Exception ex = new MissingMemberException(EnvironmentEx2.GetResourceString("Lazy_CreateValue_NoParameterlessCtorForT")); if (mode != LazyThreadSafetyMode.PublicationOnly) _boxed = new LazyInternalExceptionHolder(ex); throw ex; } return boxed; } private static object GetObjectFromMode(LazyThreadSafetyMode mode) { if (mode == LazyThreadSafetyMode.ExecutionAndPublication) return new object(); if (mode == LazyThreadSafetyMode.PublicationOnly) return PUBLICATION_ONLY_OR_ALREADY_INITIALIZED; if (mode != LazyThreadSafetyMode.None) throw new ArgumentOutOfRangeException("mode", EnvironmentEx2.GetResourceString("Lazy_ctor_ModeInvalid")); return null; } private T LazyInitValue() { Boxed boxed = null; switch (Mode) { case LazyThreadSafetyMode.None: boxed = CreateValue(); _boxed = boxed; break; case LazyThreadSafetyMode.PublicationOnly: boxed = CreateValue(); #pragma warning disable 420 if (Interlocked.CompareExchange(ref _boxed, boxed, null) != null) boxed = (Boxed)_boxed; #pragma warning restore 420 break; default: lock (_threadSafeObj) { if (_boxed == null) { boxed = CreateValue(); _boxed = boxed; } else { boxed = (_boxed as Boxed); if (boxed == null) { var holder = (_boxed as LazyInternalExceptionHolder); throw holder._exception; } } } break; } return boxed._value; } [OnSerializing] private void OnSerializing(StreamingContext context) { T local1 = Value; } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { if (!IsValueCreated) return EnvironmentEx2.GetResourceString("Lazy_ToString_ValueNotCreated"); return this.Value.ToString(); } /// <summary> /// Gets a value indicating whether this instance is value created. /// </summary> /// <value> /// <c>true</c> if this instance is value created; otherwise, <c>false</c>. /// </value> public bool IsValueCreated { //[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] get { return (_boxed != null && _boxed is Boxed); } } internal bool IsValueFaulted { get { return (_boxed is LazyInternalExceptionHolder); } } internal LazyThreadSafetyMode Mode { get { if (_threadSafeObj == null) return LazyThreadSafetyMode.None; if (_threadSafeObj == (object)PUBLICATION_ONLY_OR_ALREADY_INITIALIZED) return LazyThreadSafetyMode.PublicationOnly; return LazyThreadSafetyMode.ExecutionAndPublication; } } /// <summary> /// Gets the value. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public T Value { get { Boxed boxed = null; if (_boxed != null) { boxed = (_boxed as Boxed); if (boxed != null) return boxed._value; var holder = (_boxed as LazyInternalExceptionHolder); throw holder._exception; } //Debugger.NotifyOfCrossThreadDependency(); return LazyInitValue(); } } internal T ValueForDebugDisplay { get { if (!this.IsValueCreated) return default(T); return ((Boxed)_boxed)._value; } } [Serializable] private class Boxed { internal T _value; //[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] internal Boxed(T value) { _value = value; } } private class LazyInternalExceptionHolder { internal Exception _exception; //[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] internal LazyInternalExceptionHolder(Exception ex) { _exception = ex; } } } } #endif
#region License // Copyright (c) 2010-2019, Mark Final // 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 BuildAMation 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. #endregion // License using System.Linq; namespace VSSolutionBuilder { /// <summary> /// Utility class offering more useful functions for writing .vcxprojs /// </summary> static partial class Support { static private void AddModuleDirectoryCreationShellCommands( Bam.Core.Module module, Bam.Core.StringArray shellCommandLines) { foreach (var dir in module.OutputDirectories) { var quotedDir = dir.ToStringQuoteIfNecessary(); shellCommandLines.Add($"IF NOT EXIST {quotedDir} MKDIR {quotedDir}"); } } static private void AddModuleCommandLineShellCommand( Bam.Core.Module module, Bam.Core.StringArray shellCommandLines, bool includeEnvironmentVariables) { if (null == module.Tool) { throw new Bam.Core.Exception( $"Command line tool passed with module '{module.ToString()}' is invalid" ); } System.Diagnostics.Debug.Assert(module.Tool is Bam.Core.ICommandLineTool); var args = new Bam.Core.StringArray(); if (module.WorkingDirectory != null) { args.Add( $"cd /D {module.WorkingDirectory.ToStringQuoteIfNecessary()} &&" ); } var tool = module.Tool as Bam.Core.ICommandLineTool; if (tool.EnvironmentVariables != null && includeEnvironmentVariables) { foreach (var envVar in tool.EnvironmentVariables) { args.Add("set"); var content = new System.Text.StringBuilder(); content.Append($"{envVar.Key}="); foreach (var value in envVar.Value) { content.Append($"{value.ToStringQuoteIfNecessary()};"); } content.Append($"%{envVar.Key}%"); args.Add(content.ToString()); args.Add("&&"); } } args.Add(CommandLineProcessor.Processor.StringifyTool(tool)); args.AddRange( CommandLineProcessor.NativeConversion.Convert( module.Settings, module ) ); args.Add(CommandLineProcessor.Processor.TerminatingArgs(tool)); shellCommandLines.Add(args.ToString(' ')); } static private Bam.Core.Module GetModuleForProject( Bam.Core.Module requestingModule) { var projectModule = requestingModule.EncapsulatingModule; #if D_PACKAGE_PUBLISHER if (projectModule is Publisher.Collation) { (projectModule as Publisher.Collation).ForEachAnchor( (collation, anchor, customData) => { projectModule = anchor.SourceModule; }, null ); } #endif return projectModule; } private static void AddRedirectToFile( Bam.Core.TokenizedString outputFile, Bam.Core.StringArray shellCommandLines) { var command = shellCommandLines.Last(); shellCommandLines.Remove(command); var redirectedCommand = command + $" > {outputFile.ToString()}"; shellCommandLines.Add(redirectedCommand); } /// <summary> /// Add a custom build step for the module into the .vcxproj /// </summary> /// <param name="module">Module whose .vcxproj will be modified</param> /// <param name="inputs">List of input paths</param> /// <param name="outputs">List of output paths</param> /// <param name="message">Message to output when running the custom build step</param> /// <param name="commandList">List of commands to run</param> /// <param name="commandIsForFirstInputOnly">Whether the command should only be run on the first input, or all.</param> /// <param name="addInputFilesToProject">Whether to add input files to the project file</param> static public void AddCustomBuildStep( Bam.Core.Module module, System.Collections.Generic.IEnumerable<Bam.Core.TokenizedString> inputs, System.Collections.Generic.IEnumerable<Bam.Core.TokenizedString> outputs, string message, Bam.Core.StringArray commandList, bool commandIsForFirstInputOnly, bool addInputFilesToProject) { var projectModule = GetModuleForProject(module); var solution = Bam.Core.Graph.Instance.MetaData as VSSolution; var project = solution.EnsureProjectExists(projectModule.GetType(), projectModule.BuildEnvironment); var config = project.GetConfiguration(projectModule); var is_first_input = true; foreach (var input in inputs) { if (addInputFilesToProject) { config.AddOtherFile(input); } if (!is_first_input && commandIsForFirstInputOnly) { continue; } var customBuild = config.GetSettingsGroup( VSSettingsGroup.ESettingsGroup.CustomBuild, input ); customBuild.AddSetting("Command", commandList.ToString(System.Environment.NewLine), condition: config.ConditionText); customBuild.AddSetting("Message", message, condition: config.ConditionText); customBuild.AddSetting("Outputs", outputs, condition: config.ConditionText); customBuild.AddSetting("AdditionalInputs", inputs, condition: config.ConditionText); // TODO: incorrectly adds all inputs is_first_input = false; } } /// <summary> /// Add a custom build step for the .vcxproj based on an ICommandLineTool /// </summary> /// <param name="module">Module containing the ICommandLineTool to run</param> /// <param name="outputPath">Output path generated from the build step</param> /// <param name="messagePrefix">Message to prefix the output with from running</param> /// <param name="addInputFilesToProject">Whether to add the input files to the project</param> static public void AddCustomBuildStepForCommandLineTool( Bam.Core.Module module, Bam.Core.TokenizedString outputPath, string messagePrefix, bool addInputFilesToProject) { var shellCommandLines = new Bam.Core.StringArray(); AddModuleDirectoryCreationShellCommands(module, shellCommandLines); AddModuleCommandLineShellCommand(module, shellCommandLines, includeEnvironmentVariables: true); System.Diagnostics.Debug.Assert(1 == module.InputModulePaths.Count()); var firstInput = module.InputModulePaths.First(); var sourcePath = firstInput.module.GeneratedPaths[firstInput.pathKey]; AddCustomBuildStep( module, System.Linq.Enumerable.Repeat(sourcePath, 1), System.Linq.Enumerable.Repeat(outputPath, 1), $"{messagePrefix} {sourcePath.ToString()} into {outputPath.ToString()}", shellCommandLines, true, addInputFilesToProject ); } /// <summary> /// Add prebuild steps for the module /// </summary> /// <param name="module">Module to add the prebuild steps for</param> /// <param name="config">Optional VSProjectConfiguration to add the prebuild step for. Default to null.</param> /// <param name="addOrderOnlyDependencyOnTool">Optional whether to add the tool as an order only dependency. Default to false.</param> static public void AddPreBuildSteps( Bam.Core.Module module, VSProjectConfiguration config = null, bool addOrderOnlyDependencyOnTool = false) { var solution = Bam.Core.Graph.Instance.MetaData as VSSolution; if (config == null) { var projectModule = GetModuleForProject(module); var project = solution.EnsureProjectExists(projectModule.GetType(), projectModule.BuildEnvironment); config = project.GetConfiguration(projectModule); } var shellCommandLines = new Bam.Core.StringArray(); AddModuleDirectoryCreationShellCommands(module, shellCommandLines); AddModuleCommandLineShellCommand(module, shellCommandLines, includeEnvironmentVariables: true); config.AddPreBuildCommands(shellCommandLines); if (addOrderOnlyDependencyOnTool) { var tool = module.Tool as Bam.Core.Module; #if D_PACKAGE_PUBLISHER // note the custom handler here, which checks to see if we're running a tool // that has been collated if (tool is Publisher.CollatedCommandLineTool) { tool = (tool as Publisher.ICollatedObject).SourceModule; } #endif var toolProject = solution.EnsureProjectExists(tool.GetType(), tool.BuildEnvironment); config.RequiresProject(toolProject); } } /// <summary> /// Add post-build steps for the module /// </summary> /// <param name="module">Module whose tool generates command lines</param> /// <param name="config">Optional VSProjectConfiguration to add to. Default to null.</param> /// <param name="addOrderOnlyDependencyOnTool">Optional whether the tool is added as an order only dependency. Default to false.</param> static public void AddPostBuildSteps( Bam.Core.Module module, VSProjectConfiguration config = null, bool addOrderOnlyDependencyOnTool = false) { var solution = Bam.Core.Graph.Instance.MetaData as VSSolution; if (config == null) { var projectModule = GetModuleForProject(module); var project = solution.EnsureProjectExists(projectModule.GetType(), projectModule.BuildEnvironment); config = project.GetConfiguration(projectModule); } var shellCommandLines = new Bam.Core.StringArray(); AddModuleDirectoryCreationShellCommands(module, shellCommandLines); AddModuleCommandLineShellCommand(module, shellCommandLines, includeEnvironmentVariables: true); config.AddPostBuildCommands(shellCommandLines); if (addOrderOnlyDependencyOnTool) { var tool = module.Tool as Bam.Core.Module; #if D_PACKAGE_PUBLISHER // note the custom handler here, which checks to see if we're running a tool // that has been collated if (tool is Publisher.CollatedCommandLineTool) { tool = (tool as Publisher.ICollatedObject).SourceModule; } #endif var toolProject = solution.EnsureProjectExists(tool.GetType(), tool.BuildEnvironment); config.RequiresProject(toolProject); } } /// <summary> /// Add custom shell commands to a post build step /// </summary> /// <param name="config">VSProjectConfiguration add to</param> /// <param name="module">Module corresponding to the project</param> /// <param name="commands">List of shell commands to add</param> static public void AddCustomPostBuildStep( VSProjectConfiguration config, Bam.Core.Module module, Bam.Core.StringArray commands) { var shellCommandLines = new Bam.Core.StringArray(); AddModuleDirectoryCreationShellCommands(module, shellCommandLines); shellCommandLines.AddRange(commands); config.AddPostBuildCommands(shellCommandLines); } /// <summary> /// Add a post build step corresponding to an ICommandLineTool /// </summary> /// <param name="module">Module with ICommandLineTool</param> /// <param name="moduleToAddBuildStepTo">The Module corresponding to the VSProject to add to</param> /// <param name="project">The VSProject written</param> /// <param name="configuration">The VSProjectConfiguration written</param> /// <param name="redirectToFile">Optional whether the output from the commands are redirected to this file. Default to null.</param> /// <param name="includeEnvironmentVariables">Optional whether environment variables are added to the commands. Default to true.</param> static public void AddPostBuildStepForCommandLineTool( Bam.Core.Module module, Bam.Core.Module moduleToAddBuildStepTo, out VSProject project, out VSProjectConfiguration configuration, Bam.Core.TokenizedString redirectToFile = null, bool includeEnvironmentVariables = true) { var solution = Bam.Core.Graph.Instance.MetaData as VSSolution; project = solution.EnsureProjectExists(moduleToAddBuildStepTo.GetType(), moduleToAddBuildStepTo.BuildEnvironment); configuration = project.GetConfiguration(moduleToAddBuildStepTo); var shellCommandLines = new Bam.Core.StringArray(); AddModuleDirectoryCreationShellCommands(module, shellCommandLines); AddModuleCommandLineShellCommand(module, shellCommandLines, includeEnvironmentVariables: includeEnvironmentVariables); if (null != redirectToFile) { AddRedirectToFile(redirectToFile, shellCommandLines); } configuration.AddPostBuildCommands(shellCommandLines); } /// <summary> /// Add a pre build step corresponding to an ICommandLineTool /// </summary> /// <param name="module">Module with ICommandLineTool</param> /// <param name="project">The VSProject written</param> /// <param name="configuration">The VSProjectConfiguration written</param> /// <param name="redirectToFile">Optional whether the output from the commands are redirected to this file. Default to null.</param> /// <param name="includeEnvironmentVariables">Optional whether environment variables are added to the commands. Default to true.</param> static public void AddPreBuildStepForCommandLineTool( Bam.Core.Module module, out VSProject project, out VSProjectConfiguration configuration, Bam.Core.TokenizedString redirectToFile = null, bool includeEnvironmentVariables = true) { var moduleToAddBuildStepTo = GetModuleForProject(module); var solution = Bam.Core.Graph.Instance.MetaData as VSSolution; project = solution.EnsureProjectExists(moduleToAddBuildStepTo.GetType(), moduleToAddBuildStepTo.BuildEnvironment); configuration = project.GetConfiguration(moduleToAddBuildStepTo); var shellCommandLines = new Bam.Core.StringArray(); AddModuleDirectoryCreationShellCommands(module, shellCommandLines); AddModuleCommandLineShellCommand(module, shellCommandLines, includeEnvironmentVariables: includeEnvironmentVariables); if (null != redirectToFile) { AddRedirectToFile(redirectToFile, shellCommandLines); } configuration.AddPreBuildCommands(shellCommandLines); } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. 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. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Xml; using System.Data; using System.Collections; namespace fyiReporting.Data { /// <summary> /// iTunesCommand represents the command. The user is allowed to specify the table needed. /// </summary> public class iTunesCommand : IDbCommand { iTunesConnection _xc; // connection we're running under string _cmd; // command to execute // parsed constituents of the command string _Table; // table requested DataParameterCollection _Parameters = new DataParameterCollection(); public iTunesCommand(iTunesConnection conn) { _xc = conn; } internal string Table { get { IDbDataParameter dp= _Parameters["Table"] as IDbDataParameter; if (dp == null) dp= _Parameters["@Table"] as IDbDataParameter; // Then check to see if the Table value is a parameter? if (dp == null) dp = _Parameters[_Table] as IDbDataParameter; if (dp != null) return dp.Value != null? dp.Value.ToString(): _Table; // don't pass null; pass existing value return _Table; // the value must be a constant } set {_Table = value;} } #region IDbCommand Members public void Cancel() { throw new NotImplementedException("Cancel not implemented"); } public void Prepare() { return; // Prepare is a noop } public System.Data.CommandType CommandType { get { throw new NotImplementedException("CommandType not implemented"); } set { throw new NotImplementedException("CommandType not implemented"); } } public IDataReader ExecuteReader(System.Data.CommandBehavior behavior) { if (!(behavior == CommandBehavior.SingleResult || behavior == CommandBehavior.SchemaOnly)) throw new ArgumentException("ExecuteReader supports SingleResult and SchemaOnly only."); return new iTunesDataReader(behavior, _xc, this); } IDataReader System.Data.IDbCommand.ExecuteReader() { return ExecuteReader(System.Data.CommandBehavior.SingleResult); } public object ExecuteScalar() { throw new NotImplementedException("ExecuteScalar not implemented"); } public int ExecuteNonQuery() { throw new NotImplementedException("ExecuteNonQuery not implemented"); } public int CommandTimeout { get { return 0; } set { throw new NotImplementedException("CommandTimeout not implemented"); } } public IDbDataParameter CreateParameter() { return new XmlDataParameter(); } public IDbConnection Connection { get { return this._xc; } set { throw new NotImplementedException("Setting Connection not implemented"); } } public System.Data.UpdateRowSource UpdatedRowSource { get { throw new NotImplementedException("UpdatedRowSource not implemented"); } set { throw new NotImplementedException("UpdatedRowSource not implemented"); } } public string CommandText { get { return this._cmd; } set { // Parse the command string for keyword value pairs separated by ';' string[] args = value.Split(';'); string table=null; foreach(string arg in args) { string[] param = arg.Trim().Split('='); if (param == null || param.Length != 2) continue; string key = param[0].Trim().ToLower(); string val = param[1]; switch (key) { case "table": table = val; break; default: throw new ArgumentException(string.Format("{0} is an unknown parameter key", param[0])); } } // User must specify both the url and the RowsXPath if (table == null) table = "Tracks"; _cmd = value; _Table = table; } } public IDataParameterCollection Parameters { get { return _Parameters; } } public IDbTransaction Transaction { get { throw new NotImplementedException("Transaction not implemented"); } set { throw new NotImplementedException("Transaction not implemented"); } } #endregion #region IDisposable Members public void Dispose() { // nothing to dispose of } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Xml.Schema; using System.Xml; #if XMLSERIALIZERGENERATOR namespace Microsoft.XmlSerializer.Generator #else namespace System.Xml.Serialization #endif { internal class ReflectionXmlSerializationWriter : XmlSerializationWriter { private XmlMapping _mapping; internal static TypeDesc StringTypeDesc { get; private set; } = (new TypeScope()).GetTypeDesc(typeof(string)); internal static TypeDesc QnameTypeDesc { get; private set; } = (new TypeScope()).GetTypeDesc(typeof(XmlQualifiedName)); public ReflectionXmlSerializationWriter(XmlMapping xmlMapping, XmlWriter xmlWriter, XmlSerializerNamespaces namespaces, string encodingStyle, string id) { Init(xmlWriter, namespaces, encodingStyle, id, null); if (!xmlMapping.IsWriteable || !xmlMapping.GenerateSerializer) { throw new ArgumentException(SR.Format(SR.XmlInternalError, nameof(xmlMapping))); } if (xmlMapping is XmlTypeMapping || xmlMapping is XmlMembersMapping) { _mapping = xmlMapping; } else { throw new ArgumentException(SR.Format(SR.XmlInternalError, nameof(xmlMapping))); } } protected override void InitCallbacks() { TypeScope scope = _mapping.Scope; foreach (TypeMapping mapping in scope.TypeMappings) { if (mapping.IsSoap && (mapping is StructMapping || mapping is EnumMapping) && !mapping.TypeDesc.IsRoot) { AddWriteCallback( mapping.TypeDesc.Type, mapping.TypeName, mapping.Namespace, CreateXmlSerializationWriteCallback(mapping, mapping.TypeName, mapping.Namespace, mapping.TypeDesc.IsNullable) ); } } } public void WriteObject(object o) { XmlMapping xmlMapping = _mapping; if (xmlMapping is XmlTypeMapping xmlTypeMapping) { WriteObjectOfTypeElement(o, xmlTypeMapping); } else if (xmlMapping is XmlMembersMapping xmlMembersMapping) { GenerateMembersElement(o, xmlMembersMapping); } } private void WriteObjectOfTypeElement(object o, XmlTypeMapping mapping) { GenerateTypeElement(o, mapping); } private void GenerateTypeElement(object o, XmlTypeMapping xmlMapping) { ElementAccessor element = xmlMapping.Accessor; TypeMapping mapping = element.Mapping; WriteStartDocument(); if (o == null) { string ns = (element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty); if (element.IsNullable) { if (mapping.IsSoap) { WriteNullTagEncoded(element.Name, ns); } else { WriteNullTagLiteral(element.Name, ns); } } else { WriteEmptyTag(element.Name, ns); } return; } if (!mapping.TypeDesc.IsValueType && !mapping.TypeDesc.Type.IsPrimitive) { TopLevelElement(); } WriteMember(o, null, new ElementAccessor[] { element }, null, null, mapping.TypeDesc, !element.IsSoap); if (mapping.IsSoap) { WriteReferencedElements(); } } private void WriteMember(object o, object choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc memberTypeDesc, bool writeAccessors) { if (memberTypeDesc.IsArrayLike && !(elements.Length == 1 && elements[0].Mapping is ArrayMapping)) { WriteArray(o, choiceSource, elements, text, choice, memberTypeDesc); } else { WriteElements(o, choiceSource, elements, text, choice, writeAccessors, memberTypeDesc.IsNullable); } } private void WriteArray(object o, object choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc arrayTypeDesc) { if (elements.Length == 0 && text == null) { return; } if (arrayTypeDesc.IsNullable && o == null) { return; } if (choice != null) { if (choiceSource == null || ((Array)choiceSource).Length < ((Array)o).Length) { throw CreateInvalidChoiceIdentifierValueException(choice.Mapping.TypeDesc.FullName, choice.MemberName); } } WriteArrayItems(elements, text, choice, arrayTypeDesc, o); } private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc arrayTypeDesc, object o) { TypeDesc arrayElementTypeDesc = arrayTypeDesc.ArrayElementTypeDesc; var a = o as IEnumerable; // #10593: This assert may not be true. We need more tests for this method. Debug.Assert(a != null); IEnumerator e = a.GetEnumerator(); if (e != null) { while (e.MoveNext()) { object ai = e.Current; WriteElements(ai, null/*choiceName + "i"*/, elements, text, choice, true, true); } } } private void WriteElements(object o, object enumSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, bool writeAccessors, bool isNullable) { if (elements.Length == 0 && text == null) return; if (elements.Length == 1 && text == null) { WriteElement(o, elements[0], writeAccessors); } else { if (isNullable && choice == null && o == null) { return; } int anyCount = 0; var namedAnys = new List<ElementAccessor>(); ElementAccessor unnamedAny = null; // can only have one string enumTypeName = choice?.Mapping.TypeDesc.FullName; for (int i = 0; i < elements.Length; i++) { ElementAccessor element = elements[i]; if (element.Any) { anyCount++; if (element.Name != null && element.Name.Length > 0) namedAnys.Add(element); else if (unnamedAny == null) unnamedAny = element; } else if (choice != null) { if (o != null && o.GetType() == element.Mapping.TypeDesc.Type) { WriteElement(o, element, writeAccessors); return; } } else { TypeDesc td = element.IsUnbounded ? element.Mapping.TypeDesc.CreateArrayTypeDesc() : element.Mapping.TypeDesc; if (o.GetType() == td.Type) { WriteElement(o, element, writeAccessors); return; } } } if (anyCount > 0) { if (o is XmlElement elem) { foreach (ElementAccessor element in namedAnys) { if (element.Name == elem.Name && element.Namespace == elem.NamespaceURI) { WriteElement(elem, element, writeAccessors); return; } } if (choice != null) { throw CreateChoiceIdentifierValueException(choice.Mapping.TypeDesc.FullName, choice.MemberName, elem.Name, elem.NamespaceURI); } if (unnamedAny != null) { WriteElement(elem, unnamedAny, writeAccessors); return; } throw CreateUnknownAnyElementException(elem.Name, elem.NamespaceURI); } } if (text != null) { bool useReflection = text.Mapping.TypeDesc.UseReflection; string fullTypeName = text.Mapping.TypeDesc.CSharpName; WriteText(o, text); return; } if (elements.Length > 0 && o != null) { throw CreateUnknownTypeException(o); } } } private void WriteText(object o, TextAccessor text) { if (text.Mapping is PrimitiveMapping primitiveMapping) { string stringValue; if (text.Mapping is EnumMapping enumMapping) { stringValue = WriteEnumMethod(enumMapping, o); } else { if (!WritePrimitiveValue(primitiveMapping.TypeDesc, o, false, out stringValue)) { // #10593: Add More Tests for Serialization Code Debug.Assert(o is byte[]); } } if (o is byte[] byteArray) { WriteValue(byteArray); } else { WriteValue(stringValue); } } else if (text.Mapping is SpecialMapping specialMapping) { switch (specialMapping.TypeDesc.Kind) { case TypeKind.Node: ((XmlNode)o).WriteTo(Writer); break; default: throw new InvalidOperationException(SR.Format(SR.XmlInternalError)); } } } private void WriteElement(object o, ElementAccessor element, bool writeAccessor) { string name = writeAccessor ? element.Name : element.Mapping.TypeName; string ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping.Namespace) : string.Empty); if (element.Mapping is NullableMapping nullableMapping) { if (o != null) { ElementAccessor e = element.Clone(); e.Mapping = nullableMapping.BaseMapping; WriteElement(o, e, writeAccessor); } else if (element.IsNullable) { WriteNullTagLiteral(element.Name, ns); } } else if (element.Mapping is ArrayMapping) { var mapping = element.Mapping as ArrayMapping; if (element.IsNullable && o == null) { WriteNullTagLiteral(element.Name, element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty); } else if (mapping.IsSoap) { if (mapping.Elements == null || mapping.Elements.Length != 1) { throw new InvalidOperationException(SR.XmlInternalError); } if (!writeAccessor) { WritePotentiallyReferencingElement(name, ns, o, mapping.TypeDesc.Type, true, element.IsNullable); } else { WritePotentiallyReferencingElement(name, ns, o, null, false, element.IsNullable); } } else if (element.IsUnbounded) { TypeDesc arrayTypeDesc = mapping.TypeDesc.CreateArrayTypeDesc(); var enumerable = (IEnumerable)o; foreach (var e in enumerable) { element.IsUnbounded = false; WriteElement(e, element, writeAccessor); element.IsUnbounded = true; } } else { if (o != null) { WriteStartElement(name, ns, false); WriteArrayItems(mapping.ElementsSortedByDerivation, null, null, mapping.TypeDesc, o); WriteEndElement(); } } } else if (element.Mapping is EnumMapping) { if (element.Mapping.IsSoap) { Writer.WriteStartElement(name, ns); WriteEnumMethod((EnumMapping)element.Mapping, o); WriteEndElement(); } else { WritePrimitive(WritePrimitiveMethodRequirement.WriteElementString, name, ns, element.Default, o, element.Mapping, false, true, element.IsNullable); } } else if (element.Mapping is PrimitiveMapping) { var mapping = element.Mapping as PrimitiveMapping; if (mapping.TypeDesc == QnameTypeDesc) { WriteQualifiedNameElement(name, ns, element.Default, (XmlQualifiedName)o, element.IsNullable, mapping.IsSoap, mapping); } else { WritePrimitiveMethodRequirement suffixNullable = mapping.IsSoap ? WritePrimitiveMethodRequirement.Encoded : WritePrimitiveMethodRequirement.None; WritePrimitiveMethodRequirement suffixRaw = mapping.TypeDesc.XmlEncodingNotRequired ? WritePrimitiveMethodRequirement.Raw : WritePrimitiveMethodRequirement.None; WritePrimitive(element.IsNullable ? WritePrimitiveMethodRequirement.WriteNullableStringLiteral | suffixNullable | suffixRaw : WritePrimitiveMethodRequirement.WriteElementString | suffixRaw, name, ns, element.Default, o, mapping, mapping.IsSoap, true, element.IsNullable); } } else if (element.Mapping is StructMapping) { var mapping = element.Mapping as StructMapping; if (mapping.IsSoap) { WritePotentiallyReferencingElement(name, ns, o, !writeAccessor ? mapping.TypeDesc.Type : null, !writeAccessor, element.IsNullable); } else { WriteStructMethod(mapping, name, ns, o, element.IsNullable, needType: false); } } else if (element.Mapping is SpecialMapping) { if (element.Mapping is SerializableMapping) { WriteSerializable((IXmlSerializable)o, name, ns, element.IsNullable, !element.Any); } else { // XmlNode, XmlElement if (o is XmlNode node) { WriteElementLiteral(node, name, ns, element.IsNullable, element.Any); } else { throw CreateInvalidAnyTypeException(o); } } } else { throw new InvalidOperationException(SR.XmlInternalError); } } private XmlSerializationWriteCallback CreateXmlSerializationWriteCallback(TypeMapping mapping, string name, string ns, bool isNullable) { if (mapping is StructMapping structMapping) { return (o) => { WriteStructMethod(structMapping, name, ns, o, isNullable, needType: false); }; } else if (mapping is EnumMapping enumMapping) { return (o) => { WriteEnumMethod(enumMapping, o); }; } else { throw new InvalidOperationException(SR.Format(SR.XmlInternalError)); } } private void WriteQualifiedNameElement(string name, string ns, object defaultValue, XmlQualifiedName o, bool nullable, bool isSoap, PrimitiveMapping mapping) { bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc.HasDefaultSupport; if (hasDefault && IsDefaultValue(mapping, o, defaultValue, nullable)) return; if (isSoap) { if (nullable) { WriteNullableQualifiedNameEncoded(name, ns, o, new XmlQualifiedName(mapping.TypeName, mapping.Namespace)); } else { WriteElementQualifiedName(name, ns, o, new XmlQualifiedName(mapping.TypeName, mapping.Namespace)); } } else { if (nullable) { WriteNullableQualifiedNameLiteral(name, ns, o); } else { WriteElementQualifiedName(name, ns, o); } } } private void WriteStructMethod(StructMapping mapping, string n, string ns, object o, bool isNullable, bool needType) { if (mapping.IsSoap && mapping.TypeDesc.IsRoot) return; if (!mapping.IsSoap) { if (o == null) { if (isNullable) WriteNullTagLiteral(n, ns); return; } if (!needType && o.GetType() != mapping.TypeDesc.Type) { if (WriteDerivedTypes(mapping, n, ns, o, isNullable)) { return; } if (mapping.TypeDesc.IsRoot) { if (WriteEnumAndArrayTypes(mapping, o, n, ns)) { return; } WriteTypedPrimitive(n, ns, o, true); return; } throw CreateUnknownTypeException(o); } } if (!mapping.TypeDesc.IsAbstract) { if (mapping.TypeDesc.Type != null && typeof(XmlSchemaObject).IsAssignableFrom(mapping.TypeDesc.Type)) { EscapeName = false; } XmlSerializerNamespaces xmlnsSource = null; MemberMapping[] members = TypeScope.GetAllMembers(mapping); int xmlnsMember = FindXmlnsIndex(members); if (xmlnsMember >= 0) { MemberMapping member = members[xmlnsMember]; xmlnsSource = (XmlSerializerNamespaces)GetMemberValue(o, member.Name); } if (!mapping.IsSoap) { WriteStartElement(n, ns, o, false, xmlnsSource); if (!mapping.TypeDesc.IsRoot) { if (needType) { WriteXsiType(mapping.TypeName, mapping.Namespace); } } } else if (xmlnsSource != null) { WriteNamespaceDeclarations(xmlnsSource); } for (int i = 0; i < members.Length; i++) { MemberMapping m = members[i]; bool isSpecified = true; bool shouldPersist = true; if (m.CheckSpecified != SpecifiedAccessor.None) { string specifiedMemberName = m.Name + "Specified"; isSpecified = (bool)GetMemberValue(o, specifiedMemberName); } if (m.CheckShouldPersist) { string methodInvoke = "ShouldSerialize" + m.Name; MethodInfo method = o.GetType().GetTypeInfo().GetDeclaredMethod(methodInvoke); shouldPersist = (bool)method.Invoke(o, Array.Empty<object>()); } if (m.Attribute != null) { if (isSpecified && shouldPersist) { object memberValue = GetMemberValue(o, m.Name); WriteMember(memberValue, m.Attribute, m.TypeDesc, o); } } } for (int i = 0; i < members.Length; i++) { MemberMapping m = members[i]; if (m.Xmlns != null) continue; bool isSpecified = true; bool shouldPersist = true; if (m.CheckSpecified != SpecifiedAccessor.None) { string specifiedMemberName = m.Name + "Specified"; isSpecified = (bool)GetMemberValue(o, specifiedMemberName); } if (m.CheckShouldPersist) { string methodInvoke = "ShouldSerialize" + m.Name; MethodInfo method = o.GetType().GetTypeInfo().GetDeclaredMethod(methodInvoke); shouldPersist = (bool)method.Invoke(o, Array.Empty<object>()); } bool checkShouldPersist = m.CheckShouldPersist && (m.Elements.Length > 0 || m.Text != null); if (!checkShouldPersist) { shouldPersist = true; } if (isSpecified && shouldPersist) { object choiceSource = null; if (m.ChoiceIdentifier != null) { choiceSource = GetMemberValue(o, m.ChoiceIdentifier.MemberName); } object memberValue = GetMemberValue(o, m.Name); WriteMember(memberValue, choiceSource, m.ElementsSortedByDerivation, m.Text, m.ChoiceIdentifier, m.TypeDesc, true); } } if (!mapping.IsSoap) { WriteEndElement(o); } } } private object GetMemberValue(object o, string memberName) { MemberInfo memberInfo = ReflectionXmlSerializationHelper.GetMember(o.GetType(), memberName); object memberValue = GetMemberValue(o, memberInfo); return memberValue; } private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, string n, string ns) { if (o is Enum) { Writer.WriteStartElement(n, ns); EnumMapping enumMapping = null; Type enumType = o.GetType(); foreach (var m in _mapping.Scope.TypeMappings) { if (m is EnumMapping em && em.TypeDesc.Type == enumType) { enumMapping = em; break; } } if (enumMapping == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalError)); WriteXsiType(enumMapping.TypeName, ns); Writer.WriteString(WriteEnumMethod(enumMapping, o)); Writer.WriteEndElement(); return true; } if (o is Array) { Writer.WriteStartElement(n, ns); ArrayMapping arrayMapping = null; Type arrayType = o.GetType(); foreach (var m in _mapping.Scope.TypeMappings) { if (m is ArrayMapping am && am.TypeDesc.Type == arrayType) { arrayMapping = am; break; } } if (arrayMapping == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalError)); WriteXsiType(arrayMapping.TypeName, ns); WriteMember(o, null, arrayMapping.ElementsSortedByDerivation, null, null, arrayMapping.TypeDesc, true); Writer.WriteEndElement(); return true; } return false; } private string WriteEnumMethod(EnumMapping mapping, object v) { string returnString = null; if (mapping != null) { ConstantMapping[] constants = mapping.Constants; if (constants.Length > 0) { bool foundValue = false; var enumValue = Convert.ToInt64(v); for (int i = 0; i < constants.Length; i++) { ConstantMapping c = constants[i]; if (enumValue == c.Value) { returnString = c.XmlName; foundValue = true; break; } } if (!foundValue) { if (mapping.IsFlags) { string[] xmlNames = new string[constants.Length]; long[] valueIds = new long[constants.Length]; for (int i = 0; i < constants.Length; i++) { xmlNames[i] = constants[i].XmlName; valueIds[i] = constants[i].Value; } returnString = FromEnum(enumValue, xmlNames, valueIds); } else { throw CreateInvalidEnumValueException(v, mapping.TypeDesc.FullName); } } } } else { returnString = v.ToString(); } if (mapping.IsSoap) { WriteXsiType(mapping.TypeName, mapping.Namespace); Writer.WriteString(returnString); return null; } else { return returnString; } } private object GetMemberValue(object o, MemberInfo memberInfo) { if (memberInfo is PropertyInfo memberProperty) { return memberProperty.GetValue(o); } else if (memberInfo is FieldInfo memberField) { return memberField.GetValue(o); } throw new InvalidOperationException(SR.Format(SR.XmlInternalError)); } private void WriteMember(object memberValue, AttributeAccessor attribute, TypeDesc memberTypeDesc, object container) { if (memberTypeDesc.IsAbstract) return; if (memberTypeDesc.IsArrayLike) { var sb = new StringBuilder(); TypeDesc arrayElementTypeDesc = memberTypeDesc.ArrayElementTypeDesc; bool canOptimizeWriteListSequence = CanOptimizeWriteListSequence(arrayElementTypeDesc); if (attribute.IsList) { if (canOptimizeWriteListSequence) { Writer.WriteStartAttribute(null, attribute.Name, attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty); } } if (memberValue != null) { var a = (IEnumerable)memberValue; IEnumerator e = a.GetEnumerator(); bool shouldAppendWhitespace = false; if (e != null) { while (e.MoveNext()) { object ai = e.Current; if (attribute.IsList) { string stringValue; if (attribute.Mapping is EnumMapping enumMapping) { stringValue = WriteEnumMethod(enumMapping, ai); } else { if (!WritePrimitiveValue(arrayElementTypeDesc, ai, true, out stringValue)) { // #10593: Add More Tests for Serialization Code Debug.Assert(ai is byte[]); } } // check to see if we can write values of the attribute sequentially if (canOptimizeWriteListSequence) { if (shouldAppendWhitespace) { Writer.WriteString(" "); } if (ai is byte[]) { WriteValue((byte[])ai); } else { WriteValue(stringValue); } } else { if (shouldAppendWhitespace) { sb.Append(" "); } sb.Append(stringValue); } } else { WriteAttribute(ai, attribute, container); } shouldAppendWhitespace = true; } if (attribute.IsList) { // check to see if we can write values of the attribute sequentially if (canOptimizeWriteListSequence) { Writer.WriteEndAttribute(); } else { if (sb.Length != 0) { string ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; WriteAttribute(attribute.Name, ns, sb.ToString()); } } } } } } else { WriteAttribute(memberValue, attribute, container); } } private bool CanOptimizeWriteListSequence(TypeDesc listElementTypeDesc) { // check to see if we can write values of the attribute sequentially // currently we have only one data type (XmlQualifiedName) that we can not write "inline", // because we need to output xmlns:qx="..." for each of the qnames return (listElementTypeDesc != null && listElementTypeDesc != QnameTypeDesc); } private void WriteAttribute(object memberValue, AttributeAccessor attribute, object container) { // TODO: this block is never hit by our tests. if (attribute.Mapping is SpecialMapping special) { if (special.TypeDesc.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue) { WriteXmlAttribute((XmlNode)memberValue, container); } else { throw new InvalidOperationException(SR.XmlInternalError); } } else { string ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; WritePrimitive(WritePrimitiveMethodRequirement.WriteAttribute, attribute.Name, ns, attribute.Default, memberValue, attribute.Mapping, false, false, false); } } private int FindXmlnsIndex(MemberMapping[] members) { for (int i = 0; i < members.Length; i++) { if (members[i].Xmlns == null) continue; return i; } return -1; } private bool WriteDerivedTypes(StructMapping mapping, string n, string ns, object o, bool isNullable) { Type t = o.GetType(); for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { if (t == derived.TypeDesc.Type) { WriteStructMethod(derived, n, ns, o, isNullable, needType: true); return true; } if (WriteDerivedTypes(derived, n, ns, o, isNullable)) { return true; } } return false; } private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, string ns, object defaultValue, object o, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable) { TypeDesc typeDesc = mapping.TypeDesc; bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc.HasDefaultSupport; if (hasDefault) { if (mapping is EnumMapping) { if (((EnumMapping)mapping).IsFlags) { IEnumerable<string> defaultEnumFlagValues = defaultValue.ToString().Split((char[])null, StringSplitOptions.RemoveEmptyEntries); string defaultEnumFlagString = string.Join(", ", defaultEnumFlagValues); if (o.ToString() == defaultEnumFlagString) return; } else { if (o.ToString() == defaultValue.ToString()) return; } } else { if (IsDefaultValue(mapping, o, defaultValue, isNullable)) { return; } } } XmlQualifiedName xmlQualifiedName = null; if (writeXsiType) { xmlQualifiedName = new XmlQualifiedName(mapping.TypeName, mapping.Namespace); } string stringValue = null; bool hasValidStringValue = false; if (mapping is EnumMapping enumMapping) { stringValue = WriteEnumMethod(enumMapping, o); hasValidStringValue = true; } else { hasValidStringValue = WritePrimitiveValue(typeDesc, o, isElement, out stringValue); } if (hasValidStringValue) { if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteElementString)) { if (hasRequirement(method, WritePrimitiveMethodRequirement.Raw)) { WriteElementString(name, ns, stringValue, xmlQualifiedName); } else { WriteElementStringRaw(name, ns, stringValue, xmlQualifiedName); } } else if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteNullableStringLiteral)) { if (hasRequirement(method, WritePrimitiveMethodRequirement.Encoded)) { if (hasRequirement(method, WritePrimitiveMethodRequirement.Raw)) { WriteNullableStringEncoded(name, ns, stringValue, xmlQualifiedName); } else { WriteNullableStringEncodedRaw(name, ns, stringValue, xmlQualifiedName); } } else { if (hasRequirement(method, WritePrimitiveMethodRequirement.Raw)) { WriteNullableStringLiteral(name, ns, stringValue); } else { WriteNullableStringLiteralRaw(name, ns, stringValue); } } } else if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteAttribute)) { WriteAttribute(name, ns, stringValue); } else { // #10593: Add More Tests for Serialization Code Debug.Assert(false); } } else if (o is byte[] a) { if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteElementString | WritePrimitiveMethodRequirement.Raw)) { WriteElementStringRaw(name, ns, FromByteArrayBase64(a)); } else if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteNullableStringLiteral | WritePrimitiveMethodRequirement.Raw)) { WriteNullableStringLiteralRaw(name, ns, FromByteArrayBase64(a)); } else if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteAttribute)) { WriteAttribute(name, ns, a); } else { // #10593: Add More Tests for Serialization Code Debug.Assert(false); } } else { // #10593: Add More Tests for Serialization Code Debug.Assert(false); } } private bool hasRequirement(WritePrimitiveMethodRequirement value, WritePrimitiveMethodRequirement requirement) { return (value & requirement) == requirement; } private bool IsDefaultValue(TypeMapping mapping, object o, object value, bool isNullable) { if (value is string && ((string)value).Length == 0) { string str = (string)o; return str == null || str.Length == 0; } else { return value.Equals(o); } } private bool WritePrimitiveValue(TypeDesc typeDesc, object o, bool isElement, out string stringValue) { if (typeDesc == StringTypeDesc || typeDesc.FormatterName == "String") { stringValue = (string)o; return true; } else { if (!typeDesc.HasCustomFormatter) { stringValue = CovertPrimitiveToString(o, typeDesc); return true; } else if (o is byte[] && typeDesc.FormatterName == "ByteArrayHex") { stringValue = FromByteArrayHex((byte[])o); return true; } else if (o is DateTime) { if (typeDesc.FormatterName == "DateTime") { stringValue = FromDateTime((DateTime)o); return true; } else if (typeDesc.FormatterName == "Date") { stringValue = FromDate((DateTime)o); return true; } else if (typeDesc.FormatterName == "Time") { stringValue = FromTime((DateTime)o); return true; } else { throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Invalid DateTime")); } } else if (typeDesc == QnameTypeDesc) { stringValue = FromXmlQualifiedName((XmlQualifiedName)o); return true; } else if (o is string) { switch (typeDesc.FormatterName) { case "XmlName": stringValue = FromXmlName((string)o); break; case "XmlNCName": stringValue = FromXmlNCName((string)o); break; case "XmlNmToken": stringValue = FromXmlNmToken((string)o); break; case "XmlNmTokens": stringValue = FromXmlNmTokens((string)o); break; default: stringValue = null; return false; } return true; } else if (o is char && typeDesc.FormatterName == "Char") { stringValue = FromChar((char)o); return true; } else if (o is byte[]) { // we deal with byte[] specially in WritePrimitive() } else { throw new InvalidOperationException(SR.Format(SR.XmlInternalError)); } } stringValue = null; return false; } private string CovertPrimitiveToString(object o, TypeDesc typeDesc) { string stringValue; switch (typeDesc.FormatterName) { case "Boolean": stringValue = XmlConvert.ToString((bool)o); break; case "Int32": stringValue = XmlConvert.ToString((int)o); break; case "Int16": stringValue = XmlConvert.ToString((short)o); break; case "Int64": stringValue = XmlConvert.ToString((long)o); break; case "Single": stringValue = XmlConvert.ToString((float)o); break; case "Double": stringValue = XmlConvert.ToString((double)o); break; case "Decimal": stringValue = XmlConvert.ToString((decimal)o); break; case "Byte": stringValue = XmlConvert.ToString((byte)o); break; case "SByte": stringValue = XmlConvert.ToString((sbyte)o); break; case "UInt16": stringValue = XmlConvert.ToString((ushort)o); break; case "UInt32": stringValue = XmlConvert.ToString((uint)o); break; case "UInt64": stringValue = XmlConvert.ToString((ulong)o); break; // Types without direct mapping (ambiguous) case "Guid": stringValue = XmlConvert.ToString((Guid)o); break; case "Char": stringValue = XmlConvert.ToString((char)o); break; case "TimeSpan": stringValue = XmlConvert.ToString((TimeSpan)o); break; default: stringValue = o.ToString(); break; } return stringValue; } private void GenerateMembersElement(object o, XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; MembersMapping mapping = (MembersMapping)element.Mapping; bool hasWrapperElement = mapping.HasWrapperElement; bool writeAccessors = mapping.WriteAccessors; bool isRpc = xmlMembersMapping.IsSoap && writeAccessors; WriteStartDocument(); if (!mapping.IsSoap) { TopLevelElement(); } object[] p = (object[])o; int pLength = p.Length; if (hasWrapperElement) { WriteStartElement(element.Name, (element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty), mapping.IsSoap); int xmlnsMember = FindXmlnsIndex(mapping.Members); if (xmlnsMember >= 0) { MemberMapping member = mapping.Members[xmlnsMember]; var source = (XmlSerializerNamespaces)p[xmlnsMember]; if (pLength > xmlnsMember) { WriteNamespaceDeclarations(source); } } for (int i = 0; i < mapping.Members.Length; i++) { MemberMapping member = mapping.Members[i]; if (member.Attribute != null && !member.Ignore) { object source = p[i]; bool? specifiedSource = null; if (member.CheckSpecified != SpecifiedAccessor.None) { string memberNameSpecified = member.Name + "Specified"; for (int j = 0; j < Math.Min(pLength, mapping.Members.Length); j++) { if (mapping.Members[j].Name == memberNameSpecified) { specifiedSource = (bool) p[j]; break; } } } if (pLength > i && (specifiedSource == null || specifiedSource.Value)) { WriteMember(source, member.Attribute, member.TypeDesc, null); } } } } for (int i = 0; i < mapping.Members.Length; i++) { MemberMapping member = mapping.Members[i]; if (member.Xmlns != null) continue; if (member.Ignore) continue; bool? specifiedSource = null; if (member.CheckSpecified != SpecifiedAccessor.None) { string memberNameSpecified = member.Name + "Specified"; for (int j = 0; j < Math.Min(pLength, mapping.Members.Length); j++) { if (mapping.Members[j].Name == memberNameSpecified) { specifiedSource = (bool)p[j]; break; } } } if (pLength > i) { if (specifiedSource == null || specifiedSource.Value) { object source = p[i]; object enumSource = null; if (member.ChoiceIdentifier != null) { for (int j = 0; j < mapping.Members.Length; j++) { if (mapping.Members[j].Name == member.ChoiceIdentifier.MemberName) { enumSource = p[j]; break; } } } if (isRpc && member.IsReturnValue && member.Elements.Length > 0) { WriteRpcResult(member.Elements[0].Name, string.Empty); } // override writeAccessors choice when we've written a wrapper element WriteMember(source, enumSource, member.ElementsSortedByDerivation, member.Text, member.ChoiceIdentifier, member.TypeDesc, writeAccessors || hasWrapperElement); } } } if (hasWrapperElement) { WriteEndElement(); } if (element.IsSoap) { if (!hasWrapperElement && !writeAccessors) { // doc/bare case -- allow extra members if (pLength > mapping.Members.Length) { for (int i = mapping.Members.Length; i < pLength; i++) { if (p[i] != null) { WritePotentiallyReferencingElement(null, null, p[i], p[i].GetType(), true, false); } } } } WriteReferencedElements(); } } [Flags] private enum WritePrimitiveMethodRequirement { None = 0, Raw = 1, WriteAttribute = 2, WriteElementString = 4, WriteNullableStringLiteral = 8, Encoded = 16 } } internal class ReflectionXmlSerializationHelper { public static MemberInfo GetMember(Type declaringType, string memberName) { MemberInfo[] memberInfos = declaringType.GetMember(memberName); if (memberInfos == null || memberInfos.Length == 0) { throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, $"Could not find member named {memberName} of type {declaringType.ToString()}")); } MemberInfo memberInfo = memberInfos[0]; if (memberInfos.Length != 1) { foreach (MemberInfo mi in memberInfos) { if (declaringType == mi.DeclaringType) { memberInfo = mi; break; } } } return memberInfo; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. /// AsyncOperation.cs - A base class for asyncronous, cancellable operations /// /// This base class is designed to be used by lengthy operations that wish to /// support cancellation. The class is based heavily the Ian Griffiths article /// "Give Your .NET-based Application a Fast and Responsive UI with Multiple /// Threads" on pg. 68 of the Feb 2003 MSDN Magazine: /// http://msdn.microsoft.com/msdnmag/issues/03/02/Multithreading/default.aspx /// /// To create a new class that supports cancellable, asychronous operations: /// /// (1) Derive a new class from AsyncOperation. /// /// (2) Implement a constructor that forwards an ISynchronizeInvoke instance /// on the base class and accepts whatever custom initialization parameters /// are requried for the class. /// /// (2) Override the DoWork() method to perform the actual background work. /// /// (3) Within the DoWork implementation, periodically check the CancelRequested /// property to see whether the caller wants to cancel. If this is the case /// call the AcknowledgeCancel method to confirm that the cancel request /// has been received and acted upon. /// /// (4) If you want to fire custom events, use the protected FireEventSafely method /// to safely propagate them to the calling thread. Calls to FireEventSafely must /// be wrapped in a lock(this) block to preserve the thread-safety contract /// of AsyncOperation. /// /// To use an AsyncOperation subclass: /// /// (1) Create a new instance of the subclass, passing in an ISynchronizeInvoke /// instance into the constructor. Normally this will be a control that /// lives on the main UI thread, thus guaranteeing that all events fired /// by the background operation will be propagated safely to the UI thread. /// /// (2) Hookup to events as desired. The AsyncOperation base class supports /// Completed, Cancelled, and Failed events. /// /// (3) Call the Start method. The operation will run until either firing the /// Completed, Cancelled, or Failed event. /// /// (4) You can check the IsDone property periodically to see if the operation /// is still in progress. If you want to block waiting for the completion of /// the background task you can call the WaitUntilDone method. /// /// (5) If you want the user to be able to cancel a running event, you can /// call either the Cancel or CancelAndWait method. Cancel returns /// immediately and CancelAndWait returns only after processing terminates. /// In either case the Completed, Cancelled, or Failed event may be /// fired (since the background thread may or may not receive the cancel /// request prior to completing its task or encountering an error). The /// CancelAndWait method will return true if the operation is either /// successfully cancelled or fails, and false if it ends up running to /// completion in spite of the cancel request. /// using System; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Threading; using System.Windows.Forms; using OpenLiveWriter.CoreServices.Diagnostics; using OpenLiveWriter.CoreServices.Threading; namespace OpenLiveWriter.CoreServices { /// <summary> /// </summary> public abstract class AsyncOperation : IProgressProvider { /// <summary> /// Initializes an AsyncOperation with an association to the /// supplied ISynchronizeInvoke. All events raised from this /// object will be delivered via this target. (This might be a /// Control object, so events would be delivered to that Control's /// UI thread.) /// </summary> /// <param name="target">An object implementing the /// ISynchronizeInvoke interface. All events will be delivered /// through this target, ensuring that they are delivered to the /// correct thread.</param> public AsyncOperation(ISynchronizeInvoke target) { isiTarget = target; isRunning = false; } /// <summary> /// Launch the operation on a worker thread. This method will /// return immediately, and the operation will start asynchronously /// on a worker thread. /// </summary> public void Start() { lock (this) { if (isRunning) { throw new AsyncOperationAlreadyRunningException(); } // Set this flag here, not inside InternalStart, to avoid // race condition when Start called twice in quick // succession. isRunning = true; } ThreadHelper.NewThread(new ThreadStart(InternalStart), GetType().Name, true, false, true).Start(); } /// <summary> /// Attempt to cancel the current operation. This returns /// immediately to the caller. No guarantee is made as to /// whether the operation will be successfully cancelled. All /// that can be known is that at some point, one of the /// three events Completed, Cancelled, or Failed will be raised /// at some point. /// </summary> public void Cancel() { lock (this) { cancelledFlag = true; } } /// <summary> /// Attempt to cancel the current operation and block until either /// the cancellation succeeds or the operation completes. /// </summary> /// <returns>true if the operation was successfully cancelled /// or it failed, false if it ran to completion.</returns> public bool CancelAndWait() { lock (this) { // Set the cancelled flag cancelledFlag = true; // Now sit and wait either for the operation to // complete or the cancellation to be acknowledged. // (Wake up and check every second - shouldn't be // necessary, but it guarantees we won't deadlock // if for some reason the Pulse gets lost - means // we don't have to worry so much about bizarre // race conditions.) while (!IsDone) { Monitor.Wait(this, 1000); } } return !HasCompleted; } /// <summary> /// Blocks until the operation has either run to completion, or has /// been successfully cancelled, or has failed with an internal /// exception. /// </summary> /// <returns>true if the operation completed, false if it was /// cancelled before completion or failed with an internal /// exception.</returns> public bool WaitUntilDone() { lock (this) { // Wait for either completion or cancellation. As with // CancelAndWait, we don't sleep forever - to reduce the // chances of deadlock in obscure race conditions, we wake // up every second to check we didn't miss a Pulse. while (!IsDone) { Monitor.Wait(this, 1000); } } return HasCompleted; } /// <summary> /// Returns false if the operation is still in progress, or true if /// it has either completed successfully, been cancelled /// successfully, or failed with an internal exception. /// </summary> public bool IsDone { get { lock (this) { return completeFlag || cancelAcknowledgedFlag || failedFlag; } } } /// <summary> /// This event will be fired if the operation runs to completion /// without being cancelled. This event will be raised through the /// ISynchronizeTarget supplied at construction time. Note that /// this event may still be received after a cancellation request /// has been issued. (This would happen if the operation completed /// at about the same time that cancellation was requested.) But /// the event is not raised if the operation is cancelled /// successfully. /// </summary> public event EventHandler Completed; /// <summary> /// This event will be fired when the operation is successfully /// stoped through cancellation. This event will be raised through /// the ISynchronizeTarget supplied at construction time. /// </summary> public event EventHandler Cancelled; /// <summary> /// This event will be fired if the operation throws an exception. /// This event will be raised through the ISynchronizeTarget /// supplied at construction time. /// </summary> public event ThreadExceptionEventHandler Failed; /// <summary> /// This event will fire whenever the progress of the operation /// is updated. This event will be raised through the ISynchronizeTarget /// supplied at construction time. /// </summary> public event ProgressUpdatedEventHandler ProgressUpdated; /// <summary> /// The ISynchronizeTarget supplied during construction - this can /// be used by deriving classes which wish to add their own events. /// </summary> protected ISynchronizeInvoke Target { get { return isiTarget; } } private ISynchronizeInvoke isiTarget; /// <summary> /// To be overridden by the deriving class - this is where the work /// will be done. The base class calls this method on a worker /// thread when the Start method is called. /// </summary> protected abstract void DoWork(); /// <summary> /// Flag indicating whether the request has been cancelled. Long- /// running operations should check this flag regularly if they can /// and cancel their operations as soon as they notice that it has /// been set. /// </summary> protected bool CancelRequested { get { lock (this) { return cancelledFlag; } } } private bool cancelledFlag; /// <summary> /// Flag indicating whether the request has run through to /// completion. This will be false if the request has been /// successfully cancelled, or if it failed. /// </summary> protected bool HasCompleted { get { lock (this) { return completeFlag; } } } private bool completeFlag; public Exception Exception { get { return exception; } } private Exception exception; /// <summary> /// Called by subclasses to fire the UpdateProgress event /// </summary> /// <param name="complete">actions completed</param> /// <param name="total">total actions</param> protected virtual void UpdateProgress(int complete, int total, string message) { //Debug.Assert(complete >= total); if (complete > total) { //Fix bug 3723, never trigger an exception dialog to the user, even if we're doing something wrong. Debug.Fail("Progress calculation error occurred: completed exceeded total"); //fall back to valid values complete = total; } lock (this) { FireEventSafely(ProgressUpdated, this, new ProgressUpdatedEventArgs(complete, total, message)); } } /// <summary> /// This is called by the operation when it wants to indicate that /// it saw the cancellation request and honoured it. /// </summary> protected void AcknowledgeCancel() { lock (this) { cancelAcknowledgedFlag = true; isRunning = false; // Pulse the event in case the main thread is blocked // waiting for us to finish (e.g. in CancelAndWait or // WaitUntilDone). Monitor.Pulse(this); // Using async invocation to avoid a potential deadlock // - using Invoke would involve a cross-thread call // whilst we still held the object lock. If the event // handler on the UI thread tries to access this object // it will block because we have the lock, but using // async invocation here means that once we've fired // the event, we'll run on and release the object lock, // unblocking the UI thread. FireEventSafely(Cancelled, this, EventArgs.Empty); } } private bool cancelAcknowledgedFlag; // Set to true if the operation fails with an exception. private bool failedFlag; // Set to true if the operation is running private bool isRunning; // This method is called on a worker thread (via asynchronous // delegate invocation). This is where we call the operation (as // defined in the deriving class's DoWork method). private void InternalStart() { // Reset our state - we might be run more than once. cancelledFlag = false; completeFlag = false; cancelAcknowledgedFlag = false; failedFlag = false; // isRunning is set during Start to avoid a race condition try { DoWork(); } catch (Exception e) { // Raise the Failed event. We're in a catch handler, so we // had better try not to throw another exception. try { FailOperation(e); } catch { } } try { lock (this) { // If the operation wasn't cancelled (or if the UI thread // tried to cancel it, but the method ran to completion // anyway before noticing the cancellation) and it // didn't fail with an exception, then we complete the // operation - if the UI thread was blocked waiting for // cancellation to complete it will be unblocked, and // the Completion event will be raised. if (!cancelAcknowledgedFlag && !failedFlag) { CompleteOperation(); } } } catch (Exception e) { UnexpectedErrorMessage.Show(e); } } // This is called when the operation runs to completion. // (This is private because it is called automatically // by this base class when the deriving class's DoWork // method exits without having cancelled) private void CompleteOperation() { lock (this) { completeFlag = true; isRunning = false; Monitor.Pulse(this); // See comments in AcknowledgeCancel re use of // Async. FireEventSafely(Completed, this, EventArgs.Empty); } } private void FailOperation(Exception e) { lock (this) { failedFlag = true; isRunning = false; exception = e; Monitor.Pulse(this); FireEventSafely(Failed, this, new ThreadExceptionEventArgs(e)); } } // Utility function for firing an event through the target. // It uses C#'s variable length parameter list support // to build the parameter list. // This functions presumes that the caller holds the object lock. // (This is because the event list is typically modified on the UI // thread, but events are usually raised on the worker thread.) protected void FireEventSafely(Delegate dlg, params object[] pList) { if (dlg != null) { try { // Use the target thread if a target is available // otherwise, fire the event on this thread if (Target != null) Target.BeginInvoke(dlg, pList); else dlg.DynamicInvoke(pList); } catch (InvalidOperationException e) { string targetType = Target != null ? Target.GetType().AssemblyQualifiedName : "(unknown)"; Trace.Fail(String.Format(CultureInfo.InvariantCulture, "Failed to fire event from '{0}' to target '{1}' because it was disposed already: {2}", GetType().Name, // {0} targetType, // {1} e // {2} )); } } } } /// <summary> /// Exception thrown by AsyncUtils.AsyncOperation.Start when an /// operation is already in progress. /// </summary> public class AsyncOperationAlreadyRunningException : ApplicationException { public AsyncOperationAlreadyRunningException() : base("Asynchronous operation already running") { } } /// <summary> /// Delegeate for handling Progress notification /// </summary> public delegate void ProgressUpdatedEventHandler(object sender, ProgressUpdatedEventArgs progressUpdatedHandler); /// <summary> /// Arguments provided when progress events occur /// </summary> [Serializable] public class ProgressUpdatedEventArgs : EventArgs { /// <summary> /// Creates a new set of Progress args /// </summary> /// <param name="completed">The total number of steps in the operation</param> /// <param name="total">The number of steps completed</param> public ProgressUpdatedEventArgs(int completed, int total, string message) { Completed = completed; Total = total; ProgressMessage = message; } /// <summary> /// The number of steps completed. -1 means ignore. /// </summary> public readonly int Completed = -1; /// <summary> /// The total number of steps in the operation. -1 means ignore. /// </summary> public readonly int Total = -1; /// <summary> /// A message describing the current progress. null means ignore. /// </summary> public readonly string ProgressMessage; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor; using Microsoft.CodeAnalysis.GenerateType; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.CodeAnalysis.Utilities; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp.GenerateType { [ExportLanguageService(typeof(IGenerateTypeService), LanguageNames.CSharp), Shared] internal class CSharpGenerateTypeService : AbstractGenerateTypeService<CSharpGenerateTypeService, SimpleNameSyntax, ObjectCreationExpressionSyntax, ExpressionSyntax, TypeDeclarationSyntax, ArgumentSyntax> { private static readonly SyntaxAnnotation s_annotation = new SyntaxAnnotation(); protected override string DefaultFileExtension => ".cs"; protected override ExpressionSyntax GetLeftSideOfDot(SimpleNameSyntax simpleName) { return simpleName.GetLeftSideOfDot(); } protected override bool IsInCatchDeclaration(ExpressionSyntax expression) { return expression.IsParentKind(SyntaxKind.CatchDeclaration); } protected override bool IsArrayElementType(ExpressionSyntax expression) { return expression.IsParentKind(SyntaxKind.ArrayType) && expression.Parent.IsParentKind(SyntaxKind.ArrayCreationExpression); } protected override bool IsInValueTypeConstraintContext( SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) { if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeArgumentList)) { var typeArgumentList = (TypeArgumentListSyntax)expression.Parent; var symbolInfo = semanticModel.GetSymbolInfo(typeArgumentList.Parent, cancellationToken); var symbol = symbolInfo.GetAnySymbol(); if (symbol.IsConstructor()) { symbol = symbol.ContainingType; } var parameterIndex = typeArgumentList.Arguments.IndexOf((TypeSyntax)expression); var type = symbol as INamedTypeSymbol; if (type != null) { type = type.OriginalDefinition; var typeParameter = parameterIndex < type.TypeParameters.Length ? type.TypeParameters[parameterIndex] : null; return typeParameter != null && typeParameter.HasValueTypeConstraint; } var method = symbol as IMethodSymbol; if (method != null) { method = method.OriginalDefinition; var typeParameter = parameterIndex < method.TypeParameters.Length ? method.TypeParameters[parameterIndex] : null; return typeParameter != null && typeParameter.HasValueTypeConstraint; } } return false; } protected override bool IsInInterfaceList(ExpressionSyntax expression) { if (expression is TypeSyntax && expression.Parent is BaseTypeSyntax && expression.Parent.IsParentKind(SyntaxKind.BaseList) && ((BaseTypeSyntax)expression.Parent).Type == expression) { var baseList = (BaseListSyntax)expression.Parent.Parent; // If it's after the first item, then it's definitely an interface. if (baseList.Types[0] != expression.Parent) { return true; } // If it's in the base list of an interface or struct, then it's definitely an // interface. return baseList.IsParentKind(SyntaxKind.InterfaceDeclaration) || baseList.IsParentKind(SyntaxKind.StructDeclaration); } if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeConstraint) && expression.Parent.IsParentKind(SyntaxKind.TypeParameterConstraintClause)) { var typeConstraint = (TypeConstraintSyntax)expression.Parent; var constraintClause = (TypeParameterConstraintClauseSyntax)typeConstraint.Parent; var index = constraintClause.Constraints.IndexOf(typeConstraint); // If it's after the first item, then it's definitely an interface. return index > 0; } return false; } protected override bool TryGetNameParts(ExpressionSyntax expression, out IList<string> nameParts) { nameParts = new List<string>(); return expression.TryGetNameParts(out nameParts); } protected override bool TryInitializeState( SemanticDocument document, SimpleNameSyntax simpleName, CancellationToken cancellationToken, out GenerateTypeServiceStateOptions generateTypeServiceStateOptions) { generateTypeServiceStateOptions = new GenerateTypeServiceStateOptions(); if (simpleName.IsVar) { return false; } if (SyntaxFacts.IsAliasQualifier(simpleName)) { return false; } // Never offer if we're in a using directive, unless its a static using. The feeling here is that it's highly // unlikely that this would be a location where a user would be wanting to generate // something. They're really just trying to reference something that exists but // isn't available for some reason (i.e. a missing reference). var usingDirectiveSyntax = simpleName.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirectiveSyntax != null && usingDirectiveSyntax.StaticKeyword.Kind() != SyntaxKind.StaticKeyword) { return false; } ExpressionSyntax nameOrMemberAccessExpression = null; if (simpleName.IsRightSideOfDot()) { // This simplename comes from the cref if (simpleName.IsParentKind(SyntaxKind.NameMemberCref)) { return false; } nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = (ExpressionSyntax)simpleName.Parent; // If we're on the right side of a dot, then the left side better be a name (and // not an arbitrary expression). var leftSideExpression = simpleName.GetLeftSideOfDot(); if (!leftSideExpression.IsKind( SyntaxKind.QualifiedName, SyntaxKind.IdentifierName, SyntaxKind.AliasQualifiedName, SyntaxKind.GenericName, SyntaxKind.SimpleMemberAccessExpression)) { return false; } } else { nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = simpleName; } // BUG(5712): Don't offer generate type in an enum's base list. if (nameOrMemberAccessExpression.Parent is BaseTypeSyntax && nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.BaseList) && ((BaseTypeSyntax)nameOrMemberAccessExpression.Parent).Type == nameOrMemberAccessExpression && nameOrMemberAccessExpression.Parent.Parent.IsParentKind(SyntaxKind.EnumDeclaration)) { return false; } // If we can guarantee it's a type only context, great. Otherwise, we may not want to // provide this here. var semanticModel = document.SemanticModel; if (!SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression)) { // Don't offer Generate Type in an expression context *unless* we're on the left // side of a dot. In that case the user might be making a type that they're // accessing a static off of. var syntaxTree = semanticModel.SyntaxTree; var start = nameOrMemberAccessExpression.SpanStart; var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(start, cancellationToken); var isExpressionContext = syntaxTree.IsExpressionContext(start, tokenOnLeftOfStart, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel); var isStatementContext = syntaxTree.IsStatementContext(start, tokenOnLeftOfStart, cancellationToken); var isExpressionOrStatementContext = isExpressionContext || isStatementContext; // Delegate Type Creation is not allowed in Non Type Namespace Context generateTypeServiceStateOptions.IsDelegateAllowed = false; if (!isExpressionOrStatementContext) { return false; } if (!simpleName.IsLeftSideOfDot() && !simpleName.IsInsideNameOf()) { if (nameOrMemberAccessExpression == null || !nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || !simpleName.IsRightSideOfDot()) { return false; } var leftSymbol = semanticModel.GetSymbolInfo(((MemberAccessExpressionSyntax)nameOrMemberAccessExpression).Expression, cancellationToken).Symbol; var token = simpleName.GetLastToken().GetNextToken(); // We let only the Namespace to be left of the Dot if (leftSymbol == null || !leftSymbol.IsKind(SymbolKind.Namespace) || !token.IsKind(SyntaxKind.DotToken)) { return false; } else { generateTypeServiceStateOptions.IsMembersWithModule = true; generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true; } } // Global Namespace if (!generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess && !SyntaxFacts.IsInNamespaceOrTypeContext(simpleName)) { var token = simpleName.GetLastToken().GetNextToken(); if (token.IsKind(SyntaxKind.DotToken) && simpleName.Parent == token.Parent) { generateTypeServiceStateOptions.IsMembersWithModule = true; generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true; } } } var fieldDeclaration = simpleName.GetAncestor<FieldDeclarationSyntax>(); if (fieldDeclaration != null && fieldDeclaration.Parent is CompilationUnitSyntax && document.Document.SourceCodeKind == SourceCodeKind.Regular) { return false; } // Check to see if Module could be an option in the Type Generation in Cross Language Generation var nextToken = simpleName.GetLastToken().GetNextToken(); if (simpleName.IsLeftSideOfDot() || nextToken.IsKind(SyntaxKind.DotToken)) { if (simpleName.IsRightSideOfDot()) { var parent = simpleName.Parent as QualifiedNameSyntax; if (parent != null) { var leftSymbol = semanticModel.GetSymbolInfo(parent.Left, cancellationToken).Symbol; if (leftSymbol != null && leftSymbol.IsKind(SymbolKind.Namespace)) { generateTypeServiceStateOptions.IsMembersWithModule = true; } } } } if (SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression)) { if (nextToken.IsKind(SyntaxKind.DotToken)) { // In Namespace or Type Context we cannot have Interface, Enum, Delegate as part of the Left Expression of a QualifiedName generateTypeServiceStateOptions.IsDelegateAllowed = false; generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true; generateTypeServiceStateOptions.IsMembersWithModule = true; } // case: class Foo<T> where T: MyType if (nameOrMemberAccessExpression.GetAncestors<TypeConstraintSyntax>().Any()) { generateTypeServiceStateOptions.IsClassInterfaceTypes = true; return true; } // Events if (nameOrMemberAccessExpression.GetAncestors<EventFieldDeclarationSyntax>().Any() || nameOrMemberAccessExpression.GetAncestors<EventDeclarationSyntax>().Any()) { // Case : event foo name11 // Only Delegate if (simpleName.Parent != null && !(simpleName.Parent is QualifiedNameSyntax)) { generateTypeServiceStateOptions.IsDelegateOnly = true; return true; } // Case : event SomeSymbol.foo name11 if (nameOrMemberAccessExpression is QualifiedNameSyntax) { // Only Namespace, Class, Struct and Module are allowed to contain Delegate // Case : event Something.Mytype.<Delegate> Identifier if (nextToken.IsKind(SyntaxKind.DotToken)) { if (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.Parent is QualifiedNameSyntax) { return true; } else { Contract.Fail("Cannot reach this point"); } } else { // Case : event Something.<Delegate> Identifier generateTypeServiceStateOptions.IsDelegateOnly = true; return true; } } } } else { // MemberAccessExpression if ((nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression))) && nameOrMemberAccessExpression.IsLeftSideOfDot()) { // Check to see if the expression is part of Invocation Expression ExpressionSyntax outerMostMemberAccessExpression = null; if (nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { outerMostMemberAccessExpression = nameOrMemberAccessExpression; } else { Debug.Assert(nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)); outerMostMemberAccessExpression = (ExpressionSyntax)nameOrMemberAccessExpression.Parent; } outerMostMemberAccessExpression = outerMostMemberAccessExpression.GetAncestorsOrThis<ExpressionSyntax>().SkipWhile((n) => n != null && n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).FirstOrDefault(); if (outerMostMemberAccessExpression != null && outerMostMemberAccessExpression is InvocationExpressionSyntax) { generateTypeServiceStateOptions.IsEnumNotAllowed = true; } } } // Cases: // // 1 - Function Address // var s2 = new MyD2(foo); // // 2 - Delegate // MyD1 d = null; // var s1 = new MyD2(d); // // 3 - Action // Action action1 = null; // var s3 = new MyD2(action1); // // 4 - Func // Func<int> lambda = () => { return 0; }; // var s4 = new MyD3(lambda); if (nameOrMemberAccessExpression.Parent is ObjectCreationExpressionSyntax) { var objectCreationExpressionOpt = generateTypeServiceStateOptions.ObjectCreationExpressionOpt = (ObjectCreationExpressionSyntax)nameOrMemberAccessExpression.Parent; // Enum and Interface not Allowed in Object Creation Expression generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true; if (objectCreationExpressionOpt.ArgumentList != null) { if (objectCreationExpressionOpt.ArgumentList.CloseParenToken.IsMissing) { return false; } // Get the Method symbol for the Delegate to be created if (generateTypeServiceStateOptions.IsDelegateAllowed && objectCreationExpressionOpt.ArgumentList.Arguments.Count == 1 && objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression.Kind() != SyntaxKind.DeclarationExpression) { generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression, cancellationToken); } else { generateTypeServiceStateOptions.IsDelegateAllowed = false; } } if (objectCreationExpressionOpt.Initializer != null) { foreach (var expression in objectCreationExpressionOpt.Initializer.Expressions) { var simpleAssignmentExpression = expression as AssignmentExpressionSyntax; if (simpleAssignmentExpression == null) { continue; } var name = simpleAssignmentExpression.Left as SimpleNameSyntax; if (name == null) { continue; } generateTypeServiceStateOptions.PropertiesToGenerate.Add(name); } } } if (generateTypeServiceStateOptions.IsDelegateAllowed) { // MyD1 z1 = foo; if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.VariableDeclaration)) { var variableDeclaration = (VariableDeclarationSyntax)nameOrMemberAccessExpression.Parent; if (variableDeclaration.Variables.Count != 0) { var firstVarDeclWithInitializer = variableDeclaration.Variables.FirstOrDefault(var => var.Initializer != null && var.Initializer.Value != null); if (firstVarDeclWithInitializer != null && firstVarDeclWithInitializer.Initializer != null && firstVarDeclWithInitializer.Initializer.Value != null) { generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, firstVarDeclWithInitializer.Initializer.Value, cancellationToken); } } } // var w1 = (MyD1)foo; if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.CastExpression)) { var castExpression = (CastExpressionSyntax)nameOrMemberAccessExpression.Parent; if (castExpression.Expression != null) { generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, castExpression.Expression, cancellationToken); } } } return true; } private IMethodSymbol GetMethodSymbolIfPresent(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) { if (expression == null) { return null; } var memberGroup = semanticModel.GetMemberGroup(expression, cancellationToken); if (memberGroup.Length != 0) { return memberGroup.ElementAt(0).IsKind(SymbolKind.Method) ? (IMethodSymbol)memberGroup.ElementAt(0) : null; } var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type; if (expressionType.IsDelegateType()) { return ((INamedTypeSymbol)expressionType).DelegateInvokeMethod; } var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol; if (expressionSymbol.IsKind(SymbolKind.Method)) { return (IMethodSymbol)expressionSymbol; } return null; } private Accessibility DetermineAccessibilityConstraint( State state, SemanticModel semanticModel, CancellationToken cancellationToken) { return semanticModel.DetermineAccessibilityConstraint( state.NameOrMemberAccessExpression as TypeSyntax, cancellationToken); } protected override ImmutableArray<ITypeParameterSymbol> GetTypeParameters( State state, SemanticModel semanticModel, CancellationToken cancellationToken) { if (state.SimpleName is GenericNameSyntax) { var genericName = (GenericNameSyntax)state.SimpleName; var typeArguments = state.SimpleName.Arity == genericName.TypeArgumentList.Arguments.Count ? genericName.TypeArgumentList.Arguments.OfType<SyntaxNode>().ToList() : Enumerable.Repeat<SyntaxNode>(null, state.SimpleName.Arity); return this.GetTypeParameters(state, semanticModel, typeArguments, cancellationToken); } return ImmutableArray<ITypeParameterSymbol>.Empty; } protected override bool TryGetArgumentList(ObjectCreationExpressionSyntax objectCreationExpression, out IList<ArgumentSyntax> argumentList) { if (objectCreationExpression != null && objectCreationExpression.ArgumentList != null) { argumentList = objectCreationExpression.ArgumentList.Arguments.ToList(); return true; } argumentList = null; return false; } protected override IList<ParameterName> GenerateParameterNames( SemanticModel semanticModel, IList<ArgumentSyntax> arguments, CancellationToken cancellationToken) { return semanticModel.GenerateParameterNames(arguments, reservedNames: null, cancellationToken: cancellationToken); } public override string GetRootNamespace(CompilationOptions options) { return string.Empty; } protected override bool IsInVariableTypeContext(ExpressionSyntax expression) { return false; } protected override INamedTypeSymbol DetermineTypeToGenerateIn(SemanticModel semanticModel, SimpleNameSyntax simpleName, CancellationToken cancellationToken) { return semanticModel.GetEnclosingNamedType(simpleName.SpanStart, cancellationToken); } protected override Accessibility GetAccessibility(State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken) { var accessibility = DetermineDefaultAccessibility(state, semanticModel, intoNamespace, cancellationToken); if (!state.IsTypeGeneratedIntoNamespaceFromMemberAccess) { var accessibilityConstraint = DetermineAccessibilityConstraint(state, semanticModel, cancellationToken); if (accessibilityConstraint == Accessibility.Public || accessibilityConstraint == Accessibility.Internal) { accessibility = accessibilityConstraint; } } return accessibility; } protected override ITypeSymbol DetermineArgumentType(SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken) { return argument.DetermineParameterType(semanticModel, cancellationToken); } protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType) { return compilation.ClassifyConversion(sourceType, targetType).IsImplicit; } public override async Task<Tuple<INamespaceSymbol, INamespaceOrTypeSymbol, Location>> GetOrGenerateEnclosingNamespaceSymbolAsync( INamedTypeSymbol namedTypeSymbol, string[] containers, Document selectedDocument, SyntaxNode selectedDocumentRoot, CancellationToken cancellationToken) { var compilationUnit = (CompilationUnitSyntax)selectedDocumentRoot; var semanticModel = await selectedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (containers.Length != 0) { // Search the NS declaration in the root var containerList = new List<string>(containers); var enclosingNamespace = GetDeclaringNamespace(containerList, 0, compilationUnit); if (enclosingNamespace != null) { var enclosingNamespaceSymbol = semanticModel.GetSymbolInfo(enclosingNamespace.Name, cancellationToken); if (enclosingNamespaceSymbol.Symbol != null) { return Tuple.Create((INamespaceSymbol)enclosingNamespaceSymbol.Symbol, (INamespaceOrTypeSymbol)namedTypeSymbol, enclosingNamespace.CloseBraceToken.GetLocation()); } } } var globalNamespace = semanticModel.GetEnclosingNamespace(0, cancellationToken); var rootNamespaceOrType = namedTypeSymbol.GenerateRootNamespaceOrType(containers); var lastMember = compilationUnit.Members.LastOrDefault(); Location afterThisLocation = null; if (lastMember != null) { afterThisLocation = semanticModel.SyntaxTree.GetLocation(new TextSpan(lastMember.Span.End, 0)); } else { afterThisLocation = semanticModel.SyntaxTree.GetLocation(new TextSpan()); } return Tuple.Create(globalNamespace, rootNamespaceOrType, afterThisLocation); } private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, CompilationUnitSyntax compilationUnit) { foreach (var member in compilationUnit.Members) { var namespaceDeclaration = GetDeclaringNamespace(containers, 0, member); if (namespaceDeclaration != null) { return namespaceDeclaration; } } return null; } private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, SyntaxNode localRoot) { var namespaceDecl = localRoot as NamespaceDeclarationSyntax; if (namespaceDecl == null || namespaceDecl.Name is AliasQualifiedNameSyntax) { return null; } List<string> namespaceContainers = new List<string>(); GetNamespaceContainers(namespaceDecl.Name, namespaceContainers); if (namespaceContainers.Count + indexDone > containers.Count || !IdentifierMatches(indexDone, namespaceContainers, containers)) { return null; } indexDone = indexDone + namespaceContainers.Count; if (indexDone == containers.Count) { return namespaceDecl; } foreach (var member in namespaceDecl.Members) { var resultant = GetDeclaringNamespace(containers, indexDone, member); if (resultant != null) { return resultant; } } return null; } private bool IdentifierMatches(int indexDone, List<string> namespaceContainers, List<string> containers) { for (int i = 0; i < namespaceContainers.Count; ++i) { if (namespaceContainers[i] != containers[indexDone + i]) { return false; } } return true; } private void GetNamespaceContainers(NameSyntax name, List<string> namespaceContainers) { if (name is QualifiedNameSyntax qualifiedName) { GetNamespaceContainers(qualifiedName.Left, namespaceContainers); namespaceContainers.Add(qualifiedName.Right.Identifier.ValueText); } else { Debug.Assert(name is SimpleNameSyntax); namespaceContainers.Add(((SimpleNameSyntax)name).Identifier.ValueText); } } internal override bool TryGetBaseList(ExpressionSyntax expression, out TypeKindOptions typeKindValue) { typeKindValue = TypeKindOptions.AllOptions; if (expression == null) { return false; } var node = expression as SyntaxNode; while (node != null) { if (node is BaseListSyntax) { if (node.Parent != null && (node.Parent is InterfaceDeclarationSyntax || node.Parent is StructDeclarationSyntax)) { typeKindValue = TypeKindOptions.Interface; return true; } typeKindValue = TypeKindOptions.BaseList; return true; } node = node.Parent; } return false; } internal override bool IsPublicOnlyAccessibility(ExpressionSyntax expression, Project project) { if (expression == null) { return false; } if (GeneratedTypesMustBePublic(project)) { return true; } var node = expression as SyntaxNode; SyntaxNode previousNode = null; while (node != null) { // Types in BaseList, Type Constraint or Member Types cannot be of more restricted accessibility than the declaring type if ((node is BaseListSyntax || node is TypeParameterConstraintClauseSyntax) && node.Parent != null && node.Parent is TypeDeclarationSyntax) { var typeDecl = node.Parent as TypeDeclarationSyntax; if (typeDecl != null) { if (typeDecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword)) { return IsAllContainingTypeDeclsPublic(typeDecl); } else { // The Type Decl which contains the BaseList does not contain Public return false; } } Contract.Fail("Cannot reach this point"); } if ((node is EventDeclarationSyntax || node is EventFieldDeclarationSyntax) && node.Parent != null && node.Parent is TypeDeclarationSyntax) { // Make sure the GFU is not inside the Accessors if (previousNode != null && previousNode is AccessorListSyntax) { return false; } // Make sure that Event Declaration themselves are Public in the first place if (!node.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword)) { return false; } return IsAllContainingTypeDeclsPublic(node); } previousNode = node; node = node.Parent; } return false; } private bool IsAllContainingTypeDeclsPublic(SyntaxNode node) { // Make sure that all the containing Type Declarations are also Public var containingTypeDeclarations = node.GetAncestors<TypeDeclarationSyntax>(); if (containingTypeDeclarations.Count() == 0) { return true; } else { return containingTypeDeclarations.All(typedecl => typedecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword)); } } internal override bool IsGenericName(SimpleNameSyntax simpleName) { if (simpleName == null) { return false; } var genericName = simpleName as GenericNameSyntax; return genericName != null; } internal override bool IsSimpleName(ExpressionSyntax expression) { return expression is SimpleNameSyntax; } internal override async Task<Solution> TryAddUsingsOrImportToDocumentAsync(Solution updatedSolution, SyntaxNode modifiedRoot, Document document, SimpleNameSyntax simpleName, string includeUsingsOrImports, CancellationToken cancellationToken) { // Nothing to include if (string.IsNullOrWhiteSpace(includeUsingsOrImports)) { return updatedSolution; } SyntaxNode root = null; if (modifiedRoot == null) { root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); } else { root = modifiedRoot; } if (root is CompilationUnitSyntax compilationRoot) { var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(includeUsingsOrImports)); // Check if the usings is already present if (compilationRoot.Usings.Where(n => n != null && n.Alias == null) .Select(n => n.Name.ToString()) .Any(n => n.Equals(includeUsingsOrImports))) { return updatedSolution; } // Check if the GFU is triggered from the namespace same as the usings namespace if (await IsWithinTheImportingNamespaceAsync(document, simpleName.SpanStart, includeUsingsOrImports, cancellationToken).ConfigureAwait(false)) { return updatedSolution; } var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst); var addedCompilationRoot = compilationRoot.AddUsingDirectives(new[] { usingDirective }, placeSystemNamespaceFirst, Formatter.Annotation); updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, addedCompilationRoot, PreservationMode.PreserveIdentity); } return updatedSolution; } private ITypeSymbol GetPropertyType( SimpleNameSyntax propertyName, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken) { var parentAssignment = propertyName.Parent as AssignmentExpressionSyntax; if (parentAssignment != null) { return typeInference.InferType( semanticModel, parentAssignment.Left, objectAsDefault: true, cancellationToken: cancellationToken); } var isPatternExpression = propertyName.Parent as IsPatternExpressionSyntax; if (isPatternExpression != null) { return typeInference.InferType( semanticModel, isPatternExpression.Expression, objectAsDefault: true, cancellationToken: cancellationToken); } return null; } private IPropertySymbol CreatePropertySymbol( SimpleNameSyntax propertyName, ITypeSymbol propertyType) { return CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(), explicitInterfaceSymbol: null, name: propertyName.Identifier.ValueText, type: propertyType, returnsByRef: false, parameters: default(ImmutableArray<IParameterSymbol>), getMethod: s_accessor, setMethod: s_accessor, isIndexer: false); } private static readonly IMethodSymbol s_accessor = CodeGenerationSymbolFactory.CreateAccessorSymbol( attributes: default(ImmutableArray<AttributeData>), accessibility: Accessibility.Public, statements: default(ImmutableArray<SyntaxNode>)); internal override bool TryGenerateProperty( SimpleNameSyntax propertyName, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken, out IPropertySymbol property) { property = null; var propertyType = GetPropertyType(propertyName, semanticModel, typeInference, cancellationToken); if (propertyType == null || propertyType is IErrorTypeSymbol) { property = CreatePropertySymbol(propertyName, semanticModel.Compilation.ObjectType); return property != null; } property = CreatePropertySymbol(propertyName, propertyType); return property != null; } internal override IMethodSymbol GetDelegatingConstructor( SemanticDocument document, ObjectCreationExpressionSyntax objectCreation, INamedTypeSymbol namedType, ISet<IMethodSymbol> candidates, CancellationToken cancellationToken) { var model = document.SemanticModel; var oldNode = objectCreation .AncestorsAndSelf(ascendOutOfTrivia: false) .Where(node => SpeculationAnalyzer.CanSpeculateOnNode(node)) .LastOrDefault(); var typeNameToReplace = objectCreation.Type; var newTypeName = namedType.GenerateTypeSyntax(); var newObjectCreation = objectCreation.WithType(newTypeName).WithAdditionalAnnotations(s_annotation); var newNode = oldNode.ReplaceNode(objectCreation, newObjectCreation); var speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(oldNode, newNode, model); if (speculativeModel != null) { newObjectCreation = (ObjectCreationExpressionSyntax)newNode.GetAnnotatedNodes(s_annotation).Single(); var symbolInfo = speculativeModel.GetSymbolInfo(newObjectCreation, cancellationToken); var parameterTypes = newObjectCreation.ArgumentList.Arguments.Select( a => a.DetermineParameterType(speculativeModel, cancellationToken)).ToList(); return GenerateConstructorHelpers.GetDelegatingConstructor( document, symbolInfo, candidates, namedType, parameterTypes); } return null; } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.Runtime.Serialization.Json { using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using System.Runtime; using System.Runtime.Serialization.Diagnostics.Application; using System.Security; using System.Security.Permissions; using System.Xml; delegate object JsonFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[] memberNames); delegate object JsonFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract); delegate void JsonFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract); sealed class JsonFormatReaderGenerator { [Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that was produced within an assert.")] [SecurityCritical] CriticalHelper helper; [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.")] [SecurityCritical] public JsonFormatReaderGenerator() { helper = new CriticalHelper(); } [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical helper class 'CriticalHelper'.")] [SecurityCritical] public JsonFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract) { try { if (TD.DCJsonGenReaderStartIsEnabled()) { TD.DCJsonGenReaderStart("Class", classContract.UnderlyingType.FullName); } return helper.GenerateClassReader(classContract); } finally { if (TD.DCJsonGenReaderStopIsEnabled()) { TD.DCJsonGenReaderStop(); } } } [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical helper class 'CriticalHelper'.")] [SecurityCritical] public JsonFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract) { try { if (TD.DCJsonGenReaderStartIsEnabled()) { TD.DCJsonGenReaderStart("Collection", collectionContract.StableName.Name); } return helper.GenerateCollectionReader(collectionContract); } finally { if (TD.DCJsonGenReaderStopIsEnabled()) { TD.DCJsonGenReaderStop(); } } } [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical helper class 'CriticalHelper'.")] [SecurityCritical] public JsonFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract) { try { if (TD.DCJsonGenReaderStartIsEnabled()) { TD.DCJsonGenReaderStart("GetOnlyCollection", collectionContract.UnderlyingType.FullName); } return helper.GenerateGetOnlyCollectionReader(collectionContract); } finally { if (TD.DCJsonGenReaderStopIsEnabled()) { TD.DCJsonGenReaderStop(); } } } [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - handles all aspects of IL generation including initializing the DynamicMethod." + "Changes to how IL generated could affect how data is deserialized and what gets access to data, " + "therefore we mark it for review so that changes to generation logic are reviewed.")] class CriticalHelper { CodeGenerator ilg; LocalBuilder objectLocal; Type objectType; ArgBuilder xmlReaderArg; ArgBuilder contextArg; ArgBuilder memberNamesArg; ArgBuilder collectionContractArg; ArgBuilder emptyDictionaryStringArg; public JsonFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract) { ilg = new CodeGenerator(); bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null); try { BeginMethod(ilg, "Read" + classContract.StableName.Name + "FromJson", typeof(JsonFormatClassReaderDelegate), memberAccessFlag); } catch (SecurityException securityException) { if (memberAccessFlag && securityException.PermissionType.Equals(typeof(ReflectionPermission))) { classContract.RequiresMemberAccessForRead(securityException); } else { throw; } } InitArgs(); DemandSerializationFormatterPermission(classContract); DemandMemberAccessPermission(memberAccessFlag); CreateObject(classContract); ilg.Call(contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, objectLocal); InvokeOnDeserializing(classContract); if (classContract.IsISerializable) ReadISerializable(classContract); else ReadClass(classContract); if (Globals.TypeOfIDeserializationCallback.IsAssignableFrom(classContract.UnderlyingType)) ilg.Call(objectLocal, JsonFormatGeneratorStatics.OnDeserializationMethod, null); InvokeOnDeserialized(classContract); if (!InvokeFactoryMethod(classContract)) { ilg.Load(objectLocal); // Do a conversion back from DateTimeOffsetAdapter to DateTimeOffset after deserialization. // DateTimeOffsetAdapter is used here for deserialization purposes to bypass the ISerializable implementation // on DateTimeOffset; which does not work in partial trust. if (classContract.UnderlyingType == Globals.TypeOfDateTimeOffsetAdapter) { ilg.ConvertValue(objectLocal.LocalType, Globals.TypeOfDateTimeOffsetAdapter); ilg.Call(XmlFormatGeneratorStatics.GetDateTimeOffsetMethod); ilg.ConvertValue(Globals.TypeOfDateTimeOffset, ilg.CurrentMethod.ReturnType); } else { ilg.ConvertValue(objectLocal.LocalType, ilg.CurrentMethod.ReturnType); } } return (JsonFormatClassReaderDelegate)ilg.EndMethod(); } public JsonFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract) { ilg = GenerateCollectionReaderHelper(collectionContract, false /*isGetOnlyCollection*/); ReadCollection(collectionContract); ilg.Load(objectLocal); ilg.ConvertValue(objectLocal.LocalType, ilg.CurrentMethod.ReturnType); return (JsonFormatCollectionReaderDelegate)ilg.EndMethod(); } public JsonFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract) { ilg = GenerateCollectionReaderHelper(collectionContract, true /*isGetOnlyCollection*/); ReadGetOnlyCollection(collectionContract); return (JsonFormatGetOnlyCollectionReaderDelegate)ilg.EndMethod(); } CodeGenerator GenerateCollectionReaderHelper(CollectionDataContract collectionContract, bool isGetOnlyCollection) { ilg = new CodeGenerator(); bool memberAccessFlag = collectionContract.RequiresMemberAccessForRead(null); try { if (isGetOnlyCollection) { BeginMethod(ilg, "Read" + collectionContract.StableName.Name + "FromJson" + "IsGetOnly", typeof(JsonFormatGetOnlyCollectionReaderDelegate), memberAccessFlag); } else { BeginMethod(ilg, "Read" + collectionContract.StableName.Name + "FromJson", typeof(JsonFormatCollectionReaderDelegate), memberAccessFlag); } } catch (SecurityException securityException) { if (memberAccessFlag && securityException.PermissionType.Equals(typeof(ReflectionPermission))) { collectionContract.RequiresMemberAccessForRead(securityException); } else { throw; } } InitArgs(); DemandMemberAccessPermission(memberAccessFlag); collectionContractArg = ilg.GetArg(4); return ilg; } void BeginMethod(CodeGenerator ilg, string methodName, Type delegateType, bool allowPrivateMemberAccess) { #if USE_REFEMIT ilg.BeginMethod(methodName, delegateType, allowPrivateMemberAccess); #else MethodInfo signature = delegateType.GetMethod("Invoke"); ParameterInfo[] parameters = signature.GetParameters(); Type[] paramTypes = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) paramTypes[i] = parameters[i].ParameterType; DynamicMethod dynamicMethod = new DynamicMethod(methodName, signature.ReturnType, paramTypes, typeof(JsonFormatReaderGenerator).Module, allowPrivateMemberAccess); ilg.BeginMethod(dynamicMethod, delegateType, methodName, paramTypes, allowPrivateMemberAccess); #endif } void InitArgs() { xmlReaderArg = ilg.GetArg(0); contextArg = ilg.GetArg(1); emptyDictionaryStringArg = ilg.GetArg(2); memberNamesArg = ilg.GetArg(3); } void DemandMemberAccessPermission(bool memberAccessFlag) { if (memberAccessFlag) { ilg.Call(contextArg, XmlFormatGeneratorStatics.DemandMemberAccessPermissionMethod); } } void DemandSerializationFormatterPermission(ClassDataContract classContract) { if (!classContract.HasDataContract && !classContract.IsNonAttributedType) { ilg.Call(contextArg, XmlFormatGeneratorStatics.DemandSerializationFormatterPermissionMethod); } } void CreateObject(ClassDataContract classContract) { Type type = objectType = classContract.UnderlyingType; if (type.IsValueType && !classContract.IsNonAttributedType) type = Globals.TypeOfValueType; objectLocal = ilg.DeclareLocal(type, "objectDeserialized"); if (classContract.UnderlyingType == Globals.TypeOfDBNull) { ilg.LoadMember(Globals.TypeOfDBNull.GetField("Value")); ilg.Stloc(objectLocal); } else if (classContract.IsNonAttributedType) { if (type.IsValueType) { ilg.Ldloca(objectLocal); ilg.InitObj(type); } else { ilg.New(classContract.GetNonAttributedTypeConstructor()); ilg.Stloc(objectLocal); } } else { ilg.Call(null, JsonFormatGeneratorStatics.GetUninitializedObjectMethod, DataContract.GetIdForInitialization(classContract)); ilg.ConvertValue(Globals.TypeOfObject, type); ilg.Stloc(objectLocal); } } void InvokeOnDeserializing(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnDeserializing(classContract.BaseContract); if (classContract.OnDeserializing != null) { ilg.LoadAddress(objectLocal); ilg.ConvertAddress(objectLocal.LocalType, objectType); ilg.Load(contextArg); ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod); ilg.Call(classContract.OnDeserializing); } } void InvokeOnDeserialized(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnDeserialized(classContract.BaseContract); if (classContract.OnDeserialized != null) { ilg.LoadAddress(objectLocal); ilg.ConvertAddress(objectLocal.LocalType, objectType); ilg.Load(contextArg); ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod); ilg.Call(classContract.OnDeserialized); } } bool HasFactoryMethod(ClassDataContract classContract) { return Globals.TypeOfIObjectReference.IsAssignableFrom(classContract.UnderlyingType); } bool InvokeFactoryMethod(ClassDataContract classContract) { if (HasFactoryMethod(classContract)) { ilg.Load(contextArg); ilg.LoadAddress(objectLocal); ilg.ConvertAddress(objectLocal.LocalType, Globals.TypeOfIObjectReference); ilg.Load(Globals.NewObjectId); ilg.Call(XmlFormatGeneratorStatics.GetRealObjectMethod); ilg.ConvertValue(Globals.TypeOfObject, ilg.CurrentMethod.ReturnType); return true; } return false; } void ReadClass(ClassDataContract classContract) { if (classContract.HasExtensionData) { LocalBuilder extensionDataLocal = ilg.DeclareLocal(Globals.TypeOfExtensionDataObject, "extensionData"); ilg.New(JsonFormatGeneratorStatics.ExtensionDataObjectCtor); ilg.Store(extensionDataLocal); ReadMembers(classContract, extensionDataLocal); ClassDataContract currentContract = classContract; while (currentContract != null) { MethodInfo extensionDataSetMethod = currentContract.ExtensionDataSetMethod; if (extensionDataSetMethod != null) ilg.Call(objectLocal, extensionDataSetMethod, extensionDataLocal); currentContract = currentContract.BaseContract; } } else ReadMembers(classContract, null /*extensionDataLocal*/); } void ReadMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal) { int memberCount = classContract.MemberNames.Length; ilg.Call(contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, memberCount); BitFlagsGenerator expectedElements = new BitFlagsGenerator(memberCount, ilg, classContract.UnderlyingType.Name + "_ExpectedElements"); byte[] requiredElements = new byte[expectedElements.GetLocalCount()]; SetRequiredElements(classContract, requiredElements); SetExpectedElements(expectedElements, 0 /*startIndex*/); LocalBuilder memberIndexLocal = ilg.DeclareLocal(Globals.TypeOfInt, "memberIndex", -1); Label throwDuplicateMemberLabel = ilg.DefineLabel(); Label throwMissingRequiredMembersLabel = ilg.DefineLabel(); object forReadElements = ilg.For(null, null, null); ilg.Call(null, XmlFormatGeneratorStatics.MoveToNextElementMethod, xmlReaderArg); ilg.IfFalseBreak(forReadElements); ilg.Call(contextArg, JsonFormatGeneratorStatics.GetJsonMemberIndexMethod, xmlReaderArg, memberNamesArg, memberIndexLocal, extensionDataLocal); if (memberCount > 0) { Label[] memberLabels = ilg.Switch(memberCount); ReadMembers(classContract, expectedElements, memberLabels, throwDuplicateMemberLabel, memberIndexLocal); ilg.EndSwitch(); } else { ilg.Pop(); } ilg.EndFor(); CheckRequiredElements(expectedElements, requiredElements, throwMissingRequiredMembersLabel); Label endOfTypeLabel = ilg.DefineLabel(); ilg.Br(endOfTypeLabel); ilg.MarkLabel(throwDuplicateMemberLabel); ilg.Call(null, JsonFormatGeneratorStatics.ThrowDuplicateMemberExceptionMethod, objectLocal, memberNamesArg, memberIndexLocal); ilg.MarkLabel(throwMissingRequiredMembersLabel); ilg.Load(objectLocal); ilg.ConvertValue(objectLocal.LocalType, Globals.TypeOfObject); ilg.Load(memberNamesArg); expectedElements.LoadArray(); LoadArray(requiredElements, "requiredElements"); ilg.Call(JsonFormatGeneratorStatics.ThrowMissingRequiredMembersMethod); ilg.MarkLabel(endOfTypeLabel); } int ReadMembers(ClassDataContract classContract, BitFlagsGenerator expectedElements, Label[] memberLabels, Label throwDuplicateMemberLabel, LocalBuilder memberIndexLocal) { int memberCount = (classContract.BaseContract == null) ? 0 : ReadMembers(classContract.BaseContract, expectedElements, memberLabels, throwDuplicateMemberLabel, memberIndexLocal); for (int i = 0; i < classContract.Members.Count; i++, memberCount++) { DataMember dataMember = classContract.Members[i]; Type memberType = dataMember.MemberType; ilg.Case(memberLabels[memberCount], dataMember.Name); ilg.Set(memberIndexLocal, memberCount); expectedElements.Load(memberCount); ilg.Brfalse(throwDuplicateMemberLabel); LocalBuilder value = null; if (dataMember.IsGetOnlyCollection) { ilg.LoadAddress(objectLocal); ilg.LoadMember(dataMember.MemberInfo); value = ilg.DeclareLocal(memberType, dataMember.Name + "Value"); ilg.Stloc(value); ilg.Call(contextArg, XmlFormatGeneratorStatics.StoreCollectionMemberInfoMethod, value); ReadValue(memberType, dataMember.Name); } else { value = ReadValue(memberType, dataMember.Name); ilg.LoadAddress(objectLocal); ilg.ConvertAddress(objectLocal.LocalType, objectType); ilg.Ldloc(value); ilg.StoreMember(dataMember.MemberInfo); } ResetExpectedElements(expectedElements, memberCount); ilg.EndCase(); } return memberCount; } void CheckRequiredElements(BitFlagsGenerator expectedElements, byte[] requiredElements, Label throwMissingRequiredMembersLabel) { for (int i = 0; i < requiredElements.Length; i++) { ilg.Load(expectedElements.GetLocal(i)); ilg.Load(requiredElements[i]); ilg.And(); ilg.Load(0); ilg.Ceq(); ilg.Brfalse(throwMissingRequiredMembersLabel); } } void LoadArray(byte[] array, string name) { LocalBuilder localArray = ilg.DeclareLocal(Globals.TypeOfByteArray, name); ilg.NewArray(typeof(byte), array.Length); ilg.Store(localArray); for (int i = 0; i < array.Length; i++) { ilg.StoreArrayElement(localArray, i, array[i]); } ilg.Load(localArray); } int SetRequiredElements(ClassDataContract contract, byte[] requiredElements) { int memberCount = (contract.BaseContract == null) ? 0 : SetRequiredElements(contract.BaseContract, requiredElements); List<DataMember> members = contract.Members; for (int i = 0; i < members.Count; i++, memberCount++) { if (members[i].IsRequired) { BitFlagsGenerator.SetBit(requiredElements, memberCount); } } return memberCount; } void SetExpectedElements(BitFlagsGenerator expectedElements, int startIndex) { int memberCount = expectedElements.GetBitCount(); for (int i = startIndex; i < memberCount; i++) { expectedElements.Store(i, true); } } void ResetExpectedElements(BitFlagsGenerator expectedElements, int index) { expectedElements.Store(index, false); } void ReadISerializable(ClassDataContract classContract) { ConstructorInfo ctor = classContract.UnderlyingType.GetConstructor(Globals.ScanAllMembers, null, JsonFormatGeneratorStatics.SerInfoCtorArgs, null); if (ctor == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.SerializationInfo_ConstructorNotFound, DataContract.GetClrTypeFullName(classContract.UnderlyingType)))); ilg.LoadAddress(objectLocal); ilg.ConvertAddress(objectLocal.LocalType, objectType); ilg.Call(contextArg, XmlFormatGeneratorStatics.ReadSerializationInfoMethod, xmlReaderArg, classContract.UnderlyingType); ilg.Load(contextArg); ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod); ilg.Call(ctor); } LocalBuilder ReadValue(Type type, string name) { LocalBuilder value = ilg.DeclareLocal(type, "valueRead"); LocalBuilder nullableValue = null; int nullables = 0; while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) { nullables++; type = type.GetGenericArguments()[0]; } PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) { LocalBuilder objectId = ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); ilg.Call(contextArg, XmlFormatGeneratorStatics.ReadAttributesMethod, xmlReaderArg); ilg.Call(contextArg, XmlFormatGeneratorStatics.ReadIfNullOrRefMethod, xmlReaderArg, type, DataContract.IsTypeSerializable(type)); ilg.Stloc(objectId); // Deserialize null ilg.If(objectId, Cmp.EqualTo, Globals.NullObjectId); if (nullables != 0) { ilg.LoadAddress(value); ilg.InitObj(value.LocalType); } else if (type.IsValueType) ThrowSerializationException(SR.GetString(SR.ValueTypeCannotBeNull, DataContract.GetClrTypeFullName(type))); else { ilg.Load(null); ilg.Stloc(value); } // Deserialize value // Compare against Globals.NewObjectId, which is set to string.Empty ilg.ElseIfIsEmptyString(objectId); ilg.Call(contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod); ilg.Stloc(objectId); if (type.IsValueType) { ilg.IfNotIsEmptyString(objectId); ThrowSerializationException(SR.GetString(SR.ValueTypeCannotHaveId, DataContract.GetClrTypeFullName(type))); ilg.EndIf(); } if (nullables != 0) { nullableValue = value; value = ilg.DeclareLocal(type, "innerValueRead"); } if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) { ilg.Call(xmlReaderArg, primitiveContract.XmlFormatReaderMethod); ilg.Stloc(value); if (!type.IsValueType) ilg.Call(contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, value); } else { InternalDeserialize(value, type, name); } // Deserialize ref ilg.Else(); if (type.IsValueType) ThrowSerializationException(SR.GetString(SR.ValueTypeCannotHaveRef, DataContract.GetClrTypeFullName(type))); else { ilg.Call(contextArg, XmlFormatGeneratorStatics.GetExistingObjectMethod, objectId, type, name, string.Empty); ilg.ConvertValue(Globals.TypeOfObject, type); ilg.Stloc(value); } ilg.EndIf(); if (nullableValue != null) { ilg.If(objectId, Cmp.NotEqualTo, Globals.NullObjectId); WrapNullableObject(value, nullableValue, nullables); ilg.EndIf(); value = nullableValue; } } else { InternalDeserialize(value, type, name); } return value; } void InternalDeserialize(LocalBuilder value, Type type, string name) { ilg.Load(contextArg); ilg.Load(xmlReaderArg); Type declaredType = type.IsPointer ? Globals.TypeOfReflectionPointer : type; ilg.Load(DataContract.GetId(declaredType.TypeHandle)); ilg.Ldtoken(declaredType); ilg.Load(name); // Empty namespace ilg.Load(string.Empty); ilg.Call(XmlFormatGeneratorStatics.InternalDeserializeMethod); if (type.IsPointer) ilg.Call(JsonFormatGeneratorStatics.UnboxPointer); else ilg.ConvertValue(Globals.TypeOfObject, type); ilg.Stloc(value); } void WrapNullableObject(LocalBuilder innerValue, LocalBuilder outerValue, int nullables) { Type innerType = innerValue.LocalType, outerType = outerValue.LocalType; ilg.LoadAddress(outerValue); ilg.Load(innerValue); for (int i = 1; i < nullables; i++) { Type type = Globals.TypeOfNullable.MakeGenericType(innerType); ilg.New(type.GetConstructor(new Type[] { innerType })); innerType = type; } ilg.Call(outerType.GetConstructor(new Type[] { innerType })); } void ReadCollection(CollectionDataContract collectionContract) { Type type = collectionContract.UnderlyingType; Type itemType = collectionContract.ItemType; bool isArray = (collectionContract.Kind == CollectionKind.Array); ConstructorInfo constructor = collectionContract.Constructor; if (type.IsInterface) { switch (collectionContract.Kind) { case CollectionKind.GenericDictionary: type = Globals.TypeOfDictionaryGeneric.MakeGenericType(itemType.GetGenericArguments()); constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Globals.EmptyTypeArray, null); break; case CollectionKind.Dictionary: type = Globals.TypeOfHashtable; constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Globals.EmptyTypeArray, null); break; case CollectionKind.Collection: case CollectionKind.GenericCollection: case CollectionKind.Enumerable: case CollectionKind.GenericEnumerable: case CollectionKind.List: case CollectionKind.GenericList: type = itemType.MakeArrayType(); isArray = true; break; } } objectLocal = ilg.DeclareLocal(type, "objectDeserialized"); if (!isArray) { if (type.IsValueType) { ilg.Ldloca(objectLocal); ilg.InitObj(type); } else { ilg.New(constructor); ilg.Stloc(objectLocal); ilg.Call(contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, objectLocal); } } bool canReadSimpleDictionary = collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary; if (canReadSimpleDictionary) { ilg.Load(contextArg); ilg.LoadMember(JsonFormatGeneratorStatics.UseSimpleDictionaryFormatReadProperty); ilg.If(); ReadSimpleDictionary(collectionContract, itemType); ilg.Else(); } LocalBuilder objectId = ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); ilg.Call(contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod); ilg.Stloc(objectId); bool canReadPrimitiveArray = false; if (isArray && TryReadPrimitiveArray(itemType)) { canReadPrimitiveArray = true; ilg.IfNot(); } LocalBuilder growingCollection = null; if (isArray) { growingCollection = ilg.DeclareLocal(type, "growingCollection"); ilg.NewArray(itemType, 32); ilg.Stloc(growingCollection); } LocalBuilder i = ilg.DeclareLocal(Globals.TypeOfInt, "i"); object forLoop = ilg.For(i, 0, Int32.MaxValue); // Empty namespace IsStartElement(memberNamesArg, emptyDictionaryStringArg); ilg.If(); ilg.Call(contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); LocalBuilder value = ReadCollectionItem(collectionContract, itemType); if (isArray) { MethodInfo ensureArraySizeMethod = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod(itemType); ilg.Call(null, ensureArraySizeMethod, growingCollection, i); ilg.Stloc(growingCollection); ilg.StoreArrayElement(growingCollection, i, value); } else StoreCollectionValue(objectLocal, value, collectionContract); ilg.Else(); IsEndElement(); ilg.If(); ilg.Break(forLoop); ilg.Else(); HandleUnexpectedItemInCollection(i); ilg.EndIf(); ilg.EndIf(); ilg.EndFor(); if (isArray) { MethodInfo trimArraySizeMethod = XmlFormatGeneratorStatics.TrimArraySizeMethod.MakeGenericMethod(itemType); ilg.Call(null, trimArraySizeMethod, growingCollection, i); ilg.Stloc(objectLocal); ilg.Call(contextArg, XmlFormatGeneratorStatics.AddNewObjectWithIdMethod, objectId, objectLocal); } if (canReadPrimitiveArray) { ilg.Else(); ilg.Call(contextArg, XmlFormatGeneratorStatics.AddNewObjectWithIdMethod, objectId, objectLocal); ilg.EndIf(); } if (canReadSimpleDictionary) { ilg.EndIf(); } } void ReadSimpleDictionary(CollectionDataContract collectionContract, Type keyValueType) { Type[] keyValueTypes = keyValueType.GetGenericArguments(); Type keyType = keyValueTypes[0]; Type valueType = keyValueTypes[1]; int keyTypeNullableDepth = 0; Type keyTypeOriginal = keyType; while (keyType.IsGenericType && keyType.GetGenericTypeDefinition() == Globals.TypeOfNullable) { keyTypeNullableDepth++; keyType = keyType.GetGenericArguments()[0]; } ClassDataContract keyValueDataContract = (ClassDataContract)collectionContract.ItemContract; DataContract keyDataContract = keyValueDataContract.Members[0].MemberTypeContract; KeyParseMode keyParseMode = KeyParseMode.Fail; if (keyType == Globals.TypeOfString || keyType == Globals.TypeOfObject) { keyParseMode = KeyParseMode.AsString; } else if (keyType.IsEnum) { keyParseMode = KeyParseMode.UsingParseEnum; } else if (keyDataContract.ParseMethod != null) { keyParseMode = KeyParseMode.UsingCustomParse; } if (keyParseMode == KeyParseMode.Fail) { ThrowSerializationException( SR.GetString( SR.KeyTypeCannotBeParsedInSimpleDictionary, DataContract.GetClrTypeFullName(collectionContract.UnderlyingType), DataContract.GetClrTypeFullName(keyType))); } else { LocalBuilder nodeType = ilg.DeclareLocal(typeof(XmlNodeType), "nodeType"); ilg.BeginWhileCondition(); ilg.Call(xmlReaderArg, JsonFormatGeneratorStatics.MoveToContentMethod); ilg.Stloc(nodeType); ilg.Load(nodeType); ilg.Load(XmlNodeType.EndElement); ilg.BeginWhileBody(Cmp.NotEqualTo); ilg.Load(nodeType); ilg.Load(XmlNodeType.Element); ilg.If(Cmp.NotEqualTo); ThrowUnexpectedStateException(XmlNodeType.Element); ilg.EndIf(); ilg.Call(contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); if (keyParseMode == KeyParseMode.UsingParseEnum) { ilg.Load(keyType); } ilg.Load(xmlReaderArg); ilg.Call(JsonFormatGeneratorStatics.GetJsonMemberNameMethod); if (keyParseMode == KeyParseMode.UsingParseEnum) { ilg.Call(JsonFormatGeneratorStatics.ParseEnumMethod); ilg.ConvertValue(Globals.TypeOfObject, keyType); } else if (keyParseMode == KeyParseMode.UsingCustomParse) { ilg.Call(keyDataContract.ParseMethod); } LocalBuilder pairKey = ilg.DeclareLocal(keyType, "key"); ilg.Stloc(pairKey); if (keyTypeNullableDepth > 0) { LocalBuilder pairKeyNullable = ilg.DeclareLocal(keyTypeOriginal, "keyOriginal"); WrapNullableObject(pairKey, pairKeyNullable, keyTypeNullableDepth); pairKey = pairKeyNullable; } LocalBuilder pairValue = ReadValue(valueType, String.Empty); StoreKeyValuePair(objectLocal, collectionContract, pairKey, pairValue); ilg.EndWhile(); } } void ReadGetOnlyCollection(CollectionDataContract collectionContract) { Type type = collectionContract.UnderlyingType; Type itemType = collectionContract.ItemType; bool isArray = (collectionContract.Kind == CollectionKind.Array); LocalBuilder size = ilg.DeclareLocal(Globals.TypeOfInt, "arraySize"); objectLocal = ilg.DeclareLocal(type, "objectDeserialized"); ilg.Load(contextArg); ilg.LoadMember(XmlFormatGeneratorStatics.GetCollectionMemberMethod); ilg.ConvertValue(Globals.TypeOfObject, type); ilg.Stloc(objectLocal); bool canReadSimpleDictionary = collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary; if (canReadSimpleDictionary) { ilg.Load(contextArg); ilg.LoadMember(JsonFormatGeneratorStatics.UseSimpleDictionaryFormatReadProperty); ilg.If(); ilg.If(objectLocal, Cmp.EqualTo, null); ilg.Call(null, XmlFormatGeneratorStatics.ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod, type); ilg.Else(); ReadSimpleDictionary(collectionContract, itemType); ilg.Call(contextArg, XmlFormatGeneratorStatics.CheckEndOfArrayMethod, xmlReaderArg, size, memberNamesArg, emptyDictionaryStringArg); ilg.EndIf(); ilg.Else(); } //check that items are actually going to be deserialized into the collection IsStartElement(memberNamesArg, emptyDictionaryStringArg); ilg.If(); ilg.If(objectLocal, Cmp.EqualTo, null); ilg.Call(null, XmlFormatGeneratorStatics.ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod, type); ilg.Else(); if (isArray) { ilg.Load(objectLocal); ilg.Call(XmlFormatGeneratorStatics.GetArrayLengthMethod); ilg.Stloc(size); } LocalBuilder i = ilg.DeclareLocal(Globals.TypeOfInt, "i"); object forLoop = ilg.For(i, 0, Int32.MaxValue); IsStartElement(memberNamesArg, emptyDictionaryStringArg); ilg.If(); ilg.Call(contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); LocalBuilder value = ReadCollectionItem(collectionContract, itemType); if (isArray) { ilg.If(size, Cmp.EqualTo, i); ilg.Call(null, XmlFormatGeneratorStatics.ThrowArrayExceededSizeExceptionMethod, size, type); ilg.Else(); ilg.StoreArrayElement(objectLocal, i, value); ilg.EndIf(); } else StoreCollectionValue(objectLocal, value, collectionContract); ilg.Else(); IsEndElement(); ilg.If(); ilg.Break(forLoop); ilg.Else(); HandleUnexpectedItemInCollection(i); ilg.EndIf(); ilg.EndIf(); ilg.EndFor(); ilg.Call(contextArg, XmlFormatGeneratorStatics.CheckEndOfArrayMethod, xmlReaderArg, size, memberNamesArg, emptyDictionaryStringArg); ilg.EndIf(); ilg.EndIf(); if (canReadSimpleDictionary) { ilg.EndIf(); } } bool TryReadPrimitiveArray(Type itemType) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) return false; string readArrayMethod = null; switch (Type.GetTypeCode(itemType)) { case TypeCode.Boolean: readArrayMethod = "TryReadBooleanArray"; break; case TypeCode.Decimal: readArrayMethod = "TryReadDecimalArray"; break; case TypeCode.Int32: readArrayMethod = "TryReadInt32Array"; break; case TypeCode.Int64: readArrayMethod = "TryReadInt64Array"; break; case TypeCode.Single: readArrayMethod = "TryReadSingleArray"; break; case TypeCode.Double: readArrayMethod = "TryReadDoubleArray"; break; case TypeCode.DateTime: readArrayMethod = "TryReadJsonDateTimeArray"; break; default: break; } if (readArrayMethod != null) { ilg.Load(xmlReaderArg); ilg.ConvertValue(typeof(XmlReaderDelegator), typeof(JsonReaderDelegator)); ilg.Load(contextArg); ilg.Load(memberNamesArg); // Empty namespace ilg.Load(emptyDictionaryStringArg); // -1 Array Size ilg.Load(-1); ilg.Ldloca(objectLocal); ilg.Call(typeof(JsonReaderDelegator).GetMethod(readArrayMethod, Globals.ScanAllMembers)); return true; } return false; } LocalBuilder ReadCollectionItem(CollectionDataContract collectionContract, Type itemType) { if (collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary) { ilg.Call(contextArg, XmlFormatGeneratorStatics.ResetAttributesMethod); LocalBuilder value = ilg.DeclareLocal(itemType, "valueRead"); ilg.Load(collectionContractArg); ilg.Call(JsonFormatGeneratorStatics.GetItemContractMethod); ilg.Call(JsonFormatGeneratorStatics.GetRevisedItemContractMethod); ilg.Load(xmlReaderArg); ilg.Load(contextArg); ilg.Call(JsonFormatGeneratorStatics.ReadJsonValueMethod); ilg.ConvertValue(Globals.TypeOfObject, itemType); ilg.Stloc(value); return value; } else { return ReadValue(itemType, JsonGlobals.itemString); } } void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, CollectionDataContract collectionContract) { if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary) { ClassDataContract keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract; if (keyValuePairContract == null) { Fx.Assert("Failed to create contract for KeyValuePair type"); } DataMember keyMember = keyValuePairContract.Members[0]; DataMember valueMember = keyValuePairContract.Members[1]; LocalBuilder pairKey = ilg.DeclareLocal(keyMember.MemberType, keyMember.Name); LocalBuilder pairValue = ilg.DeclareLocal(valueMember.MemberType, valueMember.Name); ilg.LoadAddress(value); ilg.LoadMember(keyMember.MemberInfo); ilg.Stloc(pairKey); ilg.LoadAddress(value); ilg.LoadMember(valueMember.MemberInfo); ilg.Stloc(pairValue); StoreKeyValuePair(collection, collectionContract, pairKey, pairValue); } else { ilg.Call(collection, collectionContract.AddMethod, value); if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid) ilg.Pop(); } } void StoreKeyValuePair(LocalBuilder collection, CollectionDataContract collectionContract, LocalBuilder pairKey, LocalBuilder pairValue) { ilg.Call(collection, collectionContract.AddMethod, pairKey, pairValue); if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid) ilg.Pop(); } void HandleUnexpectedItemInCollection(LocalBuilder iterator) { IsStartElement(); ilg.If(); ilg.Call(contextArg, XmlFormatGeneratorStatics.SkipUnknownElementMethod, xmlReaderArg); ilg.Dec(iterator); ilg.Else(); ThrowUnexpectedStateException(XmlNodeType.Element); ilg.EndIf(); } void IsStartElement(ArgBuilder nameArg, ArgBuilder nsArg) { ilg.Call(xmlReaderArg, JsonFormatGeneratorStatics.IsStartElementMethod2, nameArg, nsArg); } void IsStartElement() { ilg.Call(xmlReaderArg, JsonFormatGeneratorStatics.IsStartElementMethod0); } void IsEndElement() { ilg.Load(xmlReaderArg); ilg.LoadMember(JsonFormatGeneratorStatics.NodeTypeProperty); ilg.Load(XmlNodeType.EndElement); ilg.Ceq(); } void ThrowUnexpectedStateException(XmlNodeType expectedState) { ilg.Call(null, XmlFormatGeneratorStatics.CreateUnexpectedStateExceptionMethod, expectedState, xmlReaderArg); ilg.Throw(); } void ThrowSerializationException(string msg, params object[] values) { if (values != null && values.Length > 0) ilg.CallStringFormat(msg, values); else ilg.Load(msg); ThrowSerializationException(); } void ThrowSerializationException() { ilg.New(JsonFormatGeneratorStatics.SerializationExceptionCtor); ilg.Throw(); } enum KeyParseMode { Fail, AsString, UsingParseEnum, UsingCustomParse } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.IO; using System.IO.Pipes; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.Services.Agent.Util; namespace Microsoft.VisualStudio.Services.Agent { [ServiceLocator(Default = typeof(JobNotification))] public interface IJobNotification : IAgentService, IDisposable { Task JobStarted(Guid jobId, string accessToken, Uri serverUrl, Guid planId, string identifier, string definitionId, string planType); Task JobCompleted(Guid jobId); void StartClient(string pipeName, string monitorSocketAddress, CancellationToken cancellationToken); void StartClient(string socketAddress, string monitorSocketAddress); } public sealed class JobNotification : AgentService, IJobNotification { private NamedPipeClientStream _outClient; private StreamWriter _writeStream; private Socket _socket; private Socket _monitorSocket; private bool _configured = false; private bool _useSockets = false; private bool _isMonitorConfigured = false; public async Task JobStarted(Guid jobId, string accessToken, Uri serverUrl, Guid planId, string identifier, string definitionId, string planType) { Trace.Info("Entering JobStarted Notification"); ArgUtil.NotNull(jobId, nameof(jobId)); ArgUtil.NotNull(accessToken, nameof(accessToken)); ArgUtil.NotNull(serverUrl, nameof(serverUrl)); ArgUtil.NotNull(planId, nameof(planId)); StartMonitor(jobId, accessToken, serverUrl, planId, identifier, definitionId, planType); if (_configured) { String message = $"Starting job: {jobId.ToString()}"; if (_useSockets) { try { Trace.Info("Writing JobStarted to socket"); _socket.Send(Encoding.UTF8.GetBytes(message)); Trace.Info("Finished JobStarted writing to socket"); } catch (SocketException e) { Trace.Error($"Failed sending message \"{message}\" on socket!"); Trace.Error(e); } } else { Trace.Info("Writing JobStarted to pipe"); await _writeStream.WriteLineAsync(message); await _writeStream.FlushAsync(); Trace.Info("Finished JobStarted writing to pipe"); } } } public async Task JobCompleted(Guid jobId) { Trace.Info("Entering JobCompleted Notification"); await EndMonitor(); if (_configured) { String message = $"Finished job: {jobId.ToString()}"; if (_useSockets) { try { Trace.Info("Writing JobCompleted to socket"); _socket.Send(Encoding.UTF8.GetBytes(message)); Trace.Info("Finished JobCompleted writing to socket"); } catch (SocketException e) { Trace.Error($"Failed sending message \"{message}\" on socket!"); Trace.Error(e); } } else { Trace.Info("Writing JobCompleted to pipe"); await _writeStream.WriteLineAsync(message); await _writeStream.FlushAsync(); Trace.Info("Finished JobCompleted writing to pipe"); } } } public async void StartClient(string pipeName, string monitorSocketAddress, CancellationToken cancellationToken) { if (pipeName != null && !_configured) { Trace.Info("Connecting to named pipe {0}", pipeName); _outClient = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.Asynchronous); await _outClient.ConnectAsync(cancellationToken); _writeStream = new StreamWriter(_outClient, Encoding.UTF8); _configured = true; Trace.Info("Connection successful to named pipe {0}", pipeName); } ConnectMonitor(monitorSocketAddress); } public void StartClient(string socketAddress, string monitorSocketAddress) { ArgUtil.NotNull(socketAddress, nameof(socketAddress)); ConnectMonitor(monitorSocketAddress); if (!_configured) { try { string[] splitAddress = socketAddress.Split(':'); if (splitAddress.Length != 2) { Trace.Error("Invalid socket address {0}. Job Notification will be disabled.", socketAddress); return; } IPAddress address; try { address = IPAddress.Parse(splitAddress[0]); } catch (FormatException e) { Trace.Error("Invalid socket ip address {0}. Job Notification will be disabled",splitAddress[0]); Trace.Error(e); return; } int port = -1; Int32.TryParse(splitAddress[1], out port); if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort) { Trace.Error("Invalid tcp socket port {0}. Job Notification will be disabled.", splitAddress[1]); return; } _socket = new Socket(SocketType.Stream, ProtocolType.Tcp); _socket.Connect(address, port); Trace.Info("Connection successful to socket {0}", socketAddress); _useSockets = true; _configured = true; } catch (SocketException e) { Trace.Error("Connection to socket {0} failed!", socketAddress); Trace.Error(e); } } } private void StartMonitor(Guid jobId, string accessToken, Uri serverUri, Guid planId, string identifier, string definitionId, string planType) { if(String.IsNullOrEmpty(accessToken)) { Trace.Info("No access token could be retrieved to start the monitor."); return; } try { Trace.Info("Entering StartMonitor"); if (_isMonitorConfigured) { String message = $"Start {jobId.ToString()} {accessToken} {serverUri.ToString()} {System.Diagnostics.Process.GetCurrentProcess().Id} {planId.ToString()} {identifier} {definitionId} {planType}"; Trace.Info("Writing StartMonitor to socket"); _monitorSocket.Send(Encoding.UTF8.GetBytes(message)); Trace.Info("Finished StartMonitor writing to socket"); } } catch (SocketException e) { Trace.Error($"Failed sending StartMonitor message on socket!"); Trace.Error(e); } catch (Exception e) { Trace.Error($"Unexpected error occured while sending StartMonitor message on socket!"); Trace.Error(e); } } private async Task EndMonitor() { try { Trace.Info("Entering EndMonitor"); if (_isMonitorConfigured) { String message = $"End {System.Diagnostics.Process.GetCurrentProcess().Id}"; Trace.Info("Writing EndMonitor to socket"); _monitorSocket.Send(Encoding.UTF8.GetBytes(message)); Trace.Info("Finished EndMonitor writing to socket"); await Task.Delay(TimeSpan.FromSeconds(2)); } } catch (SocketException e) { Trace.Error($"Failed sending end message on socket!"); Trace.Error(e); } catch (Exception e) { Trace.Error($"Unexpected error occured while sending StartMonitor message on socket!"); Trace.Error(e); } } private void ConnectMonitor(string monitorSocketAddress) { int port = -1; if (!_isMonitorConfigured && !String.IsNullOrEmpty(monitorSocketAddress)) { try { string[] splitAddress = monitorSocketAddress.Split(':'); if (splitAddress.Length != 2) { Trace.Error("Invalid socket address {0}. Unable to connect to monitor.", monitorSocketAddress); return; } IPAddress address; try { address = IPAddress.Parse(splitAddress[0]); } catch (FormatException e) { Trace.Error("Invalid socket IP address {0}. Unable to connect to monitor.", splitAddress[0]); Trace.Error(e); return; } Int32.TryParse(splitAddress[1], out port); if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort) { Trace.Error("Invalid TCP socket port {0}. Unable to connect to monitor.", splitAddress[1]); return; } Trace.Verbose("Trying to connect to monitor at port {0}", port); _monitorSocket = new Socket(SocketType.Stream, ProtocolType.Tcp); _monitorSocket.Connect(address, port); Trace.Info("Connection successful to local port {0}", port); _isMonitorConfigured = true; } catch (Exception e) { Trace.Error("Connection to monitor port {0} failed!", port); Trace.Error(e); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (disposing) { _outClient?.Dispose(); _writeStream?.Dispose(); if (_socket != null) { _socket.Send(Encoding.UTF8.GetBytes("<EOF>")); _socket.Shutdown(SocketShutdown.Both); _socket.Dispose(); _socket = null; } if (_monitorSocket != null) { _monitorSocket.Send(Encoding.UTF8.GetBytes("<EOF>")); _monitorSocket.Shutdown(SocketShutdown.Both); _monitorSocket.Dispose(); _monitorSocket = null; } } } } }
// // - ComponentName.cs - // // Copyright 2005, 2006, 2010 Carbonfrost Systems, Inc. (http://carbonfrost.com) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; namespace Carbonfrost.Commons.Shared.Runtime.Components { [TypeConverter(typeof(ComponentNameConverter))] [Serializable] [Builder(typeof(ComponentNameBuilder))] public sealed class ComponentName : IEquatable<ComponentName>, IFormattable { private readonly string name; private readonly Version version; private readonly CultureInfo culture; private readonly ProcessorArchitecture architecture; private readonly byte[] publicKey; private readonly bool usePublicKeyToken; private readonly ComponentHash hash; [NonSerialized] private int hashCodeCache; private static readonly ComponentName s_instance = new ComponentName("Unknown", null); // $NON-NLS-1 [SelfDescribingPriority(PriorityLevel.Low)] public ProcessorArchitecture Architecture { get { return architecture; } } [SelfDescribingPriority(PriorityLevel.High)] public CultureInfo Culture { get { return culture; } } public bool IsUnknown { get { return object.ReferenceEquals(this, ComponentName.Unknown); } } public ComponentHash Hash { get { return this.hash; } } [SelfDescribingPriority(PriorityLevel.High)] public string Name { get { return this.name; } } [SelfDescribingPriority(PriorityLevel.Low)] public ComponentNameQuality Quality { get { bool hasName = (Name != null && !Utility.IsAnonymousName(Name)); bool hasVersion = (Version != null); bool hasPublicKey = (this.publicKey != null && this.publicKey.Length > 0); bool hasHash = (this.Hash != null); bool hasCulture = !object.Equals(this.Culture, CultureInfo.InvariantCulture); ComponentNameQuality result = ((hasName) ? ComponentNameQuality.SpecifiedName : 0) | ((hasVersion) ? ComponentNameQuality.SpecifiedVersion : 0) | ((hasCulture) ? ComponentNameQuality.SpecifiedCulture : 0) | ((hasPublicKey) ? ComponentNameQuality.SpecifiedPublicKey : 0) | ((hasHash) ? ComponentNameQuality.SpecifiedHash : 0); return result; } } public static ComponentName Unknown { get { return s_instance; } } [SelfDescribingPriority(PriorityLevel.High)] public Version Version { get { return this.version; } } public ComponentName(string name, Version version) : this(name, version, null, null, CultureInfo.InvariantCulture) {} public ComponentName(string name, int majorVersion, int minorVersion, int build, int revision) : this(name, new Version(majorVersion, minorVersion, build, revision)) {} public ComponentName(string name, Version version, byte[] publicKey, byte[] hash, CultureInfo culture) { this.name = NameOrDefault(name); this.version = version; this.culture = culture ?? CultureInfo.InvariantCulture; this.publicKey = publicKey; if (hash != null) { this.hash = ComponentHash.Create(ComponentHashAlgorithm.MD5, hash); } } public ComponentName(string name, Version version, byte[] publicKey, ComponentHash hash, CultureInfo culture, ProcessorArchitecture architecture) : this(name, version, publicKey, hash, culture, architecture, false) { } internal ComponentName(string name, Version version, byte[] publicKey, ComponentHash hash, CultureInfo culture, ProcessorArchitecture architecture, bool usePublicKeyToken) { this.name = NameOrDefault(name); this.version = version ?? new Version(0, 0, 0, 0); this.culture = culture ?? CultureInfo.InvariantCulture; this.usePublicKeyToken = usePublicKeyToken; this.publicKey = publicKey; this.architecture = architecture; this.hash = hash; } public static ComponentName FromAssemblyName(AssemblyName name) { if (name == null) { throw new ArgumentNullException("name"); } // $NON-NLS-1 return new ComponentName( name.Name, name.Version, name.GetPublicKey(), null, name.CultureInfo, name.ProcessorArchitecture); } public static bool TryParse(string text, out ComponentName result) { return _TryParse(text, out result) == null; } internal static Exception _TryParse(string text, out ComponentName result) { result = null; if (text == null) return new ArgumentNullException("text"); // $NON-NLS-1 if (text.Length == 0) return Failure.EmptyString("text"); string[] items = text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (items.Length == 1) return _TryParseShortForm(text, out result); try { string name = items[0]; Dictionary<string, string> lookup = new Dictionary<string, string>(); for (int i = 1; i < items.Length; i++) { string s = items[i]; int index = s.IndexOf('='); if (index < 0) { throw Failure.NotParsable("text", typeof(ComponentName)); // $NON-NLS-1 } else { string key = s.Substring(0, index).Trim(); string value = s.Substring(index + 1).Trim(); lookup.Add(key, value); } } ComponentNameBuilder builder = new ComponentNameBuilder(); builder.Name = name; Exception exception = builder.ParseDictionary(lookup); if (exception == null) { result = builder.Build(); return null; } else return exception; } catch (ArgumentException a) { return Failure.NotParsable("text", typeof(ComponentName), a); // $NON-NLS-1 } catch (FormatException f) { return Failure.NotParsable("text", typeof(ComponentName), f); // $NON-NLS-1 } } static Exception _TryParseShortForm(string text, out ComponentName result) { // Name=1.0-ABCD-en-x86 result = null; string[] items = text.Split('='); if (items.Length == 1) { result = new ComponentName(text, null); return null; } if (items.Length != 2) return ParseError(); string[] qualifiers = items[1].Split('-'); Version version; ProcessorArchitecture arch = ProcessorArchitecture.None; CultureInfo culture = null; int cultureStart = 1; int cultureLength = qualifiers.Length - 1; byte[] key = null; if (!Version.TryParse(qualifiers[0], out version)) return ParseError(); if (Enum.TryParse(qualifiers[qualifiers.Length - 1], true, out arch)) { cultureLength--; } if (qualifiers.Length > 1 && qualifiers[1].Length > 2) { try { key = Utility.ConvertHexToBytes(qualifiers[1], false); cultureStart++; } catch (FormatException) { } } try { string cultureText = string.Join("-", qualifiers.Skip(cultureStart).Take(cultureLength)); if (cultureText.Length > 0) culture = CultureInfo.GetCultureInfo(cultureText); } catch (CultureNotFoundException) { return ParseError(); } result = new ComponentName(items[0], version, key, null, culture, arch, true); return null; } private static Exception ParseError() { return Failure.NotParsable("text", typeof(ComponentName)); } public static ComponentName Parse(string text) { ComponentName result; Exception ex = _TryParse(text, out result); if (ex == null) return result; else throw ex; } public byte[] GetPublicKey() { if (publicKey == null || usePublicKeyToken) { return Empty<byte>.Array; } else { return (byte[]) this.publicKey.Clone(); } } public byte[] GetPublicKeyToken() { if (usePublicKeyToken) return publicKey ?? Empty<byte>.Array; if (publicKey == null) { return Empty<byte>.Array; } else { SHA1 sha1 = SHA1.Create(); byte[] hashed = sha1.ComputeHash(publicKey); byte[] result = new byte[8]; Array.Copy(hashed, hashed.Length - 8, result, 0, 8); Array.Reverse(result); return result; } } public AssemblyName ToAssemblyName() { return new AssemblyName(this.ToString()); } public bool Matches(ComponentName name) { if (name == null) throw new ArgumentNullException("name"); if (object.ReferenceEquals(this, name)) return true; else return this.Name == name.Name && BlobMatches(this, name) && CultureMatches(this.Culture, name.Culture) && VersionMatches(this.Version, name.Version); } static bool CultureMatches(CultureInfo a, CultureInfo b) { return a == null || (a.Equals(b)); } static bool BlobMatches(ComponentName a, ComponentName b) { if (a.publicKey == null) return true; // TODO Possible (but highly unlikely) that this comparison needs to support the full key return a.GetPublicKeyToken().SequenceEqual(b.GetPublicKeyToken()); } static bool VersionMatches(Version a, Version b) { return a == null || (a.Major == b.Major && a.Minor == b.Minor && (a.Build == -1 || a.Build == b.Build) && (a.Revision == -1 || a.Revision == b.Revision)); } #region 'Object' overrides. public override int GetHashCode() { if (hashCodeCache == 0) { int hashCode = 0; unchecked { hashCode += 1000000007 * name.GetHashCode(); if (version != null) { hashCode += 1000000009 * version.GetHashCode(); } if (culture != null) { hashCode += 1000000021 * culture.GetHashCode(); } if (publicKey != null) { hashCode += 1000000087 * publicKey.GetHashCode(); } if (hash != null) { hashCode += 1000000093 * hash.GetHashCode(); } hashCode += 37 * usePublicKeyToken.GetHashCode(); hashCode += 1000000097 * architecture.GetHashCode(); } this.hashCodeCache = hashCode; if (this.hashCodeCache == 0) { hashCodeCache++; } } return this.hashCodeCache; } public override bool Equals(object obj) { ComponentName myIdentity = obj as ComponentName; if (myIdentity == null) { return false; } else if (this == obj) { return true; } else { return this.name == myIdentity.name && object.Equals(this.version, myIdentity.version) && object.Equals(this.culture, myIdentity.culture) && object.Equals(this.usePublicKeyToken, myIdentity.usePublicKeyToken) && this.GetPublicKeyEncoding() == myIdentity.GetPublicKeyEncoding() && this.architecture == myIdentity.architecture && object.Equals(this.Hash, myIdentity.Hash); } } public override string ToString() { StringBuilder result = new StringBuilder(); // Carbonfrost.Framework, Version=1.0, Culture=en-US, PublicKey=deadbeef, Hash=MD5:deadbeef, Architecture=... // Carbonfrost.Framework;version:1.0;culture:en-US;publicKey:deadbeef;hash:MD5:deadbeef;os:...;architecture:... result.Append(this.name); if (this.version != null) { result.Append(", Version="); // $NON-NLS-1 result.Append(version.ToString()); } if (this.culture != null) { result.Append(", Culture="); // $NON-NLS-1 if (this.culture.Equals(CultureInfo.InvariantCulture)) result.Append("neutral"); else result.Append(culture.ToString()); } if (this.publicKey != null) { string t = Utility.BytesToHex(this.GetPublicKeyToken(), true); result.Append(", PublicKeyToken="); // $NON-NLS-1 result.Append(t); } if (this.hash != null) { result.Append(", Hash="); // $NON-NLS-1 result.Append(this.hash); } if (this.architecture != ProcessorArchitecture.None) { result.Append(", Architecture="); // $NON-NLS-1 result.Append(this.architecture); } return result.ToString(); } #endregion #region 'IEquatable`1' implementation. bool IEquatable<ComponentName>.Equals(ComponentName other) { return Equals(other); } #endregion private string GetPublicKeyEncoding() { if (this.publicKey == null) { return string.Empty; } else { return Utility.BytesToHex(this.publicKey, true); } } static string NameOrDefault(string name) { if (string.IsNullOrEmpty(name)) return Guid.NewGuid().ToString(); else return name; } public string ToString(string format, IFormatProvider formatProvider = null) { if (string.IsNullOrEmpty(format)) format = "G"; switch (format[0]) { case 'g': case 'G': return ToString(); case 's': return ConvertToShortString(); case 'c': return Culture.Name; default: throw new FormatException(); } } private string ConvertToShortString() { StringBuilder sb = new StringBuilder(); sb.Append(Name); sb.Append('='); sb.Append(Version); if (this.publicKey != null) { sb.Append('-'); sb.Append(GetPublicKeyEncoding()); } if (Culture != null) { sb.Append('-'); sb.Append(Culture); } if (Architecture != ProcessorArchitecture.None) { sb.Append('-'); sb.Append(Architecture.ToString().ToLowerInvariant()); } return sb.ToString(); } } }
/* Copyright (c) 2010-2015 by Genstein and Jason Lautzenheiser. This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Trizbort { partial class SettingsDialog { /// <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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SettingsDialog)); this.m_okButton = new System.Windows.Forms.Button(); this.m_cancelButton = new System.Windows.Forms.Button(); this.m_handDrawnCheckBox = new System.Windows.Forms.CheckBox(); this.m_lineWidthUpDown = new System.Windows.Forms.NumericUpDown(); this.label5 = new System.Windows.Forms.Label(); this.m_linesGroupBox = new System.Windows.Forms.GroupBox(); this.label18 = new System.Windows.Forms.Label(); this.m_preferredDistanceBetweenRoomsUpDown = new System.Windows.Forms.NumericUpDown(); this.label8 = new System.Windows.Forms.Label(); this.m_textOffsetFromLineUpDown = new System.Windows.Forms.NumericUpDown(); this.label1 = new System.Windows.Forms.Label(); this.m_connectionStalkLengthUpDown = new System.Windows.Forms.NumericUpDown(); this.label4 = new System.Windows.Forms.Label(); this.m_arrowSizeUpDown = new System.Windows.Forms.NumericUpDown(); this.m_gridGroupBox = new System.Windows.Forms.GroupBox(); this.m_showOriginCheckBox = new System.Windows.Forms.CheckBox(); this.m_showGridCheckBox = new System.Windows.Forms.CheckBox(); this.m_snapToGridCheckBox = new System.Windows.Forms.CheckBox(); this.label6 = new System.Windows.Forms.Label(); this.m_gridSizeUpDown = new System.Windows.Forms.NumericUpDown(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label34 = new System.Windows.Forms.Label(); this.m_objectListOffsetFromRoomNumericUpDown = new System.Windows.Forms.NumericUpDown(); this.label13 = new System.Windows.Forms.Label(); this.m_darknessStripeSizeNumericUpDown = new System.Windows.Forms.NumericUpDown(); this.panel1 = new System.Windows.Forms.Panel(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage4 = new System.Windows.Forms.TabPage(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.label17 = new System.Windows.Forms.Label(); this.label16 = new System.Windows.Forms.Label(); this.m_historyTextBox = new System.Windows.Forms.TextBox(); this.label15 = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label(); this.m_descriptionTextBox = new System.Windows.Forms.TextBox(); this.label10 = new System.Windows.Forms.Label(); this.m_authorTextBox = new System.Windows.Forms.TextBox(); this.m_titleTextBox = new System.Windows.Forms.TextBox(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.m_colorsGroupBox = new System.Windows.Forms.GroupBox(); this.m_colorListBox = new System.Windows.Forms.ListBox(); this.m_changeColorButton = new System.Windows.Forms.Button(); this.m_fontsGroupBox = new System.Windows.Forms.GroupBox(); this.label9 = new System.Windows.Forms.Label(); this.m_lineFontSizeTextBox = new System.Windows.Forms.TextBox(); this.m_changeLineFontButton = new System.Windows.Forms.Button(); this.m_lineFontNameTextBox = new System.Windows.Forms.TextBox(); this.label12 = new System.Windows.Forms.Label(); this.m_smallFontSizeTextBox = new System.Windows.Forms.TextBox(); this.m_changeSmallFontButton = new System.Windows.Forms.Button(); this.m_smallFontNameTextBox = new System.Windows.Forms.TextBox(); this.label11 = new System.Windows.Forms.Label(); this.m_largeFontSizeTextBox = new System.Windows.Forms.TextBox(); this.m_changeLargeFontButton = new System.Windows.Forms.Button(); this.m_largeFontNameTextBox = new System.Windows.Forms.TextBox(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.tabRegions = new System.Windows.Forms.TabPage(); this.label19 = new System.Windows.Forms.Label(); this.btnDeleteRegion = new System.Windows.Forms.Button(); this.btnAddRegion = new System.Windows.Forms.Button(); this.btnChange = new System.Windows.Forms.Button(); this.m_RegionListing = new System.Windows.Forms.ListBox(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.label7 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.m_snapToElementDistanceUpDown = new System.Windows.Forms.NumericUpDown(); this.label2 = new System.Windows.Forms.Label(); this.m_handleSizeUpDown = new System.Windows.Forms.NumericUpDown(); this.propertySettings1 = new DevComponents.DotNetBar.PropertySettings(); this.superTooltip1 = new DevComponents.DotNetBar.SuperTooltip(); ((System.ComponentModel.ISupportInitialize)(this.m_lineWidthUpDown)).BeginInit(); this.m_linesGroupBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.m_preferredDistanceBetweenRoomsUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.m_textOffsetFromLineUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.m_connectionStalkLengthUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.m_arrowSizeUpDown)).BeginInit(); this.m_gridGroupBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.m_gridSizeUpDown)).BeginInit(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.m_objectListOffsetFromRoomNumericUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.m_darknessStripeSizeNumericUpDown)).BeginInit(); this.panel1.SuspendLayout(); this.tabControl1.SuspendLayout(); this.tabPage4.SuspendLayout(); this.groupBox3.SuspendLayout(); this.tabPage1.SuspendLayout(); this.m_colorsGroupBox.SuspendLayout(); this.m_fontsGroupBox.SuspendLayout(); this.tabPage2.SuspendLayout(); this.tabRegions.SuspendLayout(); this.tabPage3.SuspendLayout(); this.groupBox2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.m_snapToElementDistanceUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.m_handleSizeUpDown)).BeginInit(); this.SuspendLayout(); // // m_okButton // this.m_okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.m_okButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.m_okButton.Location = new System.Drawing.Point(207, 12); this.m_okButton.Name = "m_okButton"; this.m_okButton.Size = new System.Drawing.Size(75, 23); this.m_okButton.TabIndex = 0; this.m_okButton.Text = "OK"; this.m_okButton.UseVisualStyleBackColor = true; // // m_cancelButton // this.m_cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.m_cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.m_cancelButton.Location = new System.Drawing.Point(288, 12); this.m_cancelButton.Name = "m_cancelButton"; this.m_cancelButton.Size = new System.Drawing.Size(75, 23); this.m_cancelButton.TabIndex = 1; this.m_cancelButton.Text = "Cancel"; this.m_cancelButton.UseVisualStyleBackColor = true; // // m_handDrawnCheckBox // this.m_handDrawnCheckBox.AutoSize = true; this.m_handDrawnCheckBox.Cursor = System.Windows.Forms.Cursors.Help; this.m_handDrawnCheckBox.Location = new System.Drawing.Point(48, 20); this.m_handDrawnCheckBox.Name = "m_handDrawnCheckBox"; this.m_handDrawnCheckBox.Size = new System.Drawing.Size(93, 17); this.superTooltip1.SetSuperTooltip(this.m_handDrawnCheckBox, new DevComponents.DotNetBar.SuperTooltipInfo("Hand-drawn", "", "By default Trizbort gives lines a \"hand drawn\" appearance. If you prefer straight" + " lines, you can uncheck this box. This applies to connections\' lines, the border" + " of a room, and dividing fill lines.", null, null, DevComponents.DotNetBar.eTooltipColor.Orange)); this.m_handDrawnCheckBox.TabIndex = 0; this.m_handDrawnCheckBox.Text = "\"&Hand-drawn\""; this.m_handDrawnCheckBox.UseVisualStyleBackColor = true; // // m_lineWidthUpDown // this.m_lineWidthUpDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.m_lineWidthUpDown.DecimalPlaces = 1; this.m_lineWidthUpDown.Increment = new decimal(new int[] { 5, 0, 0, 65536}); this.m_lineWidthUpDown.Location = new System.Drawing.Point(242, 19); this.m_lineWidthUpDown.Name = "m_lineWidthUpDown"; this.m_lineWidthUpDown.Size = new System.Drawing.Size(95, 21); this.m_lineWidthUpDown.TabIndex = 2; this.m_lineWidthUpDown.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.m_lineWidthUpDown.Value = new decimal(new int[] { 1, 0, 0, 0}); // // label5 // this.label5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label5.AutoSize = true; this.label5.Cursor = System.Windows.Forms.Cursors.Help; this.label5.Location = new System.Drawing.Point(201, 21); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(35, 13); this.superTooltip1.SetSuperTooltip(this.label5, new DevComponents.DotNetBar.SuperTooltipInfo("Line Width", "", "The width of lines, in pixels. This applies to both connections\' lines and the bo" + "rder of a room.", null, null, DevComponents.DotNetBar.eTooltipColor.Orange)); this.label5.TabIndex = 1; this.label5.Text = "&Width"; // // m_linesGroupBox // this.m_linesGroupBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_linesGroupBox.Controls.Add(this.label18); this.m_linesGroupBox.Controls.Add(this.m_preferredDistanceBetweenRoomsUpDown); this.m_linesGroupBox.Controls.Add(this.label8); this.m_linesGroupBox.Controls.Add(this.m_textOffsetFromLineUpDown); this.m_linesGroupBox.Controls.Add(this.label1); this.m_linesGroupBox.Controls.Add(this.m_connectionStalkLengthUpDown); this.m_linesGroupBox.Controls.Add(this.label4); this.m_linesGroupBox.Controls.Add(this.m_arrowSizeUpDown); this.m_linesGroupBox.Controls.Add(this.m_handDrawnCheckBox); this.m_linesGroupBox.Controls.Add(this.label5); this.m_linesGroupBox.Controls.Add(this.m_lineWidthUpDown); this.m_linesGroupBox.Location = new System.Drawing.Point(5, 6); this.m_linesGroupBox.Name = "m_linesGroupBox"; this.m_linesGroupBox.Size = new System.Drawing.Size(343, 163); this.m_linesGroupBox.TabIndex = 0; this.m_linesGroupBox.TabStop = false; this.m_linesGroupBox.Text = "&Lines"; // // label18 // this.label18.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label18.AutoSize = true; this.label18.Cursor = System.Windows.Forms.Cursors.Help; this.label18.Location = new System.Drawing.Point(62, 100); this.label18.Name = "label18"; this.label18.Size = new System.Drawing.Size(177, 13); this.superTooltip1.SetSuperTooltip(this.label18, new DevComponents.DotNetBar.SuperTooltipInfo("Preferred Distance Between Rooms", "", resources.GetString("label18.SuperTooltip"), null, null, DevComponents.DotNetBar.eTooltipColor.Orange)); this.label18.TabIndex = 7; this.label18.Text = "&Preferred Distance Between Rooms"; // // m_preferredDistanceBetweenRoomsUpDown // this.m_preferredDistanceBetweenRoomsUpDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.m_preferredDistanceBetweenRoomsUpDown.DecimalPlaces = 1; this.m_preferredDistanceBetweenRoomsUpDown.Location = new System.Drawing.Point(242, 98); this.m_preferredDistanceBetweenRoomsUpDown.Maximum = new decimal(new int[] { 4096, 0, 0, 0}); this.m_preferredDistanceBetweenRoomsUpDown.Name = "m_preferredDistanceBetweenRoomsUpDown"; this.m_preferredDistanceBetweenRoomsUpDown.Size = new System.Drawing.Size(95, 21); this.m_preferredDistanceBetweenRoomsUpDown.TabIndex = 8; this.m_preferredDistanceBetweenRoomsUpDown.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.m_preferredDistanceBetweenRoomsUpDown.Value = new decimal(new int[] { 1, 0, 0, 0}); // // label8 // this.label8.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label8.AutoSize = true; this.label8.Cursor = System.Windows.Forms.Cursors.Help; this.label8.Location = new System.Drawing.Point(127, 127); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(112, 13); this.superTooltip1.SetSuperTooltip(this.label8, new DevComponents.DotNetBar.SuperTooltipInfo("Text Offset From Line", "", "Trizbort automatically adds a gap between a connection\'s line and any labels on t" + "hat line. This setting controls how large that gap is.", null, null, DevComponents.DotNetBar.eTooltipColor.Orange)); this.label8.TabIndex = 9; this.label8.Text = "&Text Offset From Line"; // // m_textOffsetFromLineUpDown // this.m_textOffsetFromLineUpDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.m_textOffsetFromLineUpDown.DecimalPlaces = 1; this.m_textOffsetFromLineUpDown.Location = new System.Drawing.Point(242, 125); this.m_textOffsetFromLineUpDown.Maximum = new decimal(new int[] { 4096, 0, 0, 0}); this.m_textOffsetFromLineUpDown.Name = "m_textOffsetFromLineUpDown"; this.m_textOffsetFromLineUpDown.Size = new System.Drawing.Size(95, 21); this.m_textOffsetFromLineUpDown.TabIndex = 10; this.m_textOffsetFromLineUpDown.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.m_textOffsetFromLineUpDown.Value = new decimal(new int[] { 1, 0, 0, 0}); // // label1 // this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label1.AutoSize = true; this.label1.Cursor = System.Windows.Forms.Cursors.Help; this.label1.Location = new System.Drawing.Point(111, 73); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(128, 13); this.superTooltip1.SetSuperTooltip(this.label1, new DevComponents.DotNetBar.SuperTooltipInfo("Room Arrow Stalk Length", "", resources.GetString("label1.SuperTooltip"), null, null, DevComponents.DotNetBar.eTooltipColor.Orange)); this.label1.TabIndex = 5; this.label1.Text = "&Room Arrow Stalk Length"; // // m_connectionStalkLengthUpDown // this.m_connectionStalkLengthUpDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.m_connectionStalkLengthUpDown.DecimalPlaces = 1; this.m_connectionStalkLengthUpDown.Location = new System.Drawing.Point(242, 71); this.m_connectionStalkLengthUpDown.Maximum = new decimal(new int[] { 4096, 0, 0, 0}); this.m_connectionStalkLengthUpDown.Name = "m_connectionStalkLengthUpDown"; this.m_connectionStalkLengthUpDown.Size = new System.Drawing.Size(95, 21); this.m_connectionStalkLengthUpDown.TabIndex = 6; this.m_connectionStalkLengthUpDown.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.m_connectionStalkLengthUpDown.Value = new decimal(new int[] { 1, 0, 0, 0}); // // label4 // this.label4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label4.AutoSize = true; this.label4.Cursor = System.Windows.Forms.Cursors.Help; this.label4.Location = new System.Drawing.Point(179, 47); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(58, 13); this.superTooltip1.SetSuperTooltip(this.label4, new DevComponents.DotNetBar.SuperTooltipInfo("Arrow Size", "", "The pixel size of the base of arrows drawn on one way connections.", null, null, DevComponents.DotNetBar.eTooltipColor.Orange)); this.label4.TabIndex = 3; this.label4.Text = "&Arrow Size"; // // m_arrowSizeUpDown // this.m_arrowSizeUpDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.m_arrowSizeUpDown.DecimalPlaces = 1; this.m_arrowSizeUpDown.Location = new System.Drawing.Point(242, 45); this.m_arrowSizeUpDown.Maximum = new decimal(new int[] { 4096, 0, 0, 0}); this.m_arrowSizeUpDown.Name = "m_arrowSizeUpDown"; this.m_arrowSizeUpDown.Size = new System.Drawing.Size(95, 21); this.m_arrowSizeUpDown.TabIndex = 4; this.m_arrowSizeUpDown.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.m_arrowSizeUpDown.Value = new decimal(new int[] { 1, 0, 0, 0}); // // m_gridGroupBox // this.m_gridGroupBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_gridGroupBox.Controls.Add(this.m_showOriginCheckBox); this.m_gridGroupBox.Controls.Add(this.m_showGridCheckBox); this.m_gridGroupBox.Controls.Add(this.m_snapToGridCheckBox); this.m_gridGroupBox.Controls.Add(this.label6); this.m_gridGroupBox.Controls.Add(this.m_gridSizeUpDown); this.m_gridGroupBox.Location = new System.Drawing.Point(5, 175); this.m_gridGroupBox.Name = "m_gridGroupBox"; this.m_gridGroupBox.Size = new System.Drawing.Size(343, 72); this.m_gridGroupBox.TabIndex = 1; this.m_gridGroupBox.TabStop = false; this.m_gridGroupBox.Text = "&Grid"; // // m_showOriginCheckBox // this.m_showOriginCheckBox.AutoSize = true; this.m_showOriginCheckBox.Location = new System.Drawing.Point(114, 20); this.m_showOriginCheckBox.Name = "m_showOriginCheckBox"; this.m_showOriginCheckBox.Size = new System.Drawing.Size(83, 17); this.m_showOriginCheckBox.TabIndex = 2; this.m_showOriginCheckBox.Text = "Show &Origin"; this.m_showOriginCheckBox.UseVisualStyleBackColor = true; // // m_showGridCheckBox // this.m_showGridCheckBox.AutoSize = true; this.m_showGridCheckBox.Location = new System.Drawing.Point(45, 20); this.m_showGridCheckBox.Name = "m_showGridCheckBox"; this.m_showGridCheckBox.Size = new System.Drawing.Size(55, 17); this.m_showGridCheckBox.TabIndex = 0; this.m_showGridCheckBox.Text = "&Visible"; this.m_showGridCheckBox.UseVisualStyleBackColor = true; // // m_snapToGridCheckBox // this.m_snapToGridCheckBox.AutoSize = true; this.m_snapToGridCheckBox.Location = new System.Drawing.Point(45, 43); this.m_snapToGridCheckBox.Name = "m_snapToGridCheckBox"; this.m_snapToGridCheckBox.Size = new System.Drawing.Size(65, 17); this.m_snapToGridCheckBox.TabIndex = 1; this.m_snapToGridCheckBox.Text = "S&nap To"; this.m_snapToGridCheckBox.UseVisualStyleBackColor = true; // // label6 // this.label6.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(212, 20); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(26, 13); this.label6.TabIndex = 3; this.label6.Text = "&Size"; // // m_gridSizeUpDown // this.m_gridSizeUpDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.m_gridSizeUpDown.DecimalPlaces = 1; this.m_gridSizeUpDown.Location = new System.Drawing.Point(242, 16); this.m_gridSizeUpDown.Maximum = new decimal(new int[] { 4096, 0, 0, 0}); this.m_gridSizeUpDown.Minimum = new decimal(new int[] { 2, 0, 0, 0}); this.m_gridSizeUpDown.Name = "m_gridSizeUpDown"; this.m_gridSizeUpDown.Size = new System.Drawing.Size(95, 21); this.m_gridSizeUpDown.TabIndex = 4; this.m_gridSizeUpDown.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.m_gridSizeUpDown.Value = new decimal(new int[] { 2, 0, 0, 0}); // // groupBox1 // this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox1.Controls.Add(this.label34); this.groupBox1.Controls.Add(this.m_objectListOffsetFromRoomNumericUpDown); this.groupBox1.Controls.Add(this.label13); this.groupBox1.Controls.Add(this.m_darknessStripeSizeNumericUpDown); this.groupBox1.Location = new System.Drawing.Point(5, 6); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(343, 72); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.groupBox1.Text = "&Room"; // // label34 // this.label34.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label34.AutoSize = true; this.label34.Location = new System.Drawing.Point(148, 43); this.label34.Name = "label34"; this.label34.Size = new System.Drawing.Size(92, 13); this.label34.TabIndex = 2; this.label34.Text = "&Object List Offset"; // // m_objectListOffsetFromRoomNumericUpDown // this.m_objectListOffsetFromRoomNumericUpDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.m_objectListOffsetFromRoomNumericUpDown.DecimalPlaces = 1; this.m_objectListOffsetFromRoomNumericUpDown.Location = new System.Drawing.Point(242, 41); this.m_objectListOffsetFromRoomNumericUpDown.Maximum = new decimal(new int[] { 4096, 0, 0, 0}); this.m_objectListOffsetFromRoomNumericUpDown.Name = "m_objectListOffsetFromRoomNumericUpDown"; this.m_objectListOffsetFromRoomNumericUpDown.Size = new System.Drawing.Size(95, 21); this.m_objectListOffsetFromRoomNumericUpDown.TabIndex = 3; this.m_objectListOffsetFromRoomNumericUpDown.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.m_objectListOffsetFromRoomNumericUpDown.Value = new decimal(new int[] { 1, 0, 0, 0}); // // label13 // this.label13.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label13.AutoSize = true; this.label13.Location = new System.Drawing.Point(133, 17); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(104, 13); this.label13.TabIndex = 0; this.label13.Text = "&Darkness Stripe Size"; // // m_darknessStripeSizeNumericUpDown // this.m_darknessStripeSizeNumericUpDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.m_darknessStripeSizeNumericUpDown.DecimalPlaces = 1; this.m_darknessStripeSizeNumericUpDown.Location = new System.Drawing.Point(242, 15); this.m_darknessStripeSizeNumericUpDown.Maximum = new decimal(new int[] { 4096, 0, 0, 0}); this.m_darknessStripeSizeNumericUpDown.Name = "m_darknessStripeSizeNumericUpDown"; this.m_darknessStripeSizeNumericUpDown.Size = new System.Drawing.Size(95, 21); this.m_darknessStripeSizeNumericUpDown.TabIndex = 1; this.m_darknessStripeSizeNumericUpDown.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.m_darknessStripeSizeNumericUpDown.Value = new decimal(new int[] { 1, 0, 0, 0}); // // panel1 // this.panel1.Controls.Add(this.m_okButton); this.panel1.Controls.Add(this.m_cancelButton); this.panel1.Dock = System.Windows.Forms.DockStyle.Top; this.panel1.Location = new System.Drawing.Point(10, 327); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(363, 35); this.panel1.TabIndex = 1; // // tabControl1 // this.tabControl1.Controls.Add(this.tabPage4); this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Controls.Add(this.tabRegions); this.tabControl1.Controls.Add(this.tabPage3); this.tabControl1.Dock = System.Windows.Forms.DockStyle.Top; this.tabControl1.Location = new System.Drawing.Point(10, 10); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(363, 317); this.tabControl1.TabIndex = 0; this.tabControl1.Selected += new System.Windows.Forms.TabControlEventHandler(this.tabControl1_Selected); // // tabPage4 // this.tabPage4.Controls.Add(this.groupBox3); this.tabPage4.Location = new System.Drawing.Point(4, 22); this.tabPage4.Name = "tabPage4"; this.tabPage4.Size = new System.Drawing.Size(355, 291); this.tabPage4.TabIndex = 3; this.tabPage4.Text = "About"; this.tabPage4.UseVisualStyleBackColor = true; // // groupBox3 // this.groupBox3.Controls.Add(this.label17); this.groupBox3.Controls.Add(this.label16); this.groupBox3.Controls.Add(this.m_historyTextBox); this.groupBox3.Controls.Add(this.label15); this.groupBox3.Controls.Add(this.label14); this.groupBox3.Controls.Add(this.m_descriptionTextBox); this.groupBox3.Controls.Add(this.label10); this.groupBox3.Controls.Add(this.m_authorTextBox); this.groupBox3.Controls.Add(this.m_titleTextBox); this.groupBox3.Location = new System.Drawing.Point(5, 6); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(343, 274); this.groupBox3.TabIndex = 0; this.groupBox3.TabStop = false; this.groupBox3.Text = "&Map"; // // label17 // this.label17.AutoSize = true; this.label17.Location = new System.Drawing.Point(24, 186); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(41, 13); this.label17.TabIndex = 7; this.label17.Text = "&History"; // // label16 // this.label16.AutoSize = true; this.label16.ForeColor = System.Drawing.SystemColors.GrayText; this.label16.Location = new System.Drawing.Point(6, 19); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(306, 13); this.label16.TabIndex = 0; this.label16.Text = "These details help identify your map to others who may see it."; // // m_historyTextBox // this.m_historyTextBox.AcceptsReturn = true; this.m_historyTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_historyTextBox.BackColor = System.Drawing.SystemColors.Window; this.m_historyTextBox.Location = new System.Drawing.Point(69, 183); this.m_historyTextBox.Multiline = true; this.m_historyTextBox.Name = "m_historyTextBox"; this.m_historyTextBox.Size = new System.Drawing.Size(265, 82); this.m_historyTextBox.TabIndex = 8; // // label15 // this.label15.AutoSize = true; this.label15.Location = new System.Drawing.Point(3, 98); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(60, 13); this.label15.TabIndex = 5; this.label15.Text = "&Description"; // // label14 // this.label14.AutoSize = true; this.label14.Location = new System.Drawing.Point(25, 72); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(40, 13); this.label14.TabIndex = 3; this.label14.Text = "&Author"; // // m_descriptionTextBox // this.m_descriptionTextBox.AcceptsReturn = true; this.m_descriptionTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_descriptionTextBox.BackColor = System.Drawing.SystemColors.Window; this.m_descriptionTextBox.Location = new System.Drawing.Point(69, 95); this.m_descriptionTextBox.Multiline = true; this.m_descriptionTextBox.Name = "m_descriptionTextBox"; this.m_descriptionTextBox.Size = new System.Drawing.Size(265, 82); this.m_descriptionTextBox.TabIndex = 6; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(36, 46); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(27, 13); this.label10.TabIndex = 1; this.label10.Text = "&Title"; // // m_authorTextBox // this.m_authorTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_authorTextBox.BackColor = System.Drawing.SystemColors.Window; this.m_authorTextBox.Location = new System.Drawing.Point(69, 69); this.m_authorTextBox.Name = "m_authorTextBox"; this.m_authorTextBox.Size = new System.Drawing.Size(265, 21); this.m_authorTextBox.TabIndex = 4; // // m_titleTextBox // this.m_titleTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_titleTextBox.BackColor = System.Drawing.SystemColors.Window; this.m_titleTextBox.Location = new System.Drawing.Point(69, 43); this.m_titleTextBox.Name = "m_titleTextBox"; this.m_titleTextBox.Size = new System.Drawing.Size(265, 21); this.m_titleTextBox.TabIndex = 2; // // tabPage1 // this.tabPage1.Controls.Add(this.m_colorsGroupBox); this.tabPage1.Controls.Add(this.m_fontsGroupBox); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(355, 291); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Colors and Fonts"; this.tabPage1.UseVisualStyleBackColor = true; // // m_colorsGroupBox // this.m_colorsGroupBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_colorsGroupBox.Controls.Add(this.m_colorListBox); this.m_colorsGroupBox.Controls.Add(this.m_changeColorButton); this.m_colorsGroupBox.Location = new System.Drawing.Point(5, 6); this.m_colorsGroupBox.Name = "m_colorsGroupBox"; this.m_colorsGroupBox.Size = new System.Drawing.Size(343, 172); this.m_colorsGroupBox.TabIndex = 0; this.m_colorsGroupBox.TabStop = false; this.m_colorsGroupBox.Text = "&Colors"; // // m_colorListBox // this.m_colorListBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_colorListBox.FormattingEnabled = true; this.m_colorListBox.Items.AddRange(new object[] { "Canvas", "Fill", "Border", "Line", "Selected Line", "Hover Line", "Room Text", "Object Text", "Line Text", "Grid"}); this.m_colorListBox.Location = new System.Drawing.Point(82, 19); this.m_colorListBox.Name = "m_colorListBox"; this.m_colorListBox.Size = new System.Drawing.Size(174, 147); this.m_colorListBox.TabIndex = 0; this.m_colorListBox.DoubleClick += new System.EventHandler(this.onChangeColor); // // m_changeColorButton // this.m_changeColorButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.m_changeColorButton.Location = new System.Drawing.Point(262, 19); this.m_changeColorButton.Name = "m_changeColorButton"; this.m_changeColorButton.Size = new System.Drawing.Size(75, 23); this.m_changeColorButton.TabIndex = 1; this.m_changeColorButton.Text = "C&hange..."; this.m_changeColorButton.UseVisualStyleBackColor = true; this.m_changeColorButton.Click += new System.EventHandler(this.onChangeColor); // // m_fontsGroupBox // this.m_fontsGroupBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_fontsGroupBox.Controls.Add(this.label9); this.m_fontsGroupBox.Controls.Add(this.m_lineFontSizeTextBox); this.m_fontsGroupBox.Controls.Add(this.m_changeLineFontButton); this.m_fontsGroupBox.Controls.Add(this.m_lineFontNameTextBox); this.m_fontsGroupBox.Controls.Add(this.label12); this.m_fontsGroupBox.Controls.Add(this.m_smallFontSizeTextBox); this.m_fontsGroupBox.Controls.Add(this.m_changeSmallFontButton); this.m_fontsGroupBox.Controls.Add(this.m_smallFontNameTextBox); this.m_fontsGroupBox.Controls.Add(this.label11); this.m_fontsGroupBox.Controls.Add(this.m_largeFontSizeTextBox); this.m_fontsGroupBox.Controls.Add(this.m_changeLargeFontButton); this.m_fontsGroupBox.Controls.Add(this.m_largeFontNameTextBox); this.m_fontsGroupBox.Location = new System.Drawing.Point(5, 184); this.m_fontsGroupBox.Name = "m_fontsGroupBox"; this.m_fontsGroupBox.Size = new System.Drawing.Size(343, 99); this.m_fontsGroupBox.TabIndex = 1; this.m_fontsGroupBox.TabStop = false; this.m_fontsGroupBox.Text = "&Fonts"; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(39, 73); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(26, 13); this.label9.TabIndex = 8; this.label9.Text = "&Line"; // // m_lineFontSizeTextBox // this.m_lineFontSizeTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.m_lineFontSizeTextBox.BackColor = System.Drawing.SystemColors.Window; this.m_lineFontSizeTextBox.Location = new System.Drawing.Point(225, 70); this.m_lineFontSizeTextBox.Name = "m_lineFontSizeTextBox"; this.m_lineFontSizeTextBox.ReadOnly = true; this.m_lineFontSizeTextBox.Size = new System.Drawing.Size(31, 21); this.m_lineFontSizeTextBox.TabIndex = 10; // // m_changeLineFontButton // this.m_changeLineFontButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.m_changeLineFontButton.Location = new System.Drawing.Point(262, 68); this.m_changeLineFontButton.Name = "m_changeLineFontButton"; this.m_changeLineFontButton.Size = new System.Drawing.Size(75, 23); this.m_changeLineFontButton.TabIndex = 11; this.m_changeLineFontButton.Text = "Cha&nge..."; this.m_changeLineFontButton.UseVisualStyleBackColor = true; this.m_changeLineFontButton.Click += new System.EventHandler(this.ChangeLineFontButton_Click); // // m_lineFontNameTextBox // this.m_lineFontNameTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_lineFontNameTextBox.BackColor = System.Drawing.SystemColors.Window; this.m_lineFontNameTextBox.Location = new System.Drawing.Point(82, 70); this.m_lineFontNameTextBox.Name = "m_lineFontNameTextBox"; this.m_lineFontNameTextBox.ReadOnly = true; this.m_lineFontNameTextBox.Size = new System.Drawing.Size(137, 21); this.m_lineFontNameTextBox.TabIndex = 9; // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(39, 47); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(39, 13); this.label12.TabIndex = 4; this.label12.Text = "&Object"; // // m_smallFontSizeTextBox // this.m_smallFontSizeTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.m_smallFontSizeTextBox.BackColor = System.Drawing.SystemColors.Window; this.m_smallFontSizeTextBox.Location = new System.Drawing.Point(225, 44); this.m_smallFontSizeTextBox.Name = "m_smallFontSizeTextBox"; this.m_smallFontSizeTextBox.ReadOnly = true; this.m_smallFontSizeTextBox.Size = new System.Drawing.Size(31, 21); this.m_smallFontSizeTextBox.TabIndex = 6; // // m_changeSmallFontButton // this.m_changeSmallFontButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.m_changeSmallFontButton.Location = new System.Drawing.Point(262, 42); this.m_changeSmallFontButton.Name = "m_changeSmallFontButton"; this.m_changeSmallFontButton.Size = new System.Drawing.Size(75, 23); this.m_changeSmallFontButton.TabIndex = 7; this.m_changeSmallFontButton.Text = "Cha&nge..."; this.m_changeSmallFontButton.UseVisualStyleBackColor = true; this.m_changeSmallFontButton.Click += new System.EventHandler(this.ChangeSmallFontButton_Click); // // m_smallFontNameTextBox // this.m_smallFontNameTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_smallFontNameTextBox.BackColor = System.Drawing.SystemColors.Window; this.m_smallFontNameTextBox.Location = new System.Drawing.Point(82, 44); this.m_smallFontNameTextBox.Name = "m_smallFontNameTextBox"; this.m_smallFontNameTextBox.ReadOnly = true; this.m_smallFontNameTextBox.Size = new System.Drawing.Size(137, 21); this.m_smallFontNameTextBox.TabIndex = 5; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(41, 22); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(34, 13); this.label11.TabIndex = 0; this.label11.Text = "&Room"; // // m_largeFontSizeTextBox // this.m_largeFontSizeTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.m_largeFontSizeTextBox.BackColor = System.Drawing.SystemColors.Window; this.m_largeFontSizeTextBox.Location = new System.Drawing.Point(225, 19); this.m_largeFontSizeTextBox.Name = "m_largeFontSizeTextBox"; this.m_largeFontSizeTextBox.ReadOnly = true; this.m_largeFontSizeTextBox.Size = new System.Drawing.Size(31, 21); this.m_largeFontSizeTextBox.TabIndex = 2; // // m_changeLargeFontButton // this.m_changeLargeFontButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.m_changeLargeFontButton.Location = new System.Drawing.Point(262, 16); this.m_changeLargeFontButton.Name = "m_changeLargeFontButton"; this.m_changeLargeFontButton.Size = new System.Drawing.Size(75, 23); this.m_changeLargeFontButton.TabIndex = 3; this.m_changeLargeFontButton.Text = "Ch&ange..."; this.m_changeLargeFontButton.UseVisualStyleBackColor = true; this.m_changeLargeFontButton.Click += new System.EventHandler(this.ChangeLargeFontButton_Click); // // m_largeFontNameTextBox // this.m_largeFontNameTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_largeFontNameTextBox.BackColor = System.Drawing.SystemColors.Window; this.m_largeFontNameTextBox.Location = new System.Drawing.Point(82, 18); this.m_largeFontNameTextBox.Name = "m_largeFontNameTextBox"; this.m_largeFontNameTextBox.ReadOnly = true; this.m_largeFontNameTextBox.Size = new System.Drawing.Size(137, 21); this.m_largeFontNameTextBox.TabIndex = 1; // // tabPage2 // this.tabPage2.Controls.Add(this.m_linesGroupBox); this.tabPage2.Controls.Add(this.m_gridGroupBox); this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(3); this.tabPage2.Size = new System.Drawing.Size(355, 291); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Lines and Grid"; this.tabPage2.UseVisualStyleBackColor = true; // // tabRegions // this.tabRegions.Controls.Add(this.label19); this.tabRegions.Controls.Add(this.btnDeleteRegion); this.tabRegions.Controls.Add(this.btnAddRegion); this.tabRegions.Controls.Add(this.btnChange); this.tabRegions.Controls.Add(this.m_RegionListing); this.tabRegions.Location = new System.Drawing.Point(4, 22); this.tabRegions.Name = "tabRegions"; this.tabRegions.Padding = new System.Windows.Forms.Padding(3); this.tabRegions.Size = new System.Drawing.Size(355, 291); this.tabRegions.TabIndex = 4; this.tabRegions.Text = "Regions"; this.tabRegions.UseVisualStyleBackColor = true; // // label19 // this.label19.AutoSize = true; this.label19.ForeColor = System.Drawing.Color.Blue; this.label19.Location = new System.Drawing.Point(7, 147); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(151, 13); this.label19.TabIndex = 5; this.label19.Text = "Note: F2 to edit Region name"; // // btnDeleteRegion // this.btnDeleteRegion.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnDeleteRegion.Location = new System.Drawing.Point(257, 117); this.btnDeleteRegion.Name = "btnDeleteRegion"; this.btnDeleteRegion.Size = new System.Drawing.Size(92, 23); this.btnDeleteRegion.TabIndex = 4; this.btnDeleteRegion.Text = "&Delete Region"; this.btnDeleteRegion.UseVisualStyleBackColor = true; this.btnDeleteRegion.Click += new System.EventHandler(this.btnDeleteRegion_Click); // // btnAddRegion // this.btnAddRegion.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnAddRegion.Location = new System.Drawing.Point(257, 6); this.btnAddRegion.Name = "btnAddRegion"; this.btnAddRegion.Size = new System.Drawing.Size(92, 23); this.btnAddRegion.TabIndex = 2; this.btnAddRegion.Text = "&Add Region"; this.btnAddRegion.UseVisualStyleBackColor = true; this.btnAddRegion.Click += new System.EventHandler(this.btnAddRegion_Click); // // btnChange // this.btnChange.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnChange.Location = new System.Drawing.Point(257, 34); this.btnChange.Name = "btnChange"; this.btnChange.Size = new System.Drawing.Size(92, 23); this.btnChange.TabIndex = 3; this.btnChange.Text = "C&hange..."; this.btnChange.UseVisualStyleBackColor = true; this.btnChange.Click += new System.EventHandler(this.btnChange_Click); // // m_RegionListing // this.m_RegionListing.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_RegionListing.FormattingEnabled = true; this.m_RegionListing.HorizontalScrollbar = true; this.m_RegionListing.Location = new System.Drawing.Point(6, 6); this.m_RegionListing.Name = "m_RegionListing"; this.m_RegionListing.Size = new System.Drawing.Size(245, 134); this.m_RegionListing.TabIndex = 1; this.m_RegionListing.SelectedIndexChanged += new System.EventHandler(this.m_RegionListing_SelectedIndexChanged); this.m_RegionListing.DoubleClick += new System.EventHandler(this.onChangeRegionColor); this.m_RegionListing.KeyDown += new System.Windows.Forms.KeyEventHandler(this.m_RegionListing_KeyDown); this.m_RegionListing.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.m_RegionListing_KeyPress); this.m_RegionListing.KeyUp += new System.Windows.Forms.KeyEventHandler(this.m_RegionListing_KeyUp); // // tabPage3 // this.tabPage3.Controls.Add(this.groupBox2); this.tabPage3.Controls.Add(this.groupBox1); this.tabPage3.Location = new System.Drawing.Point(4, 22); this.tabPage3.Name = "tabPage3"; this.tabPage3.Size = new System.Drawing.Size(355, 291); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "Other"; this.tabPage3.UseVisualStyleBackColor = true; // // groupBox2 // this.groupBox2.Controls.Add(this.label7); this.groupBox2.Controls.Add(this.label3); this.groupBox2.Controls.Add(this.m_snapToElementDistanceUpDown); this.groupBox2.Controls.Add(this.label2); this.groupBox2.Controls.Add(this.m_handleSizeUpDown); this.groupBox2.Location = new System.Drawing.Point(5, 84); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(343, 101); this.groupBox2.TabIndex = 1; this.groupBox2.TabStop = false; this.groupBox2.Text = "&Advanced"; // // label7 // this.label7.AutoSize = true; this.label7.ForeColor = System.Drawing.SystemColors.GrayText; this.label7.Location = new System.Drawing.Point(7, 20); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(320, 13); this.label7.TabIndex = 0; this.label7.Text = "These settings affect the ease with which you can click and drag."; // // label3 // this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(106, 73); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(129, 13); this.label3.TabIndex = 3; this.label3.Text = "&Snap to Element Distance"; // // m_snapToElementDistanceUpDown // this.m_snapToElementDistanceUpDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.m_snapToElementDistanceUpDown.DecimalPlaces = 1; this.m_snapToElementDistanceUpDown.Location = new System.Drawing.Point(242, 71); this.m_snapToElementDistanceUpDown.Maximum = new decimal(new int[] { 4096, 0, 0, 0}); this.m_snapToElementDistanceUpDown.Name = "m_snapToElementDistanceUpDown"; this.m_snapToElementDistanceUpDown.Size = new System.Drawing.Size(95, 21); this.m_snapToElementDistanceUpDown.TabIndex = 4; this.m_snapToElementDistanceUpDown.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.m_snapToElementDistanceUpDown.Value = new decimal(new int[] { 1, 0, 0, 0}); // // label2 // this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(112, 47); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(123, 13); this.label2.TabIndex = 1; this.label2.Text = "Resize/Drag &Handle Size"; // // m_handleSizeUpDown // this.m_handleSizeUpDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.m_handleSizeUpDown.DecimalPlaces = 1; this.m_handleSizeUpDown.Location = new System.Drawing.Point(242, 45); this.m_handleSizeUpDown.Maximum = new decimal(new int[] { 4096, 0, 0, 0}); this.m_handleSizeUpDown.Name = "m_handleSizeUpDown"; this.m_handleSizeUpDown.Size = new System.Drawing.Size(95, 21); this.m_handleSizeUpDown.TabIndex = 2; this.m_handleSizeUpDown.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.m_handleSizeUpDown.Value = new decimal(new int[] { 1, 0, 0, 0}); // // propertySettings1 // this.propertySettings1.DisplayName = "Region1"; this.propertySettings1.PropertyName = ""; // // superTooltip1 // this.superTooltip1.LicenseKey = "F962CEC7-CD8F-4911-A9E9-CAB39962FC1F"; // // SettingsDialog // this.AcceptButton = this.m_okButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.m_cancelButton; this.ClientSize = new System.Drawing.Size(383, 374); this.Controls.Add(this.panel1); this.Controls.Add(this.tabControl1); this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "SettingsDialog"; this.Padding = new System.Windows.Forms.Padding(10); this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Map Settings"; ((System.ComponentModel.ISupportInitialize)(this.m_lineWidthUpDown)).EndInit(); this.m_linesGroupBox.ResumeLayout(false); this.m_linesGroupBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.m_preferredDistanceBetweenRoomsUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.m_textOffsetFromLineUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.m_connectionStalkLengthUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.m_arrowSizeUpDown)).EndInit(); this.m_gridGroupBox.ResumeLayout(false); this.m_gridGroupBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.m_gridSizeUpDown)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.m_objectListOffsetFromRoomNumericUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.m_darknessStripeSizeNumericUpDown)).EndInit(); this.panel1.ResumeLayout(false); this.tabControl1.ResumeLayout(false); this.tabPage4.ResumeLayout(false); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.tabPage1.ResumeLayout(false); this.m_colorsGroupBox.ResumeLayout(false); this.m_fontsGroupBox.ResumeLayout(false); this.m_fontsGroupBox.PerformLayout(); this.tabPage2.ResumeLayout(false); this.tabRegions.ResumeLayout(false); this.tabRegions.PerformLayout(); this.tabPage3.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.m_snapToElementDistanceUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.m_handleSizeUpDown)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button m_okButton; private System.Windows.Forms.Button m_cancelButton; private System.Windows.Forms.CheckBox m_handDrawnCheckBox; private System.Windows.Forms.NumericUpDown m_lineWidthUpDown; private System.Windows.Forms.Label label5; private System.Windows.Forms.GroupBox m_linesGroupBox; private System.Windows.Forms.GroupBox m_gridGroupBox; private System.Windows.Forms.CheckBox m_snapToGridCheckBox; private System.Windows.Forms.Label label6; private System.Windows.Forms.NumericUpDown m_gridSizeUpDown; private System.Windows.Forms.CheckBox m_showGridCheckBox; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label13; private System.Windows.Forms.NumericUpDown m_darknessStripeSizeNumericUpDown; private System.Windows.Forms.Label label34; private System.Windows.Forms.NumericUpDown m_objectListOffsetFromRoomNumericUpDown; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.GroupBox m_colorsGroupBox; private System.Windows.Forms.ListBox m_colorListBox; private System.Windows.Forms.Button m_changeColorButton; private System.Windows.Forms.GroupBox m_fontsGroupBox; private System.Windows.Forms.Label label12; private System.Windows.Forms.TextBox m_smallFontSizeTextBox; private System.Windows.Forms.Button m_changeSmallFontButton; private System.Windows.Forms.TextBox m_smallFontNameTextBox; private System.Windows.Forms.Label label11; private System.Windows.Forms.TextBox m_largeFontSizeTextBox; private System.Windows.Forms.Button m_changeLargeFontButton; private System.Windows.Forms.TextBox m_largeFontNameTextBox; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.TabPage tabPage3; private System.Windows.Forms.Label label4; private System.Windows.Forms.NumericUpDown m_arrowSizeUpDown; private System.Windows.Forms.Label label1; private System.Windows.Forms.NumericUpDown m_connectionStalkLengthUpDown; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label3; private System.Windows.Forms.NumericUpDown m_snapToElementDistanceUpDown; private System.Windows.Forms.Label label2; private System.Windows.Forms.NumericUpDown m_handleSizeUpDown; private System.Windows.Forms.Label label8; private System.Windows.Forms.NumericUpDown m_textOffsetFromLineUpDown; private System.Windows.Forms.Label label9; private System.Windows.Forms.TextBox m_lineFontSizeTextBox; private System.Windows.Forms.Button m_changeLineFontButton; private System.Windows.Forms.TextBox m_lineFontNameTextBox; private System.Windows.Forms.TabPage tabPage4; private System.Windows.Forms.Label label16; private System.Windows.Forms.TextBox m_descriptionTextBox; private System.Windows.Forms.Label label15; private System.Windows.Forms.Label label14; private System.Windows.Forms.TextBox m_authorTextBox; private System.Windows.Forms.Label label10; private System.Windows.Forms.TextBox m_titleTextBox; private System.Windows.Forms.TextBox m_historyTextBox; private System.Windows.Forms.Label label17; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.CheckBox m_showOriginCheckBox; private System.Windows.Forms.Label label18; private System.Windows.Forms.NumericUpDown m_preferredDistanceBetweenRoomsUpDown; private System.Windows.Forms.TabPage tabRegions; private System.Windows.Forms.ListBox m_RegionListing; private System.Windows.Forms.Button btnAddRegion; private System.Windows.Forms.Button btnChange; private System.Windows.Forms.Button btnDeleteRegion; private System.Windows.Forms.Label label19; private DevComponents.DotNetBar.PropertySettings propertySettings1; private DevComponents.DotNetBar.SuperTooltip superTooltip1; } }
/** * 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.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; namespace Thrift.Transport { /// <summary> /// SSL Server Socket Wrapper Class /// </summary> public class TTLSServerSocket : TServerTransport { /// <summary> /// Underlying tcp server /// </summary> private TcpListener server = null; /// <summary> /// The port where the socket listen /// </summary> private int port = 0; /// <summary> /// Timeout for the created server socket /// </summary> private readonly int clientTimeout; /// <summary> /// Whether or not to wrap new TSocket connections in buffers /// </summary> private bool useBufferedSockets = false; /// <summary> /// The servercertificate with the private- and public-key /// </summary> private X509Certificate serverCertificate; /// <summary> /// The function to validate the client certificate. /// </summary> private RemoteCertificateValidationCallback clientCertValidator; /// <summary> /// The function to determine which certificate to use. /// </summary> private LocalCertificateSelectionCallback localCertificateSelectionCallback; /// <summary> /// The SslProtocols value that represents the protocol used for authentication. /// </summary> private readonly SslProtocols sslProtocols; /// <summary> /// Initializes a new instance of the <see cref="TTLSServerSocket" /> class. /// </summary> /// <param name="port">The port where the server runs.</param> /// <param name="certificate">The certificate object.</param> public TTLSServerSocket(int port, X509Certificate2 certificate) : this(port, 0, certificate) { } /// <summary> /// Initializes a new instance of the <see cref="TTLSServerSocket" /> class. /// </summary> /// <param name="port">The port where the server runs.</param> /// <param name="clientTimeout">Send/receive timeout.</param> /// <param name="certificate">The certificate object.</param> public TTLSServerSocket(int port, int clientTimeout, X509Certificate2 certificate) : this(port, clientTimeout, false, certificate) { } /// <summary> /// Initializes a new instance of the <see cref="TTLSServerSocket" /> class. /// </summary> /// <param name="port">The port where the server runs.</param> /// <param name="clientTimeout">Send/receive timeout.</param> /// <param name="useBufferedSockets">If set to <c>true</c> [use buffered sockets].</param> /// <param name="certificate">The certificate object.</param> /// <param name="clientCertValidator">The certificate validator.</param> /// <param name="localCertificateSelectionCallback">The callback to select which certificate to use.</param> /// <param name="sslProtocols">The SslProtocols value that represents the protocol used for authentication.</param> public TTLSServerSocket( int port, int clientTimeout, bool useBufferedSockets, X509Certificate2 certificate, RemoteCertificateValidationCallback clientCertValidator = null, LocalCertificateSelectionCallback localCertificateSelectionCallback = null, // TODO: Enable Tls11 and Tls12 (TLS 1.1 and 1.2) by default once we start using .NET 4.5+. SslProtocols sslProtocols = SslProtocols.Tls) { if (!certificate.HasPrivateKey) { throw new TTransportException(TTransportException.ExceptionType.Unknown, "Your server-certificate needs to have a private key"); } this.port = port; this.clientTimeout = clientTimeout; this.serverCertificate = certificate; this.useBufferedSockets = useBufferedSockets; this.clientCertValidator = clientCertValidator; this.localCertificateSelectionCallback = localCertificateSelectionCallback; this.sslProtocols = sslProtocols; try { // Create server socket this.server = TSocketVersionizer.CreateTcpListener(this.port); this.server.Server.NoDelay = true; } catch (Exception) { server = null; throw new TTransportException("Could not create ServerSocket on port " + this.port + "."); } } /// <summary> /// Starts the server. /// </summary> public override void Listen() { // Make sure accept is not blocking if (this.server != null) { try { this.server.Start(); } catch (SocketException sx) { throw new TTransportException("Could not accept on listening socket: " + sx.Message); } } } /// <summary> /// Callback for Accept Implementation /// </summary> /// <returns> /// TTransport-object. /// </returns> protected override TTransport AcceptImpl() { if (this.server == null) { throw new TTransportException(TTransportException.ExceptionType.NotOpen, "No underlying server socket."); } try { TcpClient client = this.server.AcceptTcpClient(); client.SendTimeout = client.ReceiveTimeout = this.clientTimeout; //wrap the client in an SSL Socket passing in the SSL cert TTLSSocket socket = new TTLSSocket( client, this.serverCertificate, true, this.clientCertValidator, this.localCertificateSelectionCallback, this.sslProtocols); socket.setupTLS(); if (useBufferedSockets) { TBufferedTransport trans = new TBufferedTransport(socket); return trans; } else { return socket; } } catch (Exception ex) { throw new TTransportException(ex.ToString()); } } /// <summary> /// Stops the Server /// </summary> public override void Close() { if (this.server != null) { try { this.server.Stop(); } catch (Exception ex) { throw new TTransportException("WARNING: Could not close server socket: " + ex); } this.server = null; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Client { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Client; /// <summary> /// Handles client features based on protocol version and feature flags. /// </summary> internal class ClientFeatures { /** Bit mask of all features. */ public static readonly byte[] AllFeatures = GetAllFeatures(); /** Current features. */ public static readonly ClientFeatures CurrentFeatures = new ClientFeatures(ClientSocket.CurrentProtocolVersion, new BitArray(AllFeatures)); /** */ private static readonly Dictionary<ClientOp, ClientProtocolVersion> OpVersion = new Dictionary<ClientOp, ClientProtocolVersion> { {ClientOp.CachePartitions, new ClientProtocolVersion(1, 4, 0)}, {ClientOp.ClusterIsActive, new ClientProtocolVersion(1, 5, 0)}, {ClientOp.ClusterChangeState, new ClientProtocolVersion(1, 5, 0)}, {ClientOp.ClusterChangeWalState, new ClientProtocolVersion(1, 5, 0)}, {ClientOp.ClusterGetWalState, new ClientProtocolVersion(1, 5, 0)}, {ClientOp.TxStart, new ClientProtocolVersion(1, 5, 0)}, {ClientOp.TxEnd, new ClientProtocolVersion(1, 5, 0)}, }; /** */ private static readonly Dictionary<ClientOp, ClientBitmaskFeature> OpFeature = new Dictionary<ClientOp, ClientBitmaskFeature> { {ClientOp.ClusterGroupGetNodesEndpoints, ClientBitmaskFeature.ClusterGroupGetNodesEndpoints}, {ClientOp.ComputeTaskExecute, ClientBitmaskFeature.ExecuteTaskByName}, {ClientOp.ClusterGroupGetNodeIds, ClientBitmaskFeature.ClusterGroups}, {ClientOp.ClusterGroupGetNodesInfo, ClientBitmaskFeature.ClusterGroups} }; /** */ private readonly ClientProtocolVersion _protocolVersion; /** */ private readonly BitArray _features; /// <summary> /// Initializes a new instance of <see cref="ClientFeatures"/>. /// </summary> public ClientFeatures(ClientProtocolVersion protocolVersion, BitArray features) { _protocolVersion = protocolVersion; _features = features; } /// <summary> /// Returns a value indicating whether specified feature is supported. /// </summary> public bool HasFeature(ClientBitmaskFeature feature) { var index = (int) feature; return _features != null && index >= 0 && index < _features.Count && _features.Get(index); } /// <summary> /// Returns a value indicating whether specified operation is supported. /// </summary> public bool HasOp(ClientOp op) { return ValidateOp(op, false); } /// <summary> /// Checks whether WithExpiryPolicy request flag is supported. Throws an exception when not supported. /// </summary> public void ValidateWithExpiryPolicyFlag() { var requiredVersion = ClientSocket.Ver150; if (_protocolVersion < requiredVersion) { ThrowMinimumVersionException("WithExpiryPolicy", requiredVersion); } } /// <summary> /// Returns a value indicating whether <see cref="QueryField.Precision"/> and <see cref="QueryField.Scale"/> /// are supported. /// </summary> public bool HasQueryFieldPrecisionAndScale() { return _protocolVersion >= ClientSocket.Ver120; } /// <summary> /// Returns a value indicating whether <see cref="CacheConfiguration.ExpiryPolicyFactory"/> is supported. /// </summary> public bool HasCacheConfigurationExpiryPolicyFactory() { return _protocolVersion >= ClientSocket.Ver160; } /// <summary> /// Gets minimum protocol version that is required to perform specified operation. /// </summary> /// <param name="op">Operation.</param> /// <returns>Minimum protocol version.</returns> public static ClientProtocolVersion GetMinVersion(ClientOp op) { ClientProtocolVersion minVersion; return OpVersion.TryGetValue(op, out minVersion) ? minVersion : ClientSocket.Ver100; } /// <summary> /// Validates specified op code against current protocol version and features. /// </summary> /// <param name="operation">Operation.</param> public void ValidateOp(ClientOp operation) { ValidateOp(operation, true); } /// <summary> /// Validates specified op code against current protocol version and features. /// </summary> private bool ValidateOp(ClientOp operation, bool shouldThrow) { var requiredProtocolVersion = GetMinVersion(operation); if (_protocolVersion < requiredProtocolVersion) { if (shouldThrow) { ThrowMinimumVersionException(operation, requiredProtocolVersion); } return false; } var requiredFeature = GetFeature(operation); if (requiredFeature != null && (_features == null || !_features.Get((int) requiredFeature.Value))) { if (shouldThrow) { throw new IgniteClientException(string.Format( "Operation {0} is not supported by the server. Feature {1} is missing.", operation, requiredFeature.Value)); } return false; } return true; } /// <summary> /// Throws minimum version exception. /// </summary> private void ThrowMinimumVersionException(object operation, ClientProtocolVersion requiredProtocolVersion) { var message = string.Format("Operation {0} is not supported by protocol version {1}. " + "Minimum protocol version required is {2}.", operation, _protocolVersion, requiredProtocolVersion); throw new IgniteClientException(message); } /// <summary> /// Gets <see cref="ClientBitmaskFeature"/> that is required to perform specified operation. /// </summary> /// <param name="op">Operation.</param> /// <returns>Required feature flag, or null.</returns> private static ClientBitmaskFeature? GetFeature(ClientOp op) { ClientBitmaskFeature feature; return OpFeature.TryGetValue(op, out feature) ? feature : (ClientBitmaskFeature?) null; } /// <summary> /// Gets a bit array with all supported features. /// </summary> private static byte[] GetAllFeatures() { var values = Enum.GetValues(typeof(ClientBitmaskFeature)) .Cast<int>() .ToArray(); var max = values.Max(); var bits = new BitArray(max + 1); foreach (var feature in values) { bits.Set(feature, true); } var bytes = new byte[1 + max / 8]; bits.CopyTo(bytes, 0); return bytes; } } }
#region Copyright (c) 2006 Ian Davis and James Carlyle /*------------------------------------------------------------------------------ COPYRIGHT AND PERMISSION NOTICE Copyright (c) 2006 Ian Davis and James Carlyle Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------*/ #endregion namespace SemPlan.Spiral.Tests.MySql { using NUnit.Framework; using SemPlan.Spiral.Core; using SemPlan.Spiral.Expressions; using SemPlan.Spiral.MySql; using SemPlan.Spiral.Utility; using System; using System.Collections; using SemPlan.Spiral.Tests.Core; /// <summary> /// Programmer tests for DatabaseQuerySolver class /// </summary> /// <remarks> /// $Id: QuerySqlMapperTest.cs,v 1.2 2006/03/08 22:42:36 ian Exp $ ///</remarks> [TestFixture] public class QuerySqlMapperTest { [Test] public void SingleStatementSingleVariableAsObject() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new UriRef("ex:s"), new UriRef("ex:p"), new Variable("v") ) ); Query query = builder.GetQuery(); QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT rn_v.resourceHash rh_v, rn_v.nodeHash nh_v, rn_v.nodeType nt_v, COALESCE(u_v.uri, pl_v.value, l_v.value) val_v, COALESCE(tl_v.value, t_v.value) sub_v " + "FROM Statements s1 JOIN ResourceNodes rn_v ON rn_v.resourceHash=s1.objectHash AND rn_v.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_v ON rn_v.nodeHash=u_v.hash AND rn_v.nodeType='u' " + "LEFT OUTER JOIN PlainLiterals pl_v ON rn_v.nodeHash=pl_v.hash AND rn_v.nodeType='p' " + "LEFT OUTER JOIN Languages l_v ON pl_v.languageHash=l_v.hash " + "LEFT OUTER JOIN TypedLiterals tl_v ON rn_v.nodehash=tl_v.hash AND rn_v.nodeType='t' " + "LEFT OUTER JOIN DataTypes t_v ON tl_v.datatypeHash=t_v.hash " + "WHERE s1.subjectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:s") ).GetHashCode() + " AND s1.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode(); Assert.AreEqual( expected, mapper.Sql ); } [Test] public void SingleStatementSingleVariableAsSubject() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new Variable("v"), new UriRef("ex:p"), new UriRef("ex:o") ) ); Query query = builder.GetQuery(); QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT rn_v.resourceHash rh_v, rn_v.nodeHash nh_v, rn_v.nodeType nt_v, u_v.uri val_v, NULL sub_v " + "FROM Statements s1 JOIN ResourceNodes rn_v ON rn_v.resourceHash=s1.subjectHash AND rn_v.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_v ON rn_v.nodeHash=u_v.hash AND rn_v.nodeType='u' " + "WHERE s1.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p") ).GetHashCode() + " AND s1.objectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:o") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode(); Assert.AreEqual( expected, mapper.Sql ); } [Test] public void SingleStatementSingleVariableAsPredicate() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new UriRef("ex:s"), new Variable("v"), new UriRef("ex:o") ) ); Query query = builder.GetQuery(); QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT rn_v.resourceHash rh_v, rn_v.nodeHash nh_v, rn_v.nodeType nt_v, u_v.uri val_v, NULL sub_v " + "FROM Statements s1 JOIN ResourceNodes rn_v ON rn_v.resourceHash=s1.predicateHash AND rn_v.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_v ON rn_v.nodeHash=u_v.hash AND rn_v.nodeType='u' " + "WHERE s1.subjectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:s") ).GetHashCode() + " AND s1.objectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:o") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode(); Assert.AreEqual( expected, mapper.Sql ); } [Test] public void SingleStatementSingleVariableWithArbitraryName() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new UriRef("ex:s"), new UriRef("ex:p"), new Variable("hula") ) ); Query query = builder.GetQuery(); QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT rn_hula.resourceHash rh_hula, rn_hula.nodeHash nh_hula, rn_hula.nodeType nt_hula, COALESCE(u_hula.uri, pl_hula.value, l_hula.value) val_hula, COALESCE(tl_hula.value, t_hula.value) sub_hula " + "FROM Statements s1 JOIN ResourceNodes rn_hula ON rn_hula.resourceHash=s1.objectHash AND rn_hula.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_hula ON rn_hula.nodeHash=u_hula.hash AND rn_hula.nodeType='u' " + "LEFT OUTER JOIN PlainLiterals pl_hula ON rn_hula.nodeHash=pl_hula.hash AND rn_hula.nodeType='p' " + "LEFT OUTER JOIN Languages l_hula ON pl_hula.languageHash=l_hula.hash " + "LEFT OUTER JOIN TypedLiterals tl_hula ON rn_hula.nodehash=tl_hula.hash AND rn_hula.nodeType='t' " + "LEFT OUTER JOIN DataTypes t_hula ON tl_hula.datatypeHash=t_hula.hash " + "WHERE s1.subjectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:s") ).GetHashCode() + " AND s1.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode(); Assert.AreEqual( expected, mapper.Sql ); } [Test] public void SingleStatementTwoVariables() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new Variable("s"), new UriRef("ex:p"), new Variable("o") ) ); Query query = builder.GetQuery(); QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT rn_s.resourceHash rh_s, rn_s.nodeHash nh_s, rn_s.nodeType nt_s, u_s.uri val_s, NULL sub_s, rn_o.resourceHash rh_o, rn_o.nodeHash nh_o, rn_o.nodeType nt_o, COALESCE(u_o.uri, pl_o.value, l_o.value) val_o, COALESCE(tl_o.value, t_o.value) sub_o " + "FROM Statements s1 JOIN ResourceNodes rn_s ON rn_s.resourceHash=s1.subjectHash AND rn_s.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_s ON rn_s.nodeHash=u_s.hash AND rn_s.nodeType='u' " + "JOIN ResourceNodes rn_o ON rn_o.resourceHash=s1.objectHash AND rn_o.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_o ON rn_o.nodeHash=u_o.hash AND rn_o.nodeType='u' " + "LEFT OUTER JOIN PlainLiterals pl_o ON rn_o.nodeHash=pl_o.hash AND rn_o.nodeType='p' " + "LEFT OUTER JOIN Languages l_o ON pl_o.languageHash=l_o.hash " + "LEFT OUTER JOIN TypedLiterals tl_o ON rn_o.nodehash=tl_o.hash AND rn_o.nodeType='t' " + "LEFT OUTER JOIN DataTypes t_o ON tl_o.datatypeHash=t_o.hash " + "WHERE s1.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode(); Assert.AreEqual( expected, mapper.Sql ); } [Test] public void TwoStatementsSingleVariableAsSubject() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p2"), new UriRef("ex:o") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new Variable("v"), new UriRef("ex:p"), new UriRef("ex:o") ) ); builder.AddPattern( new Pattern( new Variable("v"), new UriRef("ex:p2"), new UriRef("ex:o") ) ); Query query = builder.GetQuery(); QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT rn_v.resourceHash rh_v, rn_v.nodeHash nh_v, rn_v.nodeType nt_v, u_v.uri val_v, NULL sub_v " + "FROM Statements s1 " + "JOIN Statements s2 ON s2.subjectHash=s1.subjectHash" + " AND s2.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p2") ).GetHashCode() + " AND s2.objectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:o") ).GetHashCode() + " AND s2.graphId=" + statements.GetHashCode() + " JOIN ResourceNodes rn_v ON rn_v.resourceHash=s1.subjectHash AND rn_v.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_v ON rn_v.nodeHash=u_v.hash AND rn_v.nodeType='u' " + "WHERE s1.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p") ).GetHashCode() + " AND s1.objectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:o") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode(); Assert.AreEqual( expected, mapper.Sql ); } [Test] public void TwoStatementsSingleVariableAsPredicate() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p2"), new UriRef("ex:o") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new Variable("v"), new UriRef("ex:p"), new UriRef("ex:o") ) ); builder.AddPattern( new Pattern( new UriRef("ex:s"), new Variable("v"), new UriRef("ex:o") ) ); Query query = builder.GetQuery(); QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT rn_v.resourceHash rh_v, rn_v.nodeHash nh_v, rn_v.nodeType nt_v, u_v.uri val_v, NULL sub_v " + "FROM Statements s1 " + "JOIN Statements s2" + " ON s2.subjectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:s") ).GetHashCode() + " AND s2.predicateHash=s1.subjectHash" + " AND s2.objectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:o") ).GetHashCode() + " AND s2.graphId=" + statements.GetHashCode() + " JOIN ResourceNodes rn_v ON rn_v.resourceHash=s1.subjectHash AND rn_v.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_v ON rn_v.nodeHash=u_v.hash AND rn_v.nodeType='u' " + "WHERE s1.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p") ).GetHashCode() + " AND s1.objectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:o") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode(); Assert.AreEqual( expected, mapper.Sql ); } [Test] public void TwoStatementsSingleVariableAsObject() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p2"), new UriRef("ex:o") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new Variable("v"), new UriRef("ex:p"), new UriRef("ex:o") ) ); builder.AddPattern( new Pattern( new UriRef("ex:s"), new UriRef("ex:p2"), new Variable("v") ) ); Query query = builder.GetQuery(); QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT rn_v.resourceHash rh_v, rn_v.nodeHash nh_v, rn_v.nodeType nt_v, u_v.uri val_v, NULL sub_v " + "FROM Statements s1 " + "JOIN Statements s2" + " ON s2.subjectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:s") ).GetHashCode() + " AND s2.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p2") ).GetHashCode() + " AND s2.objectHash=s1.subjectHash" + " AND s2.graphId=" + statements.GetHashCode() + " JOIN ResourceNodes rn_v ON rn_v.resourceHash=s1.subjectHash AND rn_v.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_v ON rn_v.nodeHash=u_v.hash AND rn_v.nodeType='u' " + "WHERE s1.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p") ).GetHashCode() + " AND s1.objectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:o") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode(); Assert.AreEqual( expected, mapper.Sql ); } [Test] public void Distinct() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new UriRef("ex:s"), new UriRef("ex:p"), new Variable("v") ) ); Query query = builder.GetQuery(); query.IsDistinct = true; QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT DISTINCT rn_v.resourceHash rh_v, rn_v.nodeHash nh_v, rn_v.nodeType nt_v, COALESCE(u_v.uri, pl_v.value, l_v.value) val_v, COALESCE(tl_v.value, t_v.value) sub_v " + "FROM Statements s1 JOIN ResourceNodes rn_v ON rn_v.resourceHash=s1.objectHash AND rn_v.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_v ON rn_v.nodeHash=u_v.hash AND rn_v.nodeType='u' " + "LEFT OUTER JOIN PlainLiterals pl_v ON rn_v.nodeHash=pl_v.hash AND rn_v.nodeType='p' " + "LEFT OUTER JOIN Languages l_v ON pl_v.languageHash=l_v.hash " + "LEFT OUTER JOIN TypedLiterals tl_v ON rn_v.nodehash=tl_v.hash AND rn_v.nodeType='t' " + "LEFT OUTER JOIN DataTypes t_v ON tl_v.datatypeHash=t_v.hash " + "WHERE s1.subjectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:s") ).GetHashCode() + " AND s1.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode(); Assert.AreEqual( expected, mapper.Sql ); } [Test] public void NoPatterns() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); Query query = builder.GetQuery(); QuerySqlMapper mapper = new QuerySqlMapper(query, statements); Assert.AreEqual( false, mapper.IsFeasible); } [Test] public void OrderBySimpleVariableExpressionAscending() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new UriRef("ex:s"), new UriRef("ex:p"), new Variable("v") ) ); Query query = builder.GetQuery(); query.OrderBy = new VariableExpression( new Variable("v" ) ); QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT rn_v.resourceHash rh_v, rn_v.nodeHash nh_v, rn_v.nodeType nt_v, COALESCE(u_v.uri, pl_v.value, l_v.value) val_v, COALESCE(tl_v.value, t_v.value) sub_v " + "FROM Statements s1 JOIN ResourceNodes rn_v ON rn_v.resourceHash=s1.objectHash AND rn_v.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_v ON rn_v.nodeHash=u_v.hash AND rn_v.nodeType='u' " + "LEFT OUTER JOIN PlainLiterals pl_v ON rn_v.nodeHash=pl_v.hash AND rn_v.nodeType='p' " + "LEFT OUTER JOIN Languages l_v ON pl_v.languageHash=l_v.hash " + "LEFT OUTER JOIN TypedLiterals tl_v ON rn_v.nodehash=tl_v.hash AND rn_v.nodeType='t' " + "LEFT OUTER JOIN DataTypes t_v ON tl_v.datatypeHash=t_v.hash " + "WHERE s1.subjectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:s") ).GetHashCode() + " AND s1.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode() + " ORDER BY val_v"; Assert.AreEqual( expected, mapper.Sql ); } [Test] public void OrderBySimpleVariableExpressionDescending() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new UriRef("ex:s"), new UriRef("ex:p"), new Variable("v") ) ); Query query = builder.GetQuery(); query.OrderBy = new VariableExpression( new Variable("v" ) ); query.OrderDirection = Query.SortOrder.Descending; QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT rn_v.resourceHash rh_v, rn_v.nodeHash nh_v, rn_v.nodeType nt_v, COALESCE(u_v.uri, pl_v.value, l_v.value) val_v, COALESCE(tl_v.value, t_v.value) sub_v " + "FROM Statements s1 JOIN ResourceNodes rn_v ON rn_v.resourceHash=s1.objectHash AND rn_v.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_v ON rn_v.nodeHash=u_v.hash AND rn_v.nodeType='u' " + "LEFT OUTER JOIN PlainLiterals pl_v ON rn_v.nodeHash=pl_v.hash AND rn_v.nodeType='p' " + "LEFT OUTER JOIN Languages l_v ON pl_v.languageHash=l_v.hash " + "LEFT OUTER JOIN TypedLiterals tl_v ON rn_v.nodehash=tl_v.hash AND rn_v.nodeType='t' " + "LEFT OUTER JOIN DataTypes t_v ON tl_v.datatypeHash=t_v.hash " + "WHERE s1.subjectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:s") ).GetHashCode() + " AND s1.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode() + " ORDER BY val_v DESC"; Assert.AreEqual( expected, mapper.Sql ); } [Test] public void SingleStatementPlusOptionalStatementSharedSubject() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p2"), new UriRef("ex:o2") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new Variable("v"), new UriRef("ex:p"), new UriRef("ex:o") ) ); builder.AddOptional( new Pattern( new Variable("v"), new UriRef("ex:p2"), new UriRef("ex:o2") ) ); Query query = builder.GetQuery(); QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT rn_v.resourceHash rh_v, rn_v.nodeHash nh_v, rn_v.nodeType nt_v, u_v.uri val_v, NULL sub_v " + "FROM Statements s1 " + "LEFT OUTER JOIN Statements s2" + " ON s2.subjectHash=s1.subjectHash" + " AND s2.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p2") ).GetHashCode() + " AND s2.objectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:o2") ).GetHashCode() + " AND s2.graphId=" + statements.GetHashCode() + " JOIN ResourceNodes rn_v ON rn_v.resourceHash=s1.subjectHash AND rn_v.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_v ON rn_v.nodeHash=u_v.hash AND rn_v.nodeType='u' " + "WHERE s1.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p") ).GetHashCode() + " AND s1.objectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:o") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode(); Assert.AreEqual( expected, mapper.Sql ); } [Test] public void SingleStatementPlusUnmatchableOptionalStatementSharedSubject() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new Variable("v"), new UriRef("ex:p"), new UriRef("ex:o") ) ); builder.AddOptional( new Pattern( new Variable("v"), new UriRef("ex:p2"), new UriRef("ex:o2") ) ); Query query = builder.GetQuery(); QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT rn_v.resourceHash rh_v, rn_v.nodeHash nh_v, rn_v.nodeType nt_v, u_v.uri val_v, NULL sub_v " + "FROM Statements s1 JOIN ResourceNodes rn_v ON rn_v.resourceHash=s1.subjectHash AND rn_v.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_v ON rn_v.nodeHash=u_v.hash AND rn_v.nodeType='u' " + "WHERE s1.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p") ).GetHashCode() + " AND s1.objectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:o") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode(); Assert.AreEqual( expected, mapper.Sql ); } [Test] public void SingleStatementPlusMultipleOptionalStatementsInOneGroup() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p2"), new UriRef("ex:o2") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new Variable("v"), new UriRef("ex:p"), new UriRef("ex:o") ) ); builder.AddOptional( new Pattern( new Variable("v"), new Variable("p"), new UriRef("ex:o2") ) ); builder.AddOptional( new Pattern( new Variable("v"), new Variable("p"), new UriRef("ex:o") ) ); Query query = builder.GetQuery(); QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT rn_v.resourceHash rh_v, rn_v.nodeHash nh_v, rn_v.nodeType nt_v, u_v.uri val_v, NULL sub_v, rn_p.resourceHash rh_p, rn_p.nodeHash nh_p, rn_p.nodeType nt_p, u_p.uri val_p, NULL sub_p " + "FROM Statements s1 " + "LEFT OUTER JOIN Statements s2" + " ON s2.subjectHash=s1.subjectHash" + " AND s2.objectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:o2") ).GetHashCode() + " AND s2.graphId=" + statements.GetHashCode() + " JOIN Statements s3" + " ON s3.subjectHash=s2.subjectHash" + " AND s3.predicateHash=s2.predicateHash" + " AND s3.objectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:o") ).GetHashCode() + " AND s3.graphId=" + statements.GetHashCode() + " JOIN ResourceNodes rn_v ON rn_v.resourceHash=s1.subjectHash AND rn_v.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_v ON rn_v.nodeHash=u_v.hash AND rn_v.nodeType='u' " + "JOIN ResourceNodes rn_p ON rn_p.resourceHash=s2.predicateHash AND rn_p.graphId=s2.graphId " + "LEFT OUTER JOIN UriRefs u_p ON rn_p.nodeHash=u_p.hash AND rn_p.nodeType='u' " + "WHERE s1.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p") ).GetHashCode() + " AND s1.objectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:o") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode(); Assert.AreEqual( expected, mapper.Sql ); } [Test] public void SingleStatementPlusUnmatchableOptionalStatementWithVariable() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new Variable("v"), new UriRef("ex:p"), new UriRef("ex:o") ) ); builder.AddOptional( new Pattern( new Variable("v"), new UriRef("ex:p2"), new Variable("o") ) ); Query query = builder.GetQuery(); QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT rn_v.resourceHash rh_v, rn_v.nodeHash nh_v, rn_v.nodeType nt_v, u_v.uri val_v, NULL sub_v, NULL rh_o, NULL nh_o, NULL nt_o, NULL val_o, NULL sub_o " + "FROM Statements s1 JOIN ResourceNodes rn_v ON rn_v.resourceHash=s1.subjectHash AND rn_v.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_v ON rn_v.nodeHash=u_v.hash AND rn_v.nodeType='u' " + "WHERE s1.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p") ).GetHashCode() + " AND s1.objectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:o") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode(); Assert.AreEqual( expected, mapper.Sql ); } [Test] public void ConstraintSimpleVariableExpressionIsLiteral() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new UriRef("ex:s"), new UriRef("ex:p"), new Variable("v") ) ); builder.AddConstraint( new Constraint( new IsLiteral( new VariableExpression( new Variable("v") ) ) ) ); Query query = builder.GetQuery(); QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT rn_v.resourceHash rh_v, rn_v.nodeHash nh_v, rn_v.nodeType nt_v, COALESCE(u_v.uri, pl_v.value, l_v.value) val_v, COALESCE(tl_v.value, t_v.value) sub_v " + "FROM Statements s1 JOIN ResourceNodes rn_v ON rn_v.resourceHash=s1.objectHash AND rn_v.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_v ON rn_v.nodeHash=u_v.hash AND rn_v.nodeType='u' " + "LEFT OUTER JOIN PlainLiterals pl_v ON rn_v.nodeHash=pl_v.hash AND rn_v.nodeType='p' " + "LEFT OUTER JOIN Languages l_v ON pl_v.languageHash=l_v.hash " + "LEFT OUTER JOIN TypedLiterals tl_v ON rn_v.nodehash=tl_v.hash AND rn_v.nodeType='t' " + "LEFT OUTER JOIN DataTypes t_v ON tl_v.datatypeHash=t_v.hash " + "WHERE s1.subjectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:s") ).GetHashCode() + " AND s1.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode() + " AND (nt_v='p' OR nt_v='t')"; Assert.AreEqual( expected, mapper.Sql ); } [Test] public void ConstraintSimpleVariableExpressionIsIri() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new UriRef("ex:s"), new UriRef("ex:p"), new Variable("v") ) ); builder.AddConstraint( new Constraint( new IsIri( new VariableExpression( new Variable("v") ) ) ) ); Query query = builder.GetQuery(); QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT rn_v.resourceHash rh_v, rn_v.nodeHash nh_v, rn_v.nodeType nt_v, COALESCE(u_v.uri, pl_v.value, l_v.value) val_v, COALESCE(tl_v.value, t_v.value) sub_v " + "FROM Statements s1 JOIN ResourceNodes rn_v ON rn_v.resourceHash=s1.objectHash AND rn_v.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_v ON rn_v.nodeHash=u_v.hash AND rn_v.nodeType='u' " + "LEFT OUTER JOIN PlainLiterals pl_v ON rn_v.nodeHash=pl_v.hash AND rn_v.nodeType='p' " + "LEFT OUTER JOIN Languages l_v ON pl_v.languageHash=l_v.hash " + "LEFT OUTER JOIN TypedLiterals tl_v ON rn_v.nodehash=tl_v.hash AND rn_v.nodeType='t' " + "LEFT OUTER JOIN DataTypes t_v ON tl_v.datatypeHash=t_v.hash " + "WHERE s1.subjectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:s") ).GetHashCode() + " AND s1.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode() + " AND nt_v='u'"; Assert.AreEqual( expected, mapper.Sql ); } [Test] public void ConstraintSimpleVariableExpressionIsBlank() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new UriRef("ex:s"), new UriRef("ex:p"), new Variable("v") ) ); builder.AddConstraint( new Constraint( new IsBlank( new VariableExpression( new Variable("v") ) ) ) ); Query query = builder.GetQuery(); QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT rn_v.resourceHash rh_v, rn_v.nodeHash nh_v, rn_v.nodeType nt_v, COALESCE(u_v.uri, pl_v.value, l_v.value) val_v, COALESCE(tl_v.value, t_v.value) sub_v " + "FROM Statements s1 JOIN ResourceNodes rn_v ON rn_v.resourceHash=s1.objectHash AND rn_v.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_v ON rn_v.nodeHash=u_v.hash AND rn_v.nodeType='u' " + "LEFT OUTER JOIN PlainLiterals pl_v ON rn_v.nodeHash=pl_v.hash AND rn_v.nodeType='p' " + "LEFT OUTER JOIN Languages l_v ON pl_v.languageHash=l_v.hash " + "LEFT OUTER JOIN TypedLiterals tl_v ON rn_v.nodehash=tl_v.hash AND rn_v.nodeType='t' " + "LEFT OUTER JOIN DataTypes t_v ON tl_v.datatypeHash=t_v.hash " + "WHERE s1.subjectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:s") ).GetHashCode() + " AND s1.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode() + " AND nt_v='b'"; Assert.AreEqual( expected, mapper.Sql ); } [Test] public void ConstraintBound() { MemoryTripleStore statements = new MemoryTripleStore(); statements.Add( new Statement( new UriRef("ex:s"), new UriRef("ex:p"), new UriRef("ex:o") ) ); SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.AddPattern( new Pattern( new UriRef("ex:s"), new UriRef("ex:p"), new Variable("v") ) ); builder.AddConstraint( new Constraint( new Bound( new Variable("v") ) ) ); Query query = builder.GetQuery(); QuerySqlMapper mapper = new QuerySqlMapper(query, statements); string expected = "SELECT rn_v.resourceHash rh_v, rn_v.nodeHash nh_v, rn_v.nodeType nt_v, COALESCE(u_v.uri, pl_v.value, l_v.value) val_v, COALESCE(tl_v.value, t_v.value) sub_v " + "FROM Statements s1 JOIN ResourceNodes rn_v ON rn_v.resourceHash=s1.objectHash AND rn_v.graphId=s1.graphId " + "LEFT OUTER JOIN UriRefs u_v ON rn_v.nodeHash=u_v.hash AND rn_v.nodeType='u' " + "LEFT OUTER JOIN PlainLiterals pl_v ON rn_v.nodeHash=pl_v.hash AND rn_v.nodeType='p' " + "LEFT OUTER JOIN Languages l_v ON pl_v.languageHash=l_v.hash " + "LEFT OUTER JOIN TypedLiterals tl_v ON rn_v.nodehash=tl_v.hash AND rn_v.nodeType='t' " + "LEFT OUTER JOIN DataTypes t_v ON tl_v.datatypeHash=t_v.hash " + "WHERE s1.subjectHash=" + statements.GetResourceDenotedBy( new UriRef("ex:s") ).GetHashCode() + " AND s1.predicateHash=" + statements.GetResourceDenotedBy( new UriRef("ex:p") ).GetHashCode() + " AND s1.graphId=" + statements.GetHashCode() + " AND s1.objectHash IS NOT NULL"; Assert.AreEqual( expected, mapper.Sql ); } } }
/* * 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 OpenSim.Framework; namespace OpenSim.Data.SQLite { /// <summary> /// An Inventory Interface to the SQLite database /// </summary> public class SQLiteInventoryStore : SQLiteUtil, IInventoryDataPlugin { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const string invItemsSelect = "select * from inventoryitems"; private const string invFoldersSelect = "select * from inventoryfolders"; private static SqliteConnection conn; private static DataSet ds; private static SqliteDataAdapter invItemsDa; private static SqliteDataAdapter invFoldersDa; private static bool m_Initialized = false; public void Initialise() { m_log.Info("[SQLiteInventoryData]: " + Name + " cannot be default-initialized!"); throw new PluginNotInitialisedException(Name); } /// <summary> /// <list type="bullet"> /// <item>Initialises Inventory interface</item> /// <item>Loads and initialises a new SQLite connection and maintains it.</item> /// <item>use default URI if connect string string is empty.</item> /// </list> /// </summary> /// <param name="dbconnect">connect string</param> public void Initialise(string dbconnect) { if (!m_Initialized) { m_Initialized = true; if (dbconnect == string.Empty) { dbconnect = "URI=file:inventoryStore.db,version=3"; } m_log.Info("[INVENTORY DB]: Sqlite - connecting: " + dbconnect); conn = new SqliteConnection(dbconnect); conn.Open(); Assembly assem = GetType().Assembly; Migration m = new Migration(conn, assem, "InventoryStore"); m.Update(); SqliteCommand itemsSelectCmd = new SqliteCommand(invItemsSelect, conn); invItemsDa = new SqliteDataAdapter(itemsSelectCmd); // SqliteCommandBuilder primCb = new SqliteCommandBuilder(primDa); SqliteCommand foldersSelectCmd = new SqliteCommand(invFoldersSelect, conn); invFoldersDa = new SqliteDataAdapter(foldersSelectCmd); ds = new DataSet(); ds.Tables.Add(createInventoryFoldersTable()); invFoldersDa.Fill(ds.Tables["inventoryfolders"]); setupFoldersCommands(invFoldersDa, conn); CreateDataSetMapping(invFoldersDa, "inventoryfolders"); m_log.Info("[INVENTORY DB]: Populated Inventory Folders Definitions"); ds.Tables.Add(createInventoryItemsTable()); invItemsDa.Fill(ds.Tables["inventoryitems"]); setupItemsCommands(invItemsDa, conn); CreateDataSetMapping(invItemsDa, "inventoryitems"); m_log.Info("[INVENTORY DB]: Populated Inventory Items Definitions"); ds.AcceptChanges(); } } /// <summary> /// Closes the inventory interface /// </summary> public void Dispose() { if (conn != null) { conn.Close(); conn = null; } if (invItemsDa != null) { invItemsDa.Dispose(); invItemsDa = null; } if (invFoldersDa != null) { invFoldersDa.Dispose(); invFoldersDa = null; } if (ds != null) { ds.Dispose(); ds = null; } } /// <summary> /// /// </summary> /// <param name="row"></param> /// <returns></returns> public InventoryItemBase buildItem(DataRow row) { InventoryItemBase item = new InventoryItemBase(); item.ID = new UUID((string) row["UUID"]); item.AssetID = new UUID((string) row["assetID"]); item.AssetType = Convert.ToInt32(row["assetType"]); item.InvType = Convert.ToInt32(row["invType"]); item.Folder = new UUID((string) row["parentFolderID"]); item.Owner = new UUID((string) row["avatarID"]); item.CreatorIdentification = (string)row["creatorsID"]; item.Name = (string) row["inventoryName"]; item.Description = (string) row["inventoryDescription"]; item.NextPermissions = Convert.ToUInt32(row["inventoryNextPermissions"]); item.CurrentPermissions = Convert.ToUInt32(row["inventoryCurrentPermissions"]); item.BasePermissions = Convert.ToUInt32(row["inventoryBasePermissions"]); item.EveryOnePermissions = Convert.ToUInt32(row["inventoryEveryOnePermissions"]); item.GroupPermissions = Convert.ToUInt32(row["inventoryGroupPermissions"]); // new fields if (!Convert.IsDBNull(row["salePrice"])) item.SalePrice = Convert.ToInt32(row["salePrice"]); if (!Convert.IsDBNull(row["saleType"])) item.SaleType = Convert.ToByte(row["saleType"]); if (!Convert.IsDBNull(row["creationDate"])) item.CreationDate = Convert.ToInt32(row["creationDate"]); if (!Convert.IsDBNull(row["groupID"])) item.GroupID = new UUID((string)row["groupID"]); if (!Convert.IsDBNull(row["groupOwned"])) item.GroupOwned = Convert.ToBoolean(row["groupOwned"]); if (!Convert.IsDBNull(row["Flags"])) item.Flags = Convert.ToUInt32(row["Flags"]); return item; } /// <summary> /// Fill a database row with item data /// </summary> /// <param name="row"></param> /// <param name="item"></param> private static void fillItemRow(DataRow row, InventoryItemBase item) { row["UUID"] = item.ID.ToString(); row["assetID"] = item.AssetID.ToString(); row["assetType"] = item.AssetType; row["invType"] = item.InvType; row["parentFolderID"] = item.Folder.ToString(); row["avatarID"] = item.Owner.ToString(); row["creatorsID"] = item.CreatorIdentification.ToString(); row["inventoryName"] = item.Name; row["inventoryDescription"] = item.Description; row["inventoryNextPermissions"] = item.NextPermissions; row["inventoryCurrentPermissions"] = item.CurrentPermissions; row["inventoryBasePermissions"] = item.BasePermissions; row["inventoryEveryOnePermissions"] = item.EveryOnePermissions; row["inventoryGroupPermissions"] = item.GroupPermissions; // new fields row["salePrice"] = item.SalePrice; row["saleType"] = item.SaleType; row["creationDate"] = item.CreationDate; row["groupID"] = item.GroupID.ToString(); row["groupOwned"] = item.GroupOwned; row["flags"] = item.Flags; } /// <summary> /// Add inventory folder /// </summary> /// <param name="folder">Folder base</param> /// <param name="add">true=create folder. false=update existing folder</param> /// <remarks>nasty</remarks> private void addFolder(InventoryFolderBase folder, bool add) { lock (ds) { DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; DataRow inventoryRow = inventoryFolderTable.Rows.Find(folder.ID.ToString()); if (inventoryRow == null) { if (! add) m_log.ErrorFormat("Interface Misuse: Attempting to Update non-existant inventory folder: {0}", folder.ID); inventoryRow = inventoryFolderTable.NewRow(); fillFolderRow(inventoryRow, folder); inventoryFolderTable.Rows.Add(inventoryRow); } else { if (add) m_log.ErrorFormat("Interface Misuse: Attempting to Add inventory folder that already exists: {0}", folder.ID); fillFolderRow(inventoryRow, folder); } invFoldersDa.Update(ds, "inventoryfolders"); } } /// <summary> /// Move an inventory folder /// </summary> /// <param name="folder">folder base</param> private void moveFolder(InventoryFolderBase folder) { lock (ds) { DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; DataRow inventoryRow = inventoryFolderTable.Rows.Find(folder.ID.ToString()); if (inventoryRow == null) { inventoryRow = inventoryFolderTable.NewRow(); fillFolderRow(inventoryRow, folder); inventoryFolderTable.Rows.Add(inventoryRow); } else { moveFolderRow(inventoryRow, folder); } invFoldersDa.Update(ds, "inventoryfolders"); } } /// <summary> /// add an item in inventory /// </summary> /// <param name="item">the item</param> /// <param name="add">true=add item ; false=update existing item</param> private void addItem(InventoryItemBase item, bool add) { lock (ds) { DataTable inventoryItemTable = ds.Tables["inventoryitems"]; DataRow inventoryRow = inventoryItemTable.Rows.Find(item.ID.ToString()); if (inventoryRow == null) { if (!add) m_log.ErrorFormat("[INVENTORY DB]: Interface Misuse: Attempting to Update non-existant inventory item: {0}", item.ID); inventoryRow = inventoryItemTable.NewRow(); fillItemRow(inventoryRow, item); inventoryItemTable.Rows.Add(inventoryRow); } else { if (add) m_log.ErrorFormat("[INVENTORY DB]: Interface Misuse: Attempting to Add inventory item that already exists: {0}", item.ID); fillItemRow(inventoryRow, item); } invItemsDa.Update(ds, "inventoryitems"); DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; inventoryRow = inventoryFolderTable.Rows.Find(item.Folder.ToString()); if (inventoryRow != null) //MySQL doesn't throw an exception here, so sqlite shouldn't either. inventoryRow["version"] = (int)inventoryRow["version"] + 1; invFoldersDa.Update(ds, "inventoryfolders"); } } /// <summary> /// TODO : DataSet commit /// </summary> public void Shutdown() { // TODO: DataSet commit } /// <summary> /// The name of this DB provider /// </summary> /// <returns>Name of DB provider</returns> public string Name { get { return "SQLite Inventory Data Interface"; } } /// <summary> /// Returns the version of this DB provider /// </summary> /// <returns>A string containing the DB provider version</returns> public string Version { get { Module module = GetType().Module; // string dllName = module.Assembly.ManifestModule.Name; Version dllVersion = module.Assembly.GetName().Version; return string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build, dllVersion.Revision); } } /// <summary> /// Returns a list of inventory items contained within the specified folder /// </summary> /// <param name="folderID">The UUID of the target folder</param> /// <returns>A List of InventoryItemBase items</returns> public List<InventoryItemBase> getInventoryInFolder(UUID folderID) { lock (ds) { List<InventoryItemBase> retval = new List<InventoryItemBase>(); DataTable inventoryItemTable = ds.Tables["inventoryitems"]; string selectExp = "parentFolderID = '" + folderID + "'"; DataRow[] rows = inventoryItemTable.Select(selectExp); foreach (DataRow row in rows) { retval.Add(buildItem(row)); } return retval; } } /// <summary> /// Returns a list of the root folders within a users inventory /// </summary> /// <param name="user">The user whos inventory is to be searched</param> /// <returns>A list of folder objects</returns> public List<InventoryFolderBase> getUserRootFolders(UUID user) { return new List<InventoryFolderBase>(); } // see InventoryItemBase.getUserRootFolder public InventoryFolderBase getUserRootFolder(UUID user) { lock (ds) { List<InventoryFolderBase> folders = new List<InventoryFolderBase>(); DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; string selectExp = "agentID = '" + user + "' AND parentID = '" + UUID.Zero + "'"; DataRow[] rows = inventoryFolderTable.Select(selectExp); foreach (DataRow row in rows) { folders.Add(buildFolder(row)); } // There should only ever be one root folder for a user. However, if there's more // than one we'll simply use the first one rather than failing. It would be even // nicer to print some message to this effect, but this feels like it's too low a // to put such a message out, and it's too minor right now to spare the time to // suitably refactor. if (folders.Count > 0) { return folders[0]; } return null; } } /// <summary> /// Append a list of all the child folders of a parent folder /// </summary> /// <param name="folders">list where folders will be appended</param> /// <param name="parentID">ID of parent</param> protected void getInventoryFolders(ref List<InventoryFolderBase> folders, UUID parentID) { lock (ds) { DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; string selectExp = "parentID = '" + parentID + "'"; DataRow[] rows = inventoryFolderTable.Select(selectExp); foreach (DataRow row in rows) { folders.Add(buildFolder(row)); } } } /// <summary> /// Returns a list of inventory folders contained in the folder 'parentID' /// </summary> /// <param name="parentID">The folder to get subfolders for</param> /// <returns>A list of inventory folders</returns> public List<InventoryFolderBase> getInventoryFolders(UUID parentID) { List<InventoryFolderBase> folders = new List<InventoryFolderBase>(); getInventoryFolders(ref folders, parentID); return folders; } /// <summary> /// See IInventoryDataPlugin /// </summary> /// <param name="parentID"></param> /// <returns></returns> public List<InventoryFolderBase> getFolderHierarchy(UUID parentID) { /* Note: There are subtle changes between this implementation of getFolderHierarchy and the previous one * - We will only need to hit the database twice instead of n times. * - We assume the database is well-formed - no stranded/dangling folders, all folders in heirarchy owned * by the same person, each user only has 1 inventory heirarchy * - The returned list is not ordered, instead of breadth-first ordered There are basically 2 usage cases for getFolderHeirarchy: 1) Getting the user's entire inventory heirarchy when they log in 2) Finding a subfolder heirarchy to delete when emptying the trash. This implementation will pull all inventory folders from the database, and then prune away any folder that is not part of the requested sub-heirarchy. The theory is that it is cheaper to make 1 request from the database than to make n requests. This pays off only if requested heirarchy is large. By making this choice, we are making the worst case better at the cost of making the best case worse - Francis */ List<InventoryFolderBase> folders = new List<InventoryFolderBase>(); DataRow[] folderRows = null, parentRow; InventoryFolderBase parentFolder = null; lock (ds) { /* Fetch the parent folder from the database to determine the agent ID. * Then fetch all inventory folders for that agent from the agent ID. */ DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; string selectExp = "UUID = '" + parentID + "'"; parentRow = inventoryFolderTable.Select(selectExp); // Assume at most 1 result if (parentRow.GetLength(0) >= 1) // No result means parent folder does not exist { parentFolder = buildFolder(parentRow[0]); UUID agentID = parentFolder.Owner; selectExp = "agentID = '" + agentID + "'"; folderRows = inventoryFolderTable.Select(selectExp); } if (folderRows != null && folderRows.GetLength(0) >= 1) // No result means parent folder does not exist { // or has no children /* if we're querying the root folder, just return an unordered list of all folders in the user's * inventory */ if (parentFolder.ParentID == UUID.Zero) { foreach (DataRow row in folderRows) { InventoryFolderBase curFolder = buildFolder(row); if (curFolder.ID != parentID) // Return all folders except the parent folder of heirarchy folders.Add(buildFolder(row)); } } // If requesting root folder /* else we are querying a non-root folder. We currently have a list of all of the user's folders, * we must construct a list of all folders in the heirarchy below parentID. * Our first step will be to construct a hash table of all folders, indexed by parent ID. * Once we have constructed the hash table, we will do a breadth-first traversal on the tree using the * hash table to find child folders. */ else { // Querying a non-root folder // Build a hash table of all user's inventory folders, indexed by each folder's parent ID Dictionary<UUID, List<InventoryFolderBase>> hashtable = new Dictionary<UUID, List<InventoryFolderBase>>(folderRows.GetLength(0)); foreach (DataRow row in folderRows) { InventoryFolderBase curFolder = buildFolder(row); if (curFolder.ParentID != UUID.Zero) // Discard root of tree - not needed { if (hashtable.ContainsKey(curFolder.ParentID)) { // Current folder already has a sibling - append to sibling list hashtable[curFolder.ParentID].Add(curFolder); } else { List<InventoryFolderBase> siblingList = new List<InventoryFolderBase>(); siblingList.Add(curFolder); // Current folder has no known (yet) siblings hashtable.Add(curFolder.ParentID, siblingList); } } } // For all inventory folders // Note: Could release the ds lock here - we don't access folderRows or the database anymore. // This is somewhat of a moot point as the callers of this function usually lock db anyways. if (hashtable.ContainsKey(parentID)) // if requested folder does have children folders.AddRange(hashtable[parentID]); // BreadthFirstSearch build inventory tree **Note: folders.Count is *not* static for (int i = 0; i < folders.Count; i++) if (hashtable.ContainsKey(folders[i].ID)) folders.AddRange(hashtable[folders[i].ID]); } // if requesting a subfolder heirarchy } // if folder parentID exists and has children } // lock ds return folders; } /// <summary> /// Returns an inventory item by its UUID /// </summary> /// <param name="item">The UUID of the item to be returned</param> /// <returns>A class containing item information</returns> public InventoryItemBase getInventoryItem(UUID item) { lock (ds) { DataRow row = ds.Tables["inventoryitems"].Rows.Find(item.ToString()); if (row != null) { return buildItem(row); } else { return null; } } } /// <summary> /// Returns a specified inventory folder by its UUID /// </summary> /// <param name="folder">The UUID of the folder to be returned</param> /// <returns>A class containing folder information</returns> public InventoryFolderBase getInventoryFolder(UUID folder) { // TODO: Deep voodoo here. If you enable this code then // multi region breaks. No idea why, but I figured it was // better to leave multi region at this point. It does mean // that you don't get to see system textures why creating // clothes and the like. :( lock (ds) { DataRow row = ds.Tables["inventoryfolders"].Rows.Find(folder.ToString()); if (row != null) { return buildFolder(row); } else { return null; } } } /// <summary> /// Creates a new inventory item based on item /// </summary> /// <param name="item">The item to be created</param> public void addInventoryItem(InventoryItemBase item) { addItem(item, true); } /// <summary> /// Updates an inventory item with item (updates based on ID) /// </summary> /// <param name="item">The updated item</param> public void updateInventoryItem(InventoryItemBase item) { addItem(item, false); } /// <summary> /// Delete an inventory item /// </summary> /// <param name="item">The item UUID</param> public void deleteInventoryItem(UUID itemID) { lock (ds) { DataTable inventoryItemTable = ds.Tables["inventoryitems"]; DataRow inventoryRow = inventoryItemTable.Rows.Find(itemID.ToString()); if (inventoryRow != null) { inventoryRow.Delete(); } invItemsDa.Update(ds, "inventoryitems"); } } public InventoryItemBase queryInventoryItem(UUID itemID) { return getInventoryItem(itemID); } public InventoryFolderBase queryInventoryFolder(UUID folderID) { return getInventoryFolder(folderID); } /// <summary> /// Delete all items in the specified folder /// </summary> /// <param name="folderId">id of the folder, whose item content should be deleted</param> /// <todo>this is horribly inefficient, but I don't want to ruin the overall structure of this implementation</todo> private void deleteItemsInFolder(UUID folderId) { List<InventoryItemBase> items = getInventoryInFolder(folderId); foreach (InventoryItemBase i in items) deleteInventoryItem(i.ID); } /// <summary> /// Adds a new folder specified by folder /// </summary> /// <param name="folder">The inventory folder</param> public void addInventoryFolder(InventoryFolderBase folder) { addFolder(folder, true); } /// <summary> /// Updates a folder based on its ID with folder /// </summary> /// <param name="folder">The inventory folder</param> public void updateInventoryFolder(InventoryFolderBase folder) { addFolder(folder, false); } /// <summary> /// Moves a folder based on its ID with folder /// </summary> /// <param name="folder">The inventory folder</param> public void moveInventoryFolder(InventoryFolderBase folder) { moveFolder(folder); } /// <summary> /// Delete a folder /// </summary> /// <remarks> /// This will clean-up any child folders and child items as well /// </remarks> /// <param name="folderID">the folder UUID</param> public void deleteInventoryFolder(UUID folderID) { lock (ds) { List<InventoryFolderBase> subFolders = getFolderHierarchy(folderID); DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; DataRow inventoryRow; //Delete all sub-folders foreach (InventoryFolderBase f in subFolders) { inventoryRow = inventoryFolderTable.Rows.Find(f.ID.ToString()); if (inventoryRow != null) { deleteItemsInFolder(f.ID); inventoryRow.Delete(); } } //Delete the actual row inventoryRow = inventoryFolderTable.Rows.Find(folderID.ToString()); if (inventoryRow != null) { deleteItemsInFolder(folderID); inventoryRow.Delete(); } invFoldersDa.Update(ds, "inventoryfolders"); } } /*********************************************************************** * * Data Table definitions * **********************************************************************/ protected void CreateDataSetMapping(IDataAdapter da, string tableName) { ITableMapping dbMapping = da.TableMappings.Add(tableName, tableName); foreach (DataColumn col in ds.Tables[tableName].Columns) { dbMapping.ColumnMappings.Add(col.ColumnName, col.ColumnName); } } /// <summary> /// Create the "inventoryitems" table /// </summary> private static DataTable createInventoryItemsTable() { DataTable inv = new DataTable("inventoryitems"); createCol(inv, "UUID", typeof (String)); //inventoryID createCol(inv, "assetID", typeof (String)); createCol(inv, "assetType", typeof (Int32)); createCol(inv, "invType", typeof (Int32)); createCol(inv, "parentFolderID", typeof (String)); createCol(inv, "avatarID", typeof (String)); createCol(inv, "creatorsID", typeof (String)); createCol(inv, "inventoryName", typeof (String)); createCol(inv, "inventoryDescription", typeof (String)); // permissions createCol(inv, "inventoryNextPermissions", typeof (Int32)); createCol(inv, "inventoryCurrentPermissions", typeof (Int32)); createCol(inv, "inventoryBasePermissions", typeof (Int32)); createCol(inv, "inventoryEveryOnePermissions", typeof (Int32)); createCol(inv, "inventoryGroupPermissions", typeof (Int32)); // sale info createCol(inv, "salePrice", typeof(Int32)); createCol(inv, "saleType", typeof(Byte)); // creation date createCol(inv, "creationDate", typeof(Int32)); // group info createCol(inv, "groupID", typeof(String)); createCol(inv, "groupOwned", typeof(Boolean)); // Flags createCol(inv, "flags", typeof(UInt32)); inv.PrimaryKey = new DataColumn[] { inv.Columns["UUID"] }; return inv; } /// <summary> /// Creates the "inventoryfolders" table /// </summary> /// <returns></returns> private static DataTable createInventoryFoldersTable() { DataTable fol = new DataTable("inventoryfolders"); createCol(fol, "UUID", typeof (String)); //folderID createCol(fol, "name", typeof (String)); createCol(fol, "agentID", typeof (String)); createCol(fol, "parentID", typeof (String)); createCol(fol, "type", typeof (Int32)); createCol(fol, "version", typeof (Int32)); fol.PrimaryKey = new DataColumn[] {fol.Columns["UUID"]}; return fol; } /// <summary> /// /// </summary> /// <param name="da"></param> /// <param name="conn"></param> private void setupItemsCommands(SqliteDataAdapter da, SqliteConnection conn) { lock (ds) { da.InsertCommand = createInsertCommand("inventoryitems", ds.Tables["inventoryitems"]); da.InsertCommand.Connection = conn; da.UpdateCommand = createUpdateCommand("inventoryitems", "UUID=:UUID", ds.Tables["inventoryitems"]); da.UpdateCommand.Connection = conn; SqliteCommand delete = new SqliteCommand("delete from inventoryitems where UUID = :UUID"); delete.Parameters.Add(createSqliteParameter("UUID", typeof(String))); delete.Connection = conn; da.DeleteCommand = delete; } } /// <summary> /// /// </summary> /// <param name="da"></param> /// <param name="conn"></param> private void setupFoldersCommands(SqliteDataAdapter da, SqliteConnection conn) { lock (ds) { da.InsertCommand = createInsertCommand("inventoryfolders", ds.Tables["inventoryfolders"]); da.InsertCommand.Connection = conn; da.UpdateCommand = createUpdateCommand("inventoryfolders", "UUID=:UUID", ds.Tables["inventoryfolders"]); da.UpdateCommand.Connection = conn; SqliteCommand delete = new SqliteCommand("delete from inventoryfolders where UUID = :UUID"); delete.Parameters.Add(createSqliteParameter("UUID", typeof(String))); delete.Connection = conn; da.DeleteCommand = delete; } } /// <summary> /// /// </summary> /// <param name="row"></param> /// <returns></returns> private static InventoryFolderBase buildFolder(DataRow row) { InventoryFolderBase folder = new InventoryFolderBase(); folder.ID = new UUID((string) row["UUID"]); folder.Name = (string) row["name"]; folder.Owner = new UUID((string) row["agentID"]); folder.ParentID = new UUID((string) row["parentID"]); folder.Type = Convert.ToInt16(row["type"]); folder.Version = Convert.ToUInt16(row["version"]); return folder; } /// <summary> /// /// </summary> /// <param name="row"></param> /// <param name="folder"></param> private static void fillFolderRow(DataRow row, InventoryFolderBase folder) { row["UUID"] = folder.ID.ToString(); row["name"] = folder.Name; row["agentID"] = folder.Owner.ToString(); row["parentID"] = folder.ParentID.ToString(); row["type"] = folder.Type; row["version"] = folder.Version; } /// <summary> /// /// </summary> /// <param name="row"></param> /// <param name="folder"></param> private static void moveFolderRow(DataRow row, InventoryFolderBase folder) { row["UUID"] = folder.ID.ToString(); row["parentID"] = folder.ParentID.ToString(); } public List<InventoryItemBase> fetchActiveGestures (UUID avatarID) { lock (ds) { List<InventoryItemBase> items = new List<InventoryItemBase>(); DataTable inventoryItemTable = ds.Tables["inventoryitems"]; string selectExp = "avatarID = '" + avatarID + "' AND assetType = " + (int)AssetType.Gesture + " AND flags = 1"; //m_log.DebugFormat("[SQL]: sql = " + selectExp); DataRow[] rows = inventoryItemTable.Select(selectExp); foreach (DataRow row in rows) { items.Add(buildItem(row)); } return items; } } } }
// ------------------------------------------------------------------ // DirectX.Capture // // History: // 2009-Feb-27 HV - created // Functionality to control Color Space of video capture device // - Added Brian's Low 'december 2003' code (color space, video standard) // - Added code to list available color spaces // - Add fix for capture devices supporting no video standard // - Added additional color spaces, such as HCW2, YUV2, I420, IYUV // Please report possible new values, so it can be added! // // Copyright (C) 2009 Hans Vosman // ------------------------------------------------------------------ using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Reflection; using System.Collections; using System.Windows.Forms; #if DSHOWNET using DShowNET; #else using DirectShowLib; #endif namespace DirectX.Capture { /// <summary> /// Summary description for Class1. /// </summary> public class DxUtils: CollectionBase { /// <summary> Possible color spaces. </summary> /// <remarks> Note to developers: when adding new color spaces enums ensure you /// add the associated Guids in the ColorSpace property.</remarks> public enum ColorSpaceEnum { /// <summary> 4:4:4 YUV format </summary> [Label("56555941-0000-0010-8000-00AA00389B71")] AYUV, /// <summary> UYVY (packed 4:2:2) </summary> [Label("59565955-0000-0010-8000-00AA00389B71")] UYVY, /// <summary> Same as Y41P </summary> [Label("31313459-0000-0010-8000-00AA00389B71")] Y411, /// <summary> Y41P (packed 4:1:1) </summary> [Label("50313459-0000-0010-8000-00AA00389B71")] Y41P, /// <summary> Y211 </summary> [Label("31313259-0000-0010-8000-00AA00389B71")] Y211, /// <summary> YUV2 (packed 4:2:2) </summary> [Label("32565559-0000-0010-8000-00AA00389B71")] YUV2, /// <summary> YVYU (packed 4:2:2) </summary> [Label("55595659-0000-0010-8000-00AA00389B71")] YVYU, /// <summary> YVYU (packed 4:2:2) </summary> [Label("56595559-0000-0010-8000-00AA00389B71")] YUYV, /// <summary> YVU9 </summary> [Label("39555659-0000-0010-8000-00AA00389B71")] YVU9, /// <summary> YV12 </summary> [Label("32315659-0000-0010-8000-00AA00389B71")] YV12, /// <summary> RGB, 1 bpp, palettized </summary> [Label("e436eb78-524f-11ce-9f53-0020af0ba770")] RGB1, /// <summary> RGB, 4 bpp, palettized </summary> [Label("e436eb79-524f-11ce-9f53-0020af0ba770")] RGB4, /// <summary> RGB, 8 bpp </summary> [Label("e436eb7a-524f-11ce-9f53-0020af0ba770")] RGB8, /// <summary> RGB 565, 16 bpp </summary> [Label("e436eb7b-524f-11ce-9f53-0020af0ba770")] RGB565, /// <summary> RGB 555, 16 bpp </summary> [Label("e436eb7c-524f-11ce-9f53-0020af0ba770")] RGB555, /// <summary> RGB, 24 bpp </summary> [Label("e436eb7d-524f-11ce-9f53-0020af0ba770")] RGB24, /// <summary> RGB 32 bpp, no alpha channel </summary> [Label("e436eb7e-524f-11ce-9f53-0020af0ba770")] RGB32, /// <summary> RGB, 32 bpp, alpha channel </summary> [Label("773c9ac0-3274-11d0-B724-00aa006c1A01")] ARGB32, /// <summary> Trust webcam, I420 </summary> [Label("30323449-0000-0010-8000-00AA00389B71")] I420, /// <summary> IYUV </summary> [Label("56555949-0000-0010-8000-00AA00389B71")] IYUV, /// <summary> /// HCW2 format for the Capture as well as the 656 pin /// Hauppauge PVR150 (I420 , IYUV??? 4:2:0 Intel Indeo) /// </summary> [Label("32574348-005b-4504-99f8-90826c806657")] HCW2, /// <summary> /// YUY2 (packed 4:2:2), Pinnacle 330eV /// </summary> [Label("32595559-0000-0010-8000-00AA00389B71")] YUY2, } /// <summary> Video Decoder </summary> protected IAMAnalogVideoDecoder videoDecoder = null; /// <summary> Array List </summary> protected ArrayList subTypeList = null; /// <summary> /// Check if the Video Decoder interface is available /// </summary> public bool VideoDecoderAvail { get { return this.videoDecoder != null; } } /// <summary> /// Constructor /// </summary> public DxUtils() { // // TODO: Add constructor logic here // } /// <summary> /// Dispose DxUtils /// </summary> public void Dispose() { this.videoDecoder = null; if(this.subTypeList != null) { this.subTypeList.Clear(); this.subTypeList = null; } } /// <summary> /// Initialize the video control utilities /// </summary> /// <param name="videoDeviceFilter"></param> /// <returns></returns> public bool InitDxUtils(IBaseFilter videoDeviceFilter) { // Retrieve the IAMAnalogVideoDecoder interface // for setting video format (NTSC, PAL, SECAM) videoDecoder = videoDeviceFilter as IAMAnalogVideoDecoder; #if DEBUG int hr; Debug.WriteLine("-----------------------------------------"); try { Debug.WriteLine(""); // Retrieve the IAMAnalogVideoDecoder interface if available Debug.WriteLine(""); Debug.WriteLine("Testing video format..."); IAMAnalogVideoDecoder a; a = videoDeviceFilter as IAMAnalogVideoDecoder; if (a == null) { Debug.WriteLine("Failed to get IAMAnalogVideoDecoder interface"); } else { Debug.Write("Found IAMAnalogVideoDecoder interface... "); AnalogVideoStandard avs; hr = a.get_TVFormat(out avs); Debug.WriteLine("TV Format = " + (hr==0?avs.ToString():" FAILED(" + hr + ")")); hr = a.put_TVFormat((AnalogVideoStandard)0x10); Debug.WriteLine("Setting video format to PAL_B... " + (hr==0?"success":" FAILED(" + hr + ")")); } } catch (Exception e) { Debug.WriteLine(e.ToString()); } Debug.WriteLine("-----------------------------------------"); #endif return (this.videoDecoder != null)? true: false; } /// <summary> /// Gets and sets the video standard (NTSC, PAL, etc...) /// Added check on videoDecoder pointer, if value is null, /// then do nothing. An uninitialized pointer might be an /// error but might also indicate that the capture device /// does not support the Video Decoder interface (and that /// is not an error). /// </summary> public AnalogVideoStandard VideoStandard { get { #if SHOWNET DShowNET.AnalogVideoStandard v; #else AnalogVideoStandard v; #endif if(this.videoDecoder != null) { int hr = videoDecoder.get_TVFormat(out v); if ( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); return (AnalogVideoStandard)v; } else { return (AnalogVideoStandard.None); } } set { if(this.videoDecoder != null) { #if DSHOWNET int hr = videoDecoder.put_TVFormat( (DShowNET.AnalogVideoStandard) value ); #else int hr = videoDecoder.put_TVFormat( (AnalogVideoStandard) value ); #endif if ( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); } } } /// <summary> /// Provide available Video Standards /// </summary> public AnalogVideoStandard AvailableVideoStandards { get { #if SHOWNET DShowNET.AnalogVideoStandard v; #else AnalogVideoStandard v; #endif if(this.videoDecoder != null) { int hr = videoDecoder.get_AvailableTVFormats(out v); if ( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); return (AnalogVideoStandard)v; } else { return (AnalogVideoStandard.None); } } } /// <summary> /// Make FourCC from media subtype /// </summary> /// <param name="guid"></param> /// <param name="mediaSubType"></param> /// <returns></returns> public bool MakeFourCC(Guid guid, out String mediaSubType) { mediaSubType = ""; try { foreach (object c in Enum.GetValues(typeof(ColorSpaceEnum))) { if ( guid == new Guid(LabelAttribute.FromMember(c)) ) { mediaSubType = ((ColorSpaceEnum)c).ToString(); return true; } } } catch { } return false; } /// <summary> /// Get the video type for the specified pin interface /// </summary> /// <param name="streamConfig"></param> /// <returns></returns> public ColorSpaceEnum getMediaSubType(IAMStreamConfig streamConfig) { ColorSpaceEnum retval = ColorSpaceEnum.RGB24; bool found; #if DSHOWNET IntPtr pmt = IntPtr.Zero; #endif AMMediaType mediaType = new AMMediaType(); try { // Get the current format info #if DSHOWNET int hr = streamConfig.GetFormat(out pmt); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } Marshal.PtrToStructure(pmt, mediaType); #else int hr = streamConfig.GetFormat(out mediaType); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } #endif // Search the Guids to find the correct enum value. // Each enum value has a Guid associated with it // We store the Guid as a string in a LabelAttribute // applied to each enum value. See the ColorSpaceEnum. found = false; foreach (object c in Enum.GetValues(typeof(ColorSpaceEnum))) { if (mediaType.subType == new Guid(LabelAttribute.FromMember(c))) { found = true; retval = (ColorSpaceEnum)c; } } if(!found) { #if DEBUG String mediaSubType; MakeFourCC(mediaType.subType, out mediaSubType); Debug.WriteLine("Unknown color space (media subtype=" + mediaSubType + "):" + mediaType.subType.ToString()); #endif throw new ApplicationException("Unknown color space (media subtype):" + mediaType.subType.ToString()); } } finally { DsUtils.FreeAMMediaType( mediaType ); #if DSHOWNET Marshal.FreeCoTaskMem( pmt ); #endif } return retval; } /// <summary> /// Set video type for the specified pin interface /// </summary> /// <param name="streamConfig"></param> /// <param name="newValue"></param> public void setMediaSubType(IAMStreamConfig streamConfig, ColorSpaceEnum newValue) { #if DSHOWNET IntPtr pmt = IntPtr.Zero; #endif AMMediaType mediaType = new AMMediaType(); try { // Get the current format info #if DSHOWNET int hr = streamConfig.GetFormat(out pmt); if(hr < 0) { Marshal.ThrowExceptionForHR(hr); } Marshal.PtrToStructure(pmt, mediaType); #else int hr = streamConfig.GetFormat(out mediaType); if(hr < 0) { Marshal.ThrowExceptionForHR(hr); } #endif // Change the media subtype // Each enum value has a Guid associated with it // We store the Guid as a string in a LabelAttribute // applied to each enum value. See the ColorSpaceEnum. mediaType.subType = new Guid(LabelAttribute.FromMember(newValue)); // Save the changes hr = streamConfig.SetFormat(mediaType); if(hr < 0) { Marshal.ThrowExceptionForHR(hr); } } finally { DsUtils.FreeAMMediaType(mediaType); #if DSHOWNET Marshal.FreeCoTaskMem(pmt); #endif } } /// <summary> /// Set video type for the specified pin interface /// </summary> /// <param name="streamConfig"></param> /// <param name="newValue"></param> /// <returns></returns> public bool setMediaSubType(IAMStreamConfig streamConfig, Guid newValue) { #if DSHOWNET IntPtr pmt = IntPtr.Zero; #endif AMMediaType mediaType = new AMMediaType(); try { // Get the current format info #if DSHOWNET int hr = streamConfig.GetFormat(out pmt); if(hr < 0) { return false; } Marshal.PtrToStructure(pmt, mediaType); #else int hr = streamConfig.GetFormat(out mediaType); if(hr < 0) { return false; } #endif // Change the media subtype // Each enum value has a Guid associated with it // We store the Guid as a string in a LabelAttribute // applied to each enum value. See the ColorSpaceEnum. mediaType.subType = newValue; // Save the changes hr = streamConfig.SetFormat(mediaType); if(hr < 0) { return false; } } finally { DsUtils.FreeAMMediaType(mediaType); #if DSHOWNET Marshal.FreeCoTaskMem(pmt); #endif } return true; } /// <summary> /// Media subtype list /// </summary> public string [] SubTypeList { get { string[] stringList = null; if((subTypeList != null)&&(subTypeList.Count > 0)) { stringList = new String[subTypeList.Count]; for(int i = 0; i < subTypeList.Count; i++) { MakeFourCC((Guid)subTypeList[i], out stringList[i]); } } return stringList; } } /// <summary> /// Find media data by trial and error, just try every media type /// in the list, the ones that do not return an error, are accepted. /// This function might be handy if DShowNET is used as library /// instead of DirectShowLib. /// This function should be called with a derendered graph only, /// so with capture device only and no rendering of audio, video or /// VBI. /// </summary> /// <param name="streamConfig"></param> /// <returns></returns> public bool FindMediaData(IAMStreamConfig streamConfig) { bool result = false; try { ColorSpaceEnum currentValue = this.getMediaSubType(streamConfig); if(this.subTypeList != null) { this.subTypeList.Clear(); } foreach (object c in Enum.GetValues(typeof(ColorSpaceEnum))) { Guid subType = new Guid(LabelAttribute.FromMember(c)); if(this.setMediaSubType(streamConfig, subType)) { if(this.subTypeList == null) { this.subTypeList = new ArrayList(); } // Check if subtype is already in list, // if so then do not add, else add to list bool notinlist = true; for(int i = 0;(i < this.subTypeList.Count)&&(notinlist); i++) { if(((Guid)this.subTypeList[i]) == subType) { notinlist = false; } } if(notinlist) { this.subTypeList.Add(subType); result = true; } } } this.setMediaSubType(streamConfig, currentValue); return result; } catch {} return result; } private object GetField(AMMediaType mediaType, String fieldName) { object formatStruct; if ( mediaType.formatType == FormatType.WaveEx ) formatStruct = new WaveFormatEx(); else if ( mediaType.formatType == FormatType.VideoInfo ) formatStruct = new VideoInfoHeader(); else if ( mediaType.formatType == FormatType.VideoInfo2 ) formatStruct = new VideoInfoHeader2(); else throw new NotSupportedException( "This device does not support a recognized format block." ); // Retrieve the nested structure Marshal.PtrToStructure( mediaType.formatPtr, formatStruct ); // Find the required field Type structType = formatStruct.GetType(); FieldInfo fieldInfo = structType.GetField(fieldName); if(fieldInfo != null) { return fieldInfo.GetValue(formatStruct); } return null; } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; using WeifenLuo.WinFormsUI.Docking; namespace DockSample.Customization { internal class VS2003DockPaneStrip : DockPaneStripBase { private class TabVS2003 : Tab { internal TabVS2003(IDockContent content) : base(content) { } private int m_tabX; protected internal int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth; protected internal int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } private int m_maxWidth; protected internal int MaxWidth { get { return m_maxWidth; } set { m_maxWidth = value; } } private bool m_flag; protected internal bool Flag { get { return m_flag; } set { m_flag = value; } } } protected override DockPaneStripBase.Tab CreateTab(IDockContent content) { return new TabVS2003(content); } private class DocumentButton : Label { public DocumentButton(Image image) { Image = image; } } #region consts private const int _ToolWindowStripGapLeft = 4; private const int _ToolWindowStripGapRight = 3; private const int _ToolWindowImageHeight = 16; private const int _ToolWindowImageWidth = 16; private const int _ToolWindowImageGapTop = 3; private const int _ToolWindowImageGapBottom = 1; private const int _ToolWindowImageGapLeft = 3; private const int _ToolWindowImageGapRight = 2; private const int _ToolWindowTextGapRight = 1; private const int _ToolWindowTabSeperatorGapTop = 3; private const int _ToolWindowTabSeperatorGapBottom = 3; private const int _DocumentTabMaxWidth = 200; private const int _DocumentButtonGapTop = 5; private const int _DocumentButtonGapBottom = 5; private const int _DocumentButtonGapBetween = 0; private const int _DocumentButtonGapRight = 3; private const int _DocumentTabGapTop = 3; private const int _DocumentTabGapLeft = 3; private const int _DocumentTabGapRight = 3; private const int _DocumentIconGapLeft = 6; private const int _DocumentIconHeight = 16; private const int _DocumentIconWidth = 16; #endregion private InertButton m_buttonClose, m_buttonScrollLeft, m_buttonScrollRight; private IContainer m_components; private ToolTip m_toolTip; /// <exclude/> protected IContainer Components { get { return m_components; } } private int m_offsetX = 0; private int OffsetX { get { return m_offsetX; } set { m_offsetX = value; #if DEBUG if (m_offsetX > 0) throw new InvalidOperationException(); #endif } } #region Customizable Properties /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowStripGapLeft"]/*'/> protected virtual int ToolWindowStripGapLeft { get { return _ToolWindowStripGapLeft; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowStripGapRight"]/*'/> protected virtual int ToolWindowStripGapRight { get { return _ToolWindowStripGapRight; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowImageHeight"]/*'/> protected virtual int ToolWindowImageHeight { get { return _ToolWindowImageHeight; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowImageWidth"]/*'/> protected virtual int ToolWindowImageWidth { get { return _ToolWindowImageWidth; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowImageGapTop"]/*'/> protected virtual int ToolWindowImageGapTop { get { return _ToolWindowImageGapTop; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowImageGapBottom"]/*'/> protected virtual int ToolWindowImageGapBottom { get { return _ToolWindowImageGapBottom; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowImageGapLeft"]/*'/> protected virtual int ToolWindowImageGapLeft { get { return _ToolWindowImageGapLeft; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowImageGapRight"]/*'/> protected virtual int ToolWindowImageGapRight { get { return _ToolWindowImageGapRight; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowTextGapRight"]/*'/> protected virtual int ToolWindowTextGapRight { get { return _ToolWindowTextGapRight; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowSeperatorGaptop"]/*'/> protected virtual int ToolWindowTabSeperatorGapTop { get { return _ToolWindowTabSeperatorGapTop; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowSeperatorGapBottom"]/*'/> protected virtual int ToolWindowTabSeperatorGapBottom { get { return _ToolWindowTabSeperatorGapBottom; } } private static Image _imageCloseEnabled = null; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ImageCloseEnabled"]/*'/> protected virtual Image ImageCloseEnabled { get { if (_imageCloseEnabled == null) _imageCloseEnabled = Resources.DockPaneStrip_CloseEnabled; return _imageCloseEnabled; } } private static Image _imageCloseDisabled = null; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ImageCloseDisabled"]/*'/> protected virtual Image ImageCloseDisabled { get { if (_imageCloseDisabled == null) _imageCloseDisabled = Resources.DockPaneStrip_CloseDisabled; return _imageCloseDisabled; } } private static Image _imageScrollLeftEnabled = null; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ImageScrollLeftEnabled"]/*'/> protected virtual Image ImageScrollLeftEnabled { get { if (_imageScrollLeftEnabled == null) _imageScrollLeftEnabled = Resources.DockPaneStrip_ScrollLeftEnabled; return _imageScrollLeftEnabled; } } private static Image _imageScrollLeftDisabled = null; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ImageScrollLeftDisabled"]/*'/> protected virtual Image ImageScrollLeftDisabled { get { if (_imageScrollLeftDisabled == null) _imageScrollLeftDisabled = Resources.DockPaneStrip_ScrollLeftDisabled; return _imageScrollLeftDisabled; } } private static Image _imageScrollRightEnabled = null; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ImageScrollRightEnabled"]/*'/> protected virtual Image ImageScrollRightEnabled { get { if (_imageScrollRightEnabled == null) _imageScrollRightEnabled = Resources.DockPaneStrip_ScrollRightEnabled; return _imageScrollRightEnabled; } } private static Image _imageScrollRightDisabled = null; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ImageScrollRightDisabled"]/*'/> protected virtual Image ImageScrollRightDisabled { get { if (_imageScrollRightDisabled == null) _imageScrollRightDisabled = Resources.DockPaneStrip_ScrollRightDisabled; return _imageScrollRightDisabled; } } private static string _toolTipClose = null; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolTipClose"]/*'/> protected virtual string ToolTipClose { get { if (_toolTipClose == null) _toolTipClose = Strings.DockPaneStrip_ToolTipClose; return _toolTipClose; } } private static string _toolTipScrollLeft = null; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolTipScrollLeft"]/*'/> protected virtual string ToolTipScrollLeft { get { if (_toolTipScrollLeft == null) _toolTipScrollLeft = Strings.DockPaneStrip_ToolTipScrollLeft; return _toolTipScrollLeft; } } private static string _toolTipScrollRight = null; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolTipScrollRight"]/*'/> protected virtual string ToolTipScrollRight { get { if (_toolTipScrollRight == null) _toolTipScrollRight = Strings.DockPaneStrip_ToolTipScrollRight; return _toolTipScrollRight; } } private static TextFormatFlags _toolWindowTextFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.HorizontalCenter | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowTextStringFormat"]/*'/> protected virtual TextFormatFlags ToolWindowTextFormat { get { return _toolWindowTextFormat; } } private static TextFormatFlags _documentTextFormat = TextFormatFlags.PathEllipsis | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentTextStringFormat"]/*'/> public static TextFormatFlags DocumentTextFormat { get { return _documentTextFormat; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentTabMaxWidth"]/*'/> protected virtual int DocumentTabMaxWidth { get { return _DocumentTabMaxWidth; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentButtonGapTop"]/*'/> protected virtual int DocumentButtonGapTop { get { return _DocumentButtonGapTop; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentButtonGapBottom"]/*'/> protected virtual int DocumentButtonGapBottom { get { return _DocumentButtonGapBottom; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentButtonGapBetween"]/*'/> protected virtual int DocumentButtonGapBetween { get { return _DocumentButtonGapBetween; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentButtonGapRight"]/*'/> protected virtual int DocumentButtonGapRight { get { return _DocumentButtonGapRight; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentTabGapTop"]/*'/> protected virtual int DocumentTabGapTop { get { return _DocumentTabGapTop; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentTabGapLeft"]/*'/> protected virtual int DocumentTabGapLeft { get { return _DocumentTabGapLeft; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentTabGapRight"]/*'/> protected virtual int DocumentTabGapRight { get { return _DocumentTabGapRight; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentIconGapLeft"]/*'/> protected virtual int DocumentIconGapLeft { get { return _DocumentIconGapLeft; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentIconWidth"]/*'/> protected virtual int DocumentIconWidth { get { return _DocumentIconWidth; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentIconHeight"]/*'/> protected virtual int DocumentIconHeight { get { return _DocumentIconHeight; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="OutlineInnerPen"]/*'/> protected virtual Pen OutlineInnerPen { get { return SystemPens.ControlText; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="OutlineOuterPen"]/*'/> protected virtual Pen OutlineOuterPen { get { return SystemPens.ActiveCaptionText; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ActiveBackBrush"]/*'/> protected virtual Brush ActiveBackBrush { get { return SystemBrushes.Control; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ActiveTextBrush"]/*'/> protected virtual Color ActiveTextColor { get { return SystemColors.ControlText; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="TabSeperatorPen"]/*'/> protected virtual Pen TabSeperatorPen { get { return SystemPens.GrayText; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="InactiveTextBrush"]/*'/> protected virtual Color InactiveTextColor { get { return SystemColors.ControlDarkDark; } } #endregion public VS2003DockPaneStrip(DockPane pane) : base(pane) { SetStyle(ControlStyles.ResizeRedraw, true); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SuspendLayout(); Font = SystemInformation.MenuFont; BackColor = Color.WhiteSmoke; m_components = new Container(); m_toolTip = new ToolTip(Components); m_buttonClose = new InertButton(ImageCloseEnabled, ImageCloseDisabled); m_buttonScrollLeft = new InertButton(ImageScrollLeftEnabled, ImageScrollLeftDisabled); m_buttonScrollRight = new InertButton(ImageScrollRightEnabled, ImageScrollRightDisabled); m_buttonClose.ToolTipText = ToolTipClose; m_buttonClose.Anchor = AnchorStyles.Top | AnchorStyles.Right; m_buttonClose.Click += new EventHandler(Close_Click); m_buttonScrollLeft.Enabled = false; m_buttonScrollLeft.RepeatClick = true; m_buttonScrollLeft.ToolTipText = ToolTipScrollLeft; m_buttonScrollLeft.Anchor = AnchorStyles.Top | AnchorStyles.Right; m_buttonScrollLeft.Click += new EventHandler(ScrollLeft_Click); m_buttonScrollRight.Enabled = false; m_buttonScrollRight.RepeatClick = true; m_buttonScrollRight.ToolTipText = ToolTipScrollRight; m_buttonScrollRight.Anchor = AnchorStyles.Top | AnchorStyles.Right; m_buttonScrollRight.Click += new EventHandler(ScrollRight_Click); Controls.AddRange(new Control[] { m_buttonClose, m_buttonScrollLeft, m_buttonScrollRight }); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) { Components.Dispose(); } base.Dispose (disposing); } protected override int MeasureHeight() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return MeasureHeight_ToolWindow(); else return MeasureHeight_Document(); } private int MeasureHeight_ToolWindow() { if (DockPane.IsAutoHide || Tabs.Count <= 1) return 0; int height = Math.Max(Font.Height, ToolWindowImageHeight) + ToolWindowImageGapTop + ToolWindowImageGapBottom; return height; } private int MeasureHeight_Document() { int height = Math.Max(Font.Height + DocumentTabGapTop, ImageCloseEnabled.Height + DocumentButtonGapTop + DocumentButtonGapBottom); return height; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint (e); CalculateTabs(); DrawTabStrip(e.Graphics); } protected override void OnRefreshChanges() { CalculateTabs(); SetInertButtons(); Invalidate(); } protected override GraphicsPath GetOutline(int index) { Point[] pts = new Point[8]; if (Appearance == DockPane.AppearanceStyle.Document) { Rectangle rectTab = GetTabRectangle(index); rectTab.Intersect(TabsRectangle); int y = DockPane.PointToClient(PointToScreen(new Point(0, rectTab.Bottom))).Y; Rectangle rectPaneClient = DockPane.ClientRectangle; pts[0] = DockPane.PointToScreen(new Point(rectPaneClient.Left, y)); pts[1] = PointToScreen(new Point(rectTab.Left, rectTab.Bottom)); pts[2] = PointToScreen(new Point(rectTab.Left, rectTab.Top)); pts[3] = PointToScreen(new Point(rectTab.Right, rectTab.Top)); pts[4] = PointToScreen(new Point(rectTab.Right, rectTab.Bottom)); pts[5] = DockPane.PointToScreen(new Point(rectPaneClient.Right, y)); pts[6] = DockPane.PointToScreen(new Point(rectPaneClient.Right, rectPaneClient.Bottom)); pts[7] = DockPane.PointToScreen(new Point(rectPaneClient.Left, rectPaneClient.Bottom)); } else { Rectangle rectTab = GetTabRectangle(index); rectTab.Intersect(TabsRectangle); int y = DockPane.PointToClient(PointToScreen(new Point(0, rectTab.Top))).Y; Rectangle rectPaneClient = DockPane.ClientRectangle; pts[0] = DockPane.PointToScreen(new Point(rectPaneClient.Left, rectPaneClient.Top)); pts[1] = DockPane.PointToScreen(new Point(rectPaneClient.Right, rectPaneClient.Top)); pts[2] = DockPane.PointToScreen(new Point(rectPaneClient.Right, y)); pts[3] = PointToScreen(new Point(rectTab.Right, rectTab.Top)); pts[4] = PointToScreen(new Point(rectTab.Right, rectTab.Bottom)); pts[5] = PointToScreen(new Point(rectTab.Left, rectTab.Bottom)); pts[6] = PointToScreen(new Point(rectTab.Left, rectTab.Top)); pts[7] = DockPane.PointToScreen(new Point(rectPaneClient.Left, y)); } GraphicsPath path = new GraphicsPath(); path.AddLines(pts); return path; } private void CalculateTabs() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) CalculateTabs_ToolWindow(); else CalculateTabs_Document(); } private void CalculateTabs_ToolWindow() { if (Tabs.Count <= 1 || DockPane.IsAutoHide) return; Rectangle rectTabStrip = ClientRectangle; // Calculate tab widths int countTabs = Tabs.Count; foreach (TabVS2003 tab in Tabs) { tab.MaxWidth = GetTabOriginalWidth(Tabs.IndexOf(tab)); tab.Flag = false; } // Set tab whose max width less than average width bool anyWidthWithinAverage = true; int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight; int totalAllocatedWidth = 0; int averageWidth = totalWidth / countTabs; int remainedTabs = countTabs; for (anyWidthWithinAverage=true; anyWidthWithinAverage && remainedTabs>0;) { anyWidthWithinAverage = false; foreach (TabVS2003 tab in Tabs) { if (tab.Flag) continue; if (tab.MaxWidth <= averageWidth) { tab.Flag = true; tab.TabWidth = tab.MaxWidth; totalAllocatedWidth += tab.TabWidth; anyWidthWithinAverage = true; remainedTabs--; } } if (remainedTabs != 0) averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs; } // If any tab width not set yet, set it to the average width if (remainedTabs > 0) { int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs); foreach (TabVS2003 tab in Tabs) { if (tab.Flag) continue; tab.Flag = true; if (roundUpWidth > 0) { tab.TabWidth = averageWidth + 1; roundUpWidth --; } else tab.TabWidth = averageWidth; } } // Set the X position of the tabs int x = rectTabStrip.X + ToolWindowStripGapLeft; foreach (TabVS2003 tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } private void CalculateTabs_Document() { Rectangle rectTabStrip = TabsRectangle; int totalWidth = 0; foreach (TabVS2003 tab in Tabs) { tab.TabWidth = Math.Min(GetTabOriginalWidth(Tabs.IndexOf(tab)), DocumentTabMaxWidth); totalWidth += tab.TabWidth; } if (totalWidth + OffsetX < rectTabStrip.Width && OffsetX < 0) OffsetX = Math.Min(0, rectTabStrip.Width - totalWidth); int x = rectTabStrip.X + OffsetX; foreach (TabVS2003 tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } protected override void EnsureTabVisible(IDockContent content) { if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content)) return; Rectangle rectTabStrip = TabsRectangle; Rectangle rectTab = GetTabRectangle(Tabs.IndexOf(content)); if (rectTab.Right > rectTabStrip.Right) { OffsetX -= rectTab.Right - rectTabStrip.Right; rectTab.X -= rectTab.Right - rectTabStrip.Right; } if (rectTab.Left < rectTabStrip.Left) OffsetX += rectTabStrip.Left - rectTab.Left; OnRefreshChanges(); } private int GetTabOriginalWidth(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabOriginalWidth_ToolWindow(index); else return GetTabOriginalWidth_Document(index); } private int GetTabOriginalWidth_ToolWindow(int index) { IDockContent content = Tabs[index].Content; using (Graphics g = CreateGraphics()) { Size sizeString = TextRenderer.MeasureText(g, content.DockHandler.TabText, Font); return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft + ToolWindowImageGapRight + ToolWindowTextGapRight; } } private int GetTabOriginalWidth_Document(int index) { IDockContent content = Tabs[index].Content; int height = GetTabRectangle_Document(index).Height; using (Graphics g = CreateGraphics()) { Size sizeText; if (content == DockPane.ActiveContent && DockPane.IsActiveDocumentPane) { using (Font boldFont = new Font(this.Font, FontStyle.Bold)) { sizeText = TextRenderer.MeasureText(g, content.DockHandler.TabText, boldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat); } } else sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, Font, new Size(DocumentTabMaxWidth, height), DocumentTextFormat); if (DockPane.DockPanel.ShowDocumentIcon) return sizeText.Width + DocumentIconWidth + DocumentIconGapLeft; else return sizeText.Width; } } private void DrawTabStrip(Graphics g) { OnBeginDrawTabStrip(); if (Appearance == DockPane.AppearanceStyle.Document) DrawTabStrip_Document(g); else DrawTabStrip_ToolWindow(g); OnEndDrawTabStrip(); } private void DrawTabStrip_Document(Graphics g) { int count = Tabs.Count; if (count == 0) return; Rectangle rectTabStrip = ClientRectangle; g.DrawLine(OutlineOuterPen, rectTabStrip.Left, rectTabStrip.Bottom - 1, rectTabStrip.Right, rectTabStrip.Bottom - 1); // Draw the tabs Rectangle rectTabOnly = TabsRectangle; Rectangle rectTab = Rectangle.Empty; g.SetClip(rectTabOnly); for (int i=0; i<count; i++) { rectTab = GetTabRectangle(i); if (rectTab.IntersectsWith(rectTabOnly)) DrawTab(g, Tabs[i] as TabVS2003, rectTab); } } private void DrawTabStrip_ToolWindow(Graphics g) { Rectangle rectTabStrip = ClientRectangle; g.DrawLine(OutlineInnerPen, rectTabStrip.Left, rectTabStrip.Top, rectTabStrip.Right, rectTabStrip.Top); for (int i=0; i<Tabs.Count; i++) DrawTab(g, Tabs[i] as TabVS2003, GetTabRectangle(i)); } private Rectangle GetTabRectangle(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabRectangle_ToolWindow(index); else return GetTabRectangle_Document(index); } private Rectangle GetTabRectangle_ToolWindow(int index) { Rectangle rectTabStrip = ClientRectangle; TabVS2003 tab = (TabVS2003)(Tabs[index]); return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height); } private Rectangle GetTabRectangle_Document(int index) { Rectangle rectTabStrip = ClientRectangle; TabVS2003 tab = (TabVS2003)Tabs[index]; return new Rectangle(tab.TabX, rectTabStrip.Y + DocumentTabGapTop, tab.TabWidth, rectTabStrip.Height - DocumentTabGapTop); } private void DrawTab(Graphics g, TabVS2003 tab, Rectangle rect) { OnBeginDrawTab(tab); if (Appearance == DockPane.AppearanceStyle.ToolWindow) DrawTab_ToolWindow(g, tab, rect); else DrawTab_Document(g, tab, rect); OnEndDrawTab(tab); } private void DrawTab_ToolWindow(Graphics g, TabVS2003 tab, Rectangle rect) { Rectangle rectIcon = new Rectangle( rect.X + ToolWindowImageGapLeft, rect.Y + rect.Height - 1 - ToolWindowImageGapBottom - ToolWindowImageHeight, ToolWindowImageWidth, ToolWindowImageHeight); Rectangle rectText = rectIcon; rectText.X += rectIcon.Width + ToolWindowImageGapRight; rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft - ToolWindowImageGapRight - ToolWindowTextGapRight; if (DockPane.ActiveContent == tab.Content) { g.FillRectangle(ActiveBackBrush, rect); g.DrawLine(OutlineOuterPen, rect.X, rect.Y, rect.X, rect.Y + rect.Height - 1); g.DrawLine(OutlineInnerPen, rect.X, rect.Y + rect.Height - 1, rect.X + rect.Width - 1, rect.Y + rect.Height - 1); g.DrawLine(OutlineInnerPen, rect.X + rect.Width - 1, rect.Y, rect.X + rect.Width - 1, rect.Y + rect.Height - 1); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, Font, rectText, ActiveTextColor, ToolWindowTextFormat); } else { if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(tab) + 1) g.DrawLine(TabSeperatorPen, rect.X + rect.Width - 1, rect.Y + ToolWindowTabSeperatorGapTop, rect.X + rect.Width - 1, rect.Y + rect.Height - 1 - ToolWindowTabSeperatorGapBottom); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, Font, rectText, InactiveTextColor, ToolWindowTextFormat); } if (rect.Contains(rectIcon)) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } private void DrawTab_Document(Graphics g, TabVS2003 tab, Rectangle rect) { Rectangle rectText = rect; if (DockPane.DockPanel.ShowDocumentIcon) { rectText.X += DocumentIconWidth + DocumentIconGapLeft; rectText.Width -= DocumentIconWidth + DocumentIconGapLeft; } if (DockPane.ActiveContent == tab.Content) { g.FillRectangle(ActiveBackBrush, rect); g.DrawLine(OutlineOuterPen, rect.X, rect.Y, rect.X, rect.Y + rect.Height); g.DrawLine(OutlineOuterPen, rect.X, rect.Y, rect.X + rect.Width - 1, rect.Y); g.DrawLine(OutlineInnerPen, rect.X + rect.Width - 1, rect.Y, rect.X + rect.Width - 1, rect.Y + rect.Height - 1); if (DockPane.DockPanel.ShowDocumentIcon) { Icon icon = (tab.Content as Form).Icon; Rectangle rectIcon = new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + (rect.Height - DocumentIconHeight) / 2, DocumentIconWidth, DocumentIconHeight); g.DrawIcon(tab.ContentForm.Icon, rectIcon); } if (DockPane.IsActiveDocumentPane) { using (Font boldFont = new Font(this.Font, FontStyle.Bold)) { TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, boldFont, rectText, ActiveTextColor, DocumentTextFormat); } } else TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, Font, rectText, InactiveTextColor, DocumentTextFormat); } else { if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(tab) + 1) g.DrawLine(TabSeperatorPen, rect.X + rect.Width - 1, rect.Y, rect.X + rect.Width - 1, rect.Y + rect.Height - 1 - DocumentTabGapTop); if (DockPane.DockPanel.ShowDocumentIcon) { Icon icon = tab.ContentForm.Icon; Rectangle rectIcon = new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + (rect.Height - DocumentIconHeight) / 2, DocumentIconWidth, DocumentIconHeight); g.DrawIcon(tab.ContentForm.Icon, rectIcon); } TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, Font, rectText, InactiveTextColor, DocumentTextFormat); } } private Rectangle TabsRectangle { get { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return ClientRectangle; Rectangle rectWindow = ClientRectangle; int x = rectWindow.X; int y = rectWindow.Y; int width = rectWindow.Width; int height = rectWindow.Height; x += DocumentTabGapLeft; width -= DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + m_buttonClose.Width + m_buttonScrollRight.Width + m_buttonScrollLeft.Width + 2 * DocumentButtonGapBetween; return new Rectangle(x, y, width, height); } } private void ScrollLeft_Click(object sender, EventArgs e) { Rectangle rectTabStrip = TabsRectangle; int index; for (index=0; index<Tabs.Count; index++) if (GetTabRectangle(index).IntersectsWith(rectTabStrip)) break; Rectangle rectTab = GetTabRectangle(index); if (rectTab.Left < rectTabStrip.Left) OffsetX += rectTabStrip.Left - rectTab.Left; else if (index == 0) OffsetX = 0; else OffsetX += rectTabStrip.Left - GetTabRectangle(index - 1).Left; OnRefreshChanges(); } private void ScrollRight_Click(object sender, EventArgs e) { Rectangle rectTabStrip = TabsRectangle; int index; int count = Tabs.Count; for (index=0; index<count; index++) if (GetTabRectangle(index).IntersectsWith(rectTabStrip)) break; if (index + 1 < count) { OffsetX -= GetTabRectangle(index + 1).Left - rectTabStrip.Left; CalculateTabs(); } Rectangle rectLastTab = GetTabRectangle(count - 1); if (rectLastTab.Right < rectTabStrip.Right) OffsetX += rectTabStrip.Right - rectLastTab.Right; OnRefreshChanges(); } private void SetInertButtons() { // Set the visibility of the inert buttons m_buttonScrollLeft.Visible = m_buttonScrollRight.Visible = m_buttonClose.Visible = (DockPane.DockState == DockState.Document); m_buttonClose.ForeColor = m_buttonScrollRight.ForeColor = m_buttonScrollLeft.ForeColor = SystemColors.ControlDarkDark; m_buttonClose.BorderColor = m_buttonScrollRight.BorderColor = m_buttonScrollLeft.BorderColor = SystemColors.ControlDarkDark; // Enable/disable scroll buttons int count = Tabs.Count; Rectangle rectTabOnly = TabsRectangle; Rectangle rectTab = (count == 0) ? Rectangle.Empty : GetTabRectangle(count - 1); m_buttonScrollLeft.Enabled = (OffsetX < 0); m_buttonScrollRight.Enabled = rectTab.Right > rectTabOnly.Right; // show/hide close button if (Appearance == DockPane.AppearanceStyle.ToolWindow) m_buttonClose.Visible = false; else { bool showCloseButton = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButton; if (m_buttonClose.Visible != showCloseButton) { m_buttonClose.Visible = showCloseButton; PerformLayout(); } } } /// <exclude/> protected override void OnLayout(LayoutEventArgs levent) { Rectangle rectTabStrip = ClientRectangle; // Set position and size of the buttons int buttonWidth = ImageCloseEnabled.Width; int buttonHeight = ImageCloseEnabled.Height; int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } Size buttonSize = new Size(buttonWidth, buttonHeight); m_buttonClose.Size = m_buttonScrollLeft.Size = m_buttonScrollRight.Size = buttonSize; int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft - DocumentButtonGapRight - buttonWidth; int y = rectTabStrip.Y + DocumentButtonGapTop; m_buttonClose.Location = new Point(x, y); Point point = m_buttonClose.Location; bool showCloseButton = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButton; if (showCloseButton) point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0); m_buttonScrollRight.Location = point; point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0); m_buttonScrollLeft.Location = point; OnRefreshChanges(); base.OnLayout (levent); } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); } /// <exclude/> protected override int HitTest(Point ptMouse) { Rectangle rectTabStrip = TabsRectangle; for (int i=0; i<Tabs.Count; i++) { Rectangle rectTab = GetTabRectangle(i); rectTab.Intersect(rectTabStrip); if (rectTab.Contains(ptMouse)) return i; } return -1; } /// <exclude/> protected override void OnMouseMove(MouseEventArgs e) { int index = HitTest(PointToClient(Control.MousePosition)); string toolTip = string.Empty; base.OnMouseMove(e); if (index != -1) { Rectangle rectTab = GetTabRectangle(index); if (Tabs[index].Content.DockHandler.ToolTipText != null) toolTip = Tabs[index].Content.DockHandler.ToolTipText; else if (rectTab.Width < GetTabOriginalWidth(index)) toolTip = Tabs[index].Content.DockHandler.TabText; } if (m_toolTip.GetToolTip(this) != toolTip) { m_toolTip.Active = false; m_toolTip.SetToolTip(this, toolTip); m_toolTip.Active = true; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Method[@name="OnBeginDrawTabStrip()"]/*'/> protected virtual void OnBeginDrawTabStrip() { } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Method[@name="OnEndDrawTabStrip()"]/*'/> protected virtual void OnEndDrawTabStrip() { } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Method[@name="OnBeginDrawTab(DockPaneTab)"]/*'/> protected virtual void OnBeginDrawTab(Tab tab) { } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Method[@name="OnEndDrawTab(DockPaneTab)"]/*'/> protected virtual void OnEndDrawTab(Tab tab) { } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Runtime.InteropServices; using System.Threading; namespace Erwine.Leonard.T.GDIPlus { #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member [StructLayout(LayoutKind.Explicit)] public struct Fraction8 : IEquatable<Fraction8>, IComparable<Fraction8>, IFraction<sbyte> { #region Fields public static readonly Fraction8 Zero = new Fraction8(0, 0, 1); [FieldOffset(0)] private int _hashCode; [FieldOffset(0)] private sbyte _wholeNumber; [FieldOffset(1)] private sbyte _numerator; [FieldOffset(2)] private sbyte _denominator; #endregion #region Properties public sbyte WholeNumber { get { return _wholeNumber; } } public sbyte Numerator { get { return _numerator; } } public sbyte Denominator { get { return _denominator; } } IConvertible IFraction.WholeNumber { get { return _wholeNumber; } } IConvertible IFraction.Numerator { get { return _numerator; } } IConvertible IFraction.Denominator { get { return _denominator; } } #endregion #region Constructors public Fraction8(sbyte wholeNumber, sbyte numerator, sbyte denominator) { int n, d; _hashCode = 0; _wholeNumber = (sbyte)(FractionUtil.GetNormalizedRational(wholeNumber, numerator, denominator, out n, out d)); _numerator = (sbyte)n; _denominator = (sbyte)d; } public Fraction8(sbyte numerator, sbyte denominator) { int n, d; _hashCode = 0; _wholeNumber = (sbyte)(FractionUtil.GetNormalizedRational(0, numerator, denominator, out n, out d)); _numerator = (sbyte)n; _denominator = (sbyte)d; } public Fraction8(IFraction other) { _hashCode = 0; sbyte numerator, denominator; _wholeNumber = FractionUtil.GetNormalizedRational8(FractionUtil.ToSByte(other.WholeNumber), FractionUtil.ToSByte(other.Numerator), FractionUtil.ToSByte(other.Denominator, 1), out numerator, out denominator); _numerator = numerator; _denominator = denominator; } public Fraction8(sbyte wholeNumber) { _hashCode = 0; _wholeNumber = wholeNumber; _numerator = 0; _denominator = 1; } #endregion #region Add public IFraction<sbyte> Add(sbyte wholeNumber, sbyte numerator, sbyte denominator) { throw new NotImplementedException(); } public IFraction<sbyte> Add(sbyte numerator, sbyte denominator) { throw new NotImplementedException(); } public IFraction<sbyte> Add(IFraction<sbyte> other) { throw new NotImplementedException(); } public IFraction<sbyte> Add(sbyte wholeNumber) { throw new NotImplementedException(); } public IFraction Add(IFraction other) { throw new NotImplementedException(); } #endregion #region As* public IFraction<sbyte> AsInverted() { throw new NotImplementedException(); } IFraction IFraction.AsInverted() { throw new NotImplementedException(); } public sbyte AsRoundedValue() { throw new NotImplementedException(); } #endregion #region CompareTo public int CompareTo(Fraction8 other) { throw new NotImplementedException(); } public int CompareTo(IFraction<sbyte> other) { throw new NotImplementedException(); } public int CompareTo(IFraction other) { throw new NotImplementedException(); } public int CompareTo(object obj) { throw new NotImplementedException(); } #endregion #region Divide public IFraction<sbyte> Divide(sbyte wholeNumber, sbyte numerator, sbyte denominator) { throw new NotImplementedException(); } public IFraction<sbyte> Divide(sbyte numerator, sbyte denominator) { throw new NotImplementedException(); } public IFraction<sbyte> Divide(IFraction<sbyte> other) { throw new NotImplementedException(); } public IFraction<sbyte> Divide(sbyte wholeNumber) { throw new NotImplementedException(); } public IFraction Divide(IFraction other) { throw new NotImplementedException(); } #endregion #region Equals public bool Equals(Fraction8 other) { throw new NotImplementedException(); } public bool Equals(IFraction<sbyte> other) { throw new NotImplementedException(); } public bool Equals(IFraction other) { throw new NotImplementedException(); } public override bool Equals(object obj) { throw new NotImplementedException(); } #endregion #region Get*UnderlyingValue public IComparable GetMaxUnderlyingValue() { throw new NotImplementedException(); } public IComparable GetMinUnderlyingValue() { throw new NotImplementedException(); } #endregion #region Multiply public IFraction<sbyte> Multiply(sbyte wholeNumber, sbyte numerator, sbyte denominator) { throw new NotImplementedException(); } public IFraction<sbyte> Multiply(sbyte numerator, sbyte denominator) { throw new NotImplementedException(); } public IFraction<sbyte> Multiply(IFraction<sbyte> other) { throw new NotImplementedException(); } public IFraction<sbyte> Multiply(sbyte wholeNumber) { throw new NotImplementedException(); } public IFraction Multiply(IFraction other) { throw new NotImplementedException(); } #endregion #region Subtract public IFraction<sbyte> Subtract(sbyte wholeNumber, sbyte numerator, sbyte denominator) { throw new NotImplementedException(); } public IFraction<sbyte> Subtract(sbyte numerator, sbyte denominator) { throw new NotImplementedException(); } public IFraction<sbyte> Subtract(IFraction<sbyte> other) { throw new NotImplementedException(); } public IFraction<sbyte> Subtract(sbyte wholeNumber) { throw new NotImplementedException(); } public IFraction Subtract(IFraction other) { throw new NotImplementedException(); } #endregion #region To* public float ToSingle() { return (_denominator == 0) ? 0.0f : Convert.ToSingle(_wholeNumber) + (Convert.ToSingle(_numerator) / Convert.ToSingle(_denominator)); } public double ToDouble() { return (_denominator == 0) ? 0.0 : Convert.ToDouble(_wholeNumber) + (Convert.ToDouble(_numerator) / Convert.ToDouble(_denominator)); } public decimal ToDecimal() { return (_denominator == 0) ? 0.0M : Convert.ToDecimal(_wholeNumber) + (Convert.ToDecimal(_numerator) / Convert.ToDecimal(_denominator)); } public override string ToString() { return ToString(null); } private string ToString(IFormatProvider provider) { if (provider == null) provider = System.Globalization.CultureInfo.CurrentCulture; return (_numerator == 0 || _denominator == 0) ? _wholeNumber.ToString(provider) : ((_wholeNumber == 0) ? _numerator.ToString(provider) + "/" + _denominator.ToString(provider) : _wholeNumber.ToString(provider) + " " + _numerator.ToString(provider) + "/" + _denominator.ToString(provider)); } #endregion public override int GetHashCode() { throw new NotImplementedException(); } #region IConvertible Explicit Implementation TypeCode IConvertible.GetTypeCode() { return TypeCode.Double; } bool IConvertible.ToBoolean(IFormatProvider provider) { return ((IConvertible)ToDouble()).ToBoolean(provider); } char IConvertible.ToChar(IFormatProvider provider) { return ((IConvertible)ToDouble()).ToChar(provider); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return ((IConvertible)ToDouble()).ToSByte(provider); } byte IConvertible.ToByte(IFormatProvider provider) { return ((IConvertible)ToDouble()).ToByte(provider); } short IConvertible.ToInt16(IFormatProvider provider) { return ((IConvertible)ToDouble()).ToInt16(provider); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return ((IConvertible)ToDouble()).ToUInt16(provider); } int IConvertible.ToInt32(IFormatProvider provider) { return ((IConvertible)ToDouble()).ToInt32(provider); } uint IConvertible.ToUInt32(IFormatProvider provider) { return ((IConvertible)ToDouble()).ToUInt32(provider); } long IConvertible.ToInt64(IFormatProvider provider) { return ((IConvertible)ToDouble()).ToInt64(provider); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return ((IConvertible)ToDouble()).ToUInt64(provider); } float IConvertible.ToSingle(IFormatProvider provider) { return ToSingle(); } double IConvertible.ToDouble(IFormatProvider provider) { return ToDouble(); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return ToDecimal(); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { return ((IConvertible)ToDouble()).ToDateTime(provider); } string IConvertible.ToString(IFormatProvider provider) { return ToString(provider); } object IConvertible.ToType(Type conversionType, IFormatProvider provider) { return ((IConvertible)ToDouble()).ToType(conversionType, provider); } #endregion } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member }
using System; using System.Reflection; using System.Web.Mvc; using Orchard.Blogs.Extensions; using Orchard.Blogs.Models; using Orchard.Blogs.Services; using Orchard.ContentManagement; using Orchard.ContentManagement.Aspects; using Orchard.Core.Contents.Settings; using Orchard.Localization; using Orchard.Mvc; using Orchard.Mvc.AntiForgery; using Orchard.Mvc.Extensions; using Orchard.UI.Admin; using Orchard.UI.Notify; namespace Orchard.Blogs.Controllers { /// <summary> /// TODO: (PH:Autoroute) This replicates a whole lot of Core.Contents functionality. All we actually need to do is take the BlogId from the query string in the BlogPostPartDriver, and remove /// helper extensions from UrlHelperExtensions. /// </summary> [ValidateInput(false), Admin] public class BlogPostAdminController : Controller, IUpdateModel { private readonly IBlogService _blogService; private readonly IBlogPostService _blogPostService; public BlogPostAdminController(IOrchardServices services, IBlogService blogService, IBlogPostService blogPostService) { Services = services; _blogService = blogService; _blogPostService = blogPostService; T = NullLocalizer.Instance; } public IOrchardServices Services { get; set; } public Localizer T { get; set; } public ActionResult Create(int blogId) { var blog = _blogService.Get(blogId, VersionOptions.Latest).As<BlogPart>(); if (blog == null) return HttpNotFound(); var blogPost = Services.ContentManager.New<BlogPostPart>("BlogPost"); blogPost.BlogPart = blog; if (!Services.Authorizer.Authorize(Permissions.EditBlogPost, blog, T("Not allowed to create blog post"))) return new HttpUnauthorizedResult(); dynamic model = Services.ContentManager.BuildEditor(blogPost); // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation. return View((object)model); } [HttpPost, ActionName("Create")] [FormValueRequired("submit.Save")] public ActionResult CreatePOST(int blogId) { return CreatePOST(blogId, false); } [HttpPost, ActionName("Create")] [FormValueRequired("submit.Publish")] public ActionResult CreateAndPublishPOST(int blogId) { if (!Services.Authorizer.Authorize(Permissions.PublishOwnBlogPost, T("Couldn't create content"))) return new HttpUnauthorizedResult(); return CreatePOST(blogId, true); } private ActionResult CreatePOST(int blogId, bool publish = false) { var blog = _blogService.Get(blogId, VersionOptions.Latest).As<BlogPart>(); if (blog == null) return HttpNotFound(); var blogPost = Services.ContentManager.New<BlogPostPart>("BlogPost"); blogPost.BlogPart = blog; if (!Services.Authorizer.Authorize(Permissions.EditBlogPost, blog, T("Couldn't create blog post"))) return new HttpUnauthorizedResult(); Services.ContentManager.Create(blogPost, VersionOptions.Draft); var model = Services.ContentManager.UpdateEditor(blogPost, this); if (!ModelState.IsValid) { Services.TransactionManager.Cancel(); // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation. return View((object)model); } if (publish) { if (!Services.Authorizer.Authorize(Permissions.PublishBlogPost, blog.ContentItem, T("Couldn't publish blog post"))) return new HttpUnauthorizedResult(); Services.ContentManager.Publish(blogPost.ContentItem); } Services.Notifier.Information(T("Your {0} has been created.", blogPost.TypeDefinition.DisplayName)); return Redirect(Url.BlogPostEdit(blogPost)); } //todo: the content shape template has extra bits that the core contents module does not (remove draft functionality) //todo: - move this extra functionality there or somewhere else that's appropriate? public ActionResult Edit(int blogId, int postId) { var blog = _blogService.Get(blogId, VersionOptions.Latest); if (blog == null) return HttpNotFound(); var post = _blogPostService.Get(postId, VersionOptions.Latest); if (post == null) return HttpNotFound(); if (!Services.Authorizer.Authorize(Permissions.EditBlogPost, post, T("Couldn't edit blog post"))) return new HttpUnauthorizedResult(); dynamic model = Services.ContentManager.BuildEditor(post); // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation. return View((object)model); } [HttpPost, ActionName("Edit")] [FormValueRequired("submit.Save")] public ActionResult EditPOST(int blogId, int postId, string returnUrl) { return EditPOST(blogId, postId, returnUrl, contentItem => { if (!contentItem.Has<IPublishingControlAspect>() && !contentItem.TypeDefinition.Settings.GetModel<ContentTypeSettings>().Draftable) Services.ContentManager.Publish(contentItem); }); } [HttpPost, ActionName("Edit")] [FormValueRequired("submit.Publish")] public ActionResult EditAndPublishPOST(int blogId, int postId, string returnUrl) { var blog = _blogService.Get(blogId, VersionOptions.Latest); if (blog == null) return HttpNotFound(); // Get draft (create a new version if needed) var blogPost = _blogPostService.Get(postId, VersionOptions.DraftRequired); if (blogPost == null) return HttpNotFound(); if (!Services.Authorizer.Authorize(Permissions.PublishBlogPost, blogPost, T("Couldn't publish blog post"))) return new HttpUnauthorizedResult(); return EditPOST(blogId, postId, returnUrl, contentItem => Services.ContentManager.Publish(contentItem)); } public ActionResult EditPOST(int blogId, int postId, string returnUrl, Action<ContentItem> conditionallyPublish) { var blog = _blogService.Get(blogId, VersionOptions.Latest); if (blog == null) return HttpNotFound(); // Get draft (create a new version if needed) var blogPost = _blogPostService.Get(postId, VersionOptions.DraftRequired); if (blogPost == null) return HttpNotFound(); if (!Services.Authorizer.Authorize(Permissions.EditBlogPost, blogPost, T("Couldn't edit blog post"))) return new HttpUnauthorizedResult(); // Validate form input var model = Services.ContentManager.UpdateEditor(blogPost, this); if (!ModelState.IsValid) { Services.TransactionManager.Cancel(); // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation. return View((object)model); } conditionallyPublish(blogPost.ContentItem); Services.Notifier.Information(T("Your {0} has been saved.", blogPost.TypeDefinition.DisplayName)); return this.RedirectLocal(returnUrl, Url.BlogPostEdit(blogPost)); } [ValidateAntiForgeryTokenOrchard] public ActionResult DiscardDraft(int id) { // get the current draft version var draft = Services.ContentManager.Get(id, VersionOptions.Draft); if (draft == null) { Services.Notifier.Information(T("There is no draft to discard.")); return RedirectToEdit(id); } // check edit permission if (!Services.Authorizer.Authorize(Permissions.EditBlogPost, draft, T("Couldn't discard blog post draft"))) return new HttpUnauthorizedResult(); // locate the published revision to revert onto var published = Services.ContentManager.Get(id, VersionOptions.Published); if (published == null) { Services.Notifier.Information(T("Can not discard draft on unpublished blog post.")); return RedirectToEdit(draft); } // marking the previously published version as the latest // has the effect of discarding the draft but keeping the history draft.VersionRecord.Latest = false; published.VersionRecord.Latest = true; Services.Notifier.Information(T("Blog post draft version discarded")); return RedirectToEdit(published); } ActionResult RedirectToEdit(int id) { return RedirectToEdit(Services.ContentManager.GetLatest<BlogPostPart>(id)); } ActionResult RedirectToEdit(IContent item) { if (item == null || item.As<BlogPostPart>() == null) return HttpNotFound(); return RedirectToAction("Edit", new { BlogId = item.As<BlogPostPart>().BlogPart.Id, PostId = item.ContentItem.Id }); } [ValidateAntiForgeryTokenOrchard] public ActionResult Delete(int blogId, int postId) { //refactoring: test PublishBlogPost/PublishBlogPost in addition if published var blog = _blogService.Get(blogId, VersionOptions.Latest); if (blog == null) return HttpNotFound(); var post = _blogPostService.Get(postId, VersionOptions.Latest); if (post == null) return HttpNotFound(); if (!Services.Authorizer.Authorize(Permissions.DeleteBlogPost, post, T("Couldn't delete blog post"))) return new HttpUnauthorizedResult(); _blogPostService.Delete(post); Services.Notifier.Information(T("Blog post was successfully deleted")); return Redirect(Url.BlogForAdmin(blog.As<BlogPart>())); } [ValidateAntiForgeryTokenOrchard] public ActionResult Publish(int blogId, int postId) { var blog = _blogService.Get(blogId, VersionOptions.Latest); if (blog == null) return HttpNotFound(); var post = _blogPostService.Get(postId, VersionOptions.Latest); if (post == null) return HttpNotFound(); if (!Services.Authorizer.Authorize(Permissions.PublishBlogPost, post, T("Couldn't publish blog post"))) return new HttpUnauthorizedResult(); _blogPostService.Publish(post); Services.Notifier.Information(T("Blog post successfully published.")); return Redirect(Url.BlogForAdmin(blog.As<BlogPart>())); } [ValidateAntiForgeryTokenOrchard] public ActionResult Unpublish(int blogId, int postId) { var blog = _blogService.Get(blogId, VersionOptions.Latest); if (blog == null) return HttpNotFound(); var post = _blogPostService.Get(postId, VersionOptions.Latest); if (post == null) return HttpNotFound(); if (!Services.Authorizer.Authorize(Permissions.PublishBlogPost, post, T("Couldn't unpublish blog post"))) return new HttpUnauthorizedResult(); _blogPostService.Unpublish(post); Services.Notifier.Information(T("Blog post successfully unpublished.")); return Redirect(Url.BlogForAdmin(blog.As<BlogPart>())); } bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) { return TryUpdateModel(model, prefix, includeProperties, excludeProperties); } void IUpdateModel.AddModelError(string key, LocalizedString errorMessage) { ModelState.AddModelError(key, errorMessage.ToString()); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; using Microsoft.WindowsAzure; namespace Microsoft.Azure.Management.Automation { public static partial class RunbookOperationsExtensions { /// <summary> /// Create a runbook schedule link. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create runbook schedule /// link operation. /// </param> /// <returns> /// The response model for the create runbook schedule link operation. /// </returns> public static RunbookCreateScheduleLinkResponse CreateScheduleLink(this IRunbookOperations operations, string automationAccount, RunbookCreateScheduleLinkParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).CreateScheduleLinkAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create a runbook schedule link. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create runbook schedule /// link operation. /// </param> /// <returns> /// The response model for the create runbook schedule link operation. /// </returns> public static Task<RunbookCreateScheduleLinkResponse> CreateScheduleLinkAsync(this IRunbookOperations operations, string automationAccount, RunbookCreateScheduleLinkParameters parameters) { return operations.CreateScheduleLinkAsync(automationAccount, parameters, CancellationToken.None); } /// <summary> /// Delete the runbook identified by runbookId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookId'> /// Required. The runbook id. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse Delete(this IRunbookOperations operations, string automationAccount, string runbookId) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).DeleteAsync(automationAccount, runbookId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete the runbook identified by runbookId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookId'> /// Required. The runbook id. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> DeleteAsync(this IRunbookOperations operations, string automationAccount, string runbookId) { return operations.DeleteAsync(automationAccount, runbookId, CancellationToken.None); } /// <summary> /// Delete the runbook schedule link. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the delete runbook schedule /// link operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse DeleteScheduleLink(this IRunbookOperations operations, string automationAccount, RunbookDeleteScheduleLinkParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).DeleteScheduleLinkAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete the runbook schedule link. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the delete runbook schedule /// link operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> DeleteScheduleLinkAsync(this IRunbookOperations operations, string automationAccount, RunbookDeleteScheduleLinkParameters parameters) { return operations.DeleteScheduleLinkAsync(automationAccount, parameters, CancellationToken.None); } /// <summary> /// Edit the runbook identified by runbookId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookId'> /// Required. The runbook id. /// </param> /// <returns> /// The response model for the edit runbook operation. /// </returns> public static RunbookEditResponse Edit(this IRunbookOperations operations, string automationAccount, string runbookId) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).EditAsync(automationAccount, runbookId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Edit the runbook identified by runbookId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookId'> /// Required. The runbook id. /// </param> /// <returns> /// The response model for the edit runbook operation. /// </returns> public static Task<RunbookEditResponse> EditAsync(this IRunbookOperations operations, string automationAccount, string runbookId) { return operations.EditAsync(automationAccount, runbookId, CancellationToken.None); } /// <summary> /// Retrieve the runbook identified by runbookId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookId'> /// Required. The runbook id. /// </param> /// <returns> /// The response model for the get runbook operation. /// </returns> public static RunbookGetResponse Get(this IRunbookOperations operations, string automationAccount, string runbookId) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).GetAsync(automationAccount, runbookId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the runbook identified by runbookId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookId'> /// Required. The runbook id. /// </param> /// <returns> /// The response model for the get runbook operation. /// </returns> public static Task<RunbookGetResponse> GetAsync(this IRunbookOperations operations, string automationAccount, string runbookId) { return operations.GetAsync(automationAccount, runbookId, CancellationToken.None); } /// <summary> /// Retrieve the runbook identified by runbookId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookId'> /// Required. The runbook id. /// </param> /// <returns> /// The response model for the get runbook operation. /// </returns> public static RunbookGetResponse GetWithSchedules(this IRunbookOperations operations, string automationAccount, string runbookId) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).GetWithSchedulesAsync(automationAccount, runbookId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the runbook identified by runbookId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookId'> /// Required. The runbook id. /// </param> /// <returns> /// The response model for the get runbook operation. /// </returns> public static Task<RunbookGetResponse> GetWithSchedulesAsync(this IRunbookOperations operations, string automationAccount, string runbookId) { return operations.GetWithSchedulesAsync(automationAccount, runbookId, CancellationToken.None); } /// <summary> /// Retrieve a list of one runbook identified by runbookName. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the list runbook operation. /// </returns> public static RunbookListResponse ListByName(this IRunbookOperations operations, string automationAccount, string runbookName) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).ListByNameAsync(automationAccount, runbookName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of one runbook identified by runbookName. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the list runbook operation. /// </returns> public static Task<RunbookListResponse> ListByNameAsync(this IRunbookOperations operations, string automationAccount, string runbookName) { return operations.ListByNameAsync(automationAccount, runbookName, CancellationToken.None); } /// <summary> /// Retrieve a list of one runbook identified by runbookName. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the list runbook operation. /// </returns> public static RunbookListResponse ListByNameWithSchedules(this IRunbookOperations operations, string automationAccount, string runbookName) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).ListByNameWithSchedulesAsync(automationAccount, runbookName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of one runbook identified by runbookName. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the list runbook operation. /// </returns> public static Task<RunbookListResponse> ListByNameWithSchedulesAsync(this IRunbookOperations operations, string automationAccount, string runbookName) { return operations.ListByNameWithSchedulesAsync(automationAccount, runbookName, CancellationToken.None); } /// <summary> /// Retrieve a list of runbooks which run on the schedule. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the list runbook by schedule /// name operation. /// </param> /// <returns> /// The response model for the list runbook operation. /// </returns> public static RunbookListResponse ListByScheduleName(this IRunbookOperations operations, string automationAccount, RunbookListByScheduleNameParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).ListByScheduleNameAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of runbooks which run on the schedule. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the list runbook by schedule /// name operation. /// </param> /// <returns> /// The response model for the list runbook operation. /// </returns> public static Task<RunbookListResponse> ListByScheduleNameAsync(this IRunbookOperations operations, string automationAccount, RunbookListByScheduleNameParameters parameters) { return operations.ListByScheduleNameAsync(automationAccount, parameters, CancellationToken.None); } /// <summary> /// Retrieve a list of runbooks which run on the schedule. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the list runbook by schedule /// name operation. /// </param> /// <returns> /// The response model for the list runbook operation. /// </returns> public static RunbookListResponse ListByScheduleNameWithSchedules(this IRunbookOperations operations, string automationAccount, RunbookListByScheduleNameParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).ListByScheduleNameWithSchedulesAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of runbooks which run on the schedule. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the list runbook by schedule /// name operation. /// </param> /// <returns> /// The response model for the list runbook operation. /// </returns> public static Task<RunbookListResponse> ListByScheduleNameWithSchedulesAsync(this IRunbookOperations operations, string automationAccount, RunbookListByScheduleNameParameters parameters) { return operations.ListByScheduleNameWithSchedulesAsync(automationAccount, parameters, CancellationToken.None); } /// <summary> /// Retrieve a list of runbooks for the given automation account. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='skipToken'> /// Optional. The skip token. /// </param> /// <returns> /// The response model for the list runbook operation. /// </returns> public static RunbookListResponse ListWithSchedules(this IRunbookOperations operations, string automationAccount, string skipToken) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).ListWithSchedulesAsync(automationAccount, skipToken); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of runbooks for the given automation account. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='skipToken'> /// Optional. The skip token. /// </param> /// <returns> /// The response model for the list runbook operation. /// </returns> public static Task<RunbookListResponse> ListWithSchedulesAsync(this IRunbookOperations operations, string automationAccount, string skipToken) { return operations.ListWithSchedulesAsync(automationAccount, skipToken, CancellationToken.None); } /// <summary> /// Publish the runbook identified by runbookId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the publish runbook operation. /// </param> /// <returns> /// The response model for the publish runbook operation. /// </returns> public static RunbookPublishResponse Publish(this IRunbookOperations operations, string automationAccount, RunbookPublishParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).PublishAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Publish the runbook identified by runbookId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the publish runbook operation. /// </param> /// <returns> /// The response model for the publish runbook operation. /// </returns> public static Task<RunbookPublishResponse> PublishAsync(this IRunbookOperations operations, string automationAccount, RunbookPublishParameters parameters) { return operations.PublishAsync(automationAccount, parameters, CancellationToken.None); } /// <summary> /// Delete the runbook identified by runbookId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the start runbook operation. /// </param> /// <returns> /// The response model for the start runbook operation. /// </returns> public static RunbookStartResponse Start(this IRunbookOperations operations, string automationAccount, RunbookStartParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).StartAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete the runbook identified by runbookId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the start runbook operation. /// </param> /// <returns> /// The response model for the start runbook operation. /// </returns> public static Task<RunbookStartResponse> StartAsync(this IRunbookOperations operations, string automationAccount, RunbookStartParameters parameters) { return operations.StartAsync(automationAccount, parameters, CancellationToken.None); } /// <summary> /// Update the runbook identified by runbookId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the update runbook operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse Update(this IRunbookOperations operations, string automationAccount, RunbookUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).UpdateAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update the runbook identified by runbookId. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the update runbook operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> UpdateAsync(this IRunbookOperations operations, string automationAccount, RunbookUpdateParameters parameters) { return operations.UpdateAsync(automationAccount, parameters, CancellationToken.None); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // Implementation of CallContext ... currently leverages off // the LocalDataStore facility. namespace System.Runtime.Remoting.Messaging{ using System.Threading; using System.Runtime.Remoting; using System.Security.Principal; using System.Collections; using System.Runtime.Serialization; using System.Security.Permissions; // This class exposes the API for the users of call context. All methods // in CallContext are static and operate upon the call context in the Thread. // NOTE: CallContext is a specialized form of something that behaves like // TLS for method calls. However, since the call objects may get serialized // and deserialized along the path, it is tough to guarantee identity // preservation. // The LogicalCallContext class has all the actual functionality. We have // to use this scheme because Remoting message sinks etc do need to have // the distinction between the call context on the physical thread and // the call context that the remoting message actually carries. In most cases // they will operate on the message's call context and hence the latter // exposes the same set of methods as instance methods. // Only statics does not need to marked with the serializable attribute [System.Security.SecurityCritical] // auto-generated_required [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public sealed class CallContext { private CallContext() { } // Sets the given logical call context object on the thread. // Returns the previous one. internal static LogicalCallContext SetLogicalCallContext( LogicalCallContext callCtx) { ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext(); LogicalCallContext prev = ec.LogicalCallContext; ec.LogicalCallContext = callCtx; return prev; } /*========================================================================= ** Frees a named data slot. =========================================================================*/ [System.Security.SecurityCritical] // auto-generated public static void FreeNamedDataSlot(String name) { ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext(); ec.LogicalCallContext.FreeNamedDataSlot(name); ec.IllogicalCallContext.FreeNamedDataSlot(name); } /*========================================================================= ** Get data on the logical call context =========================================================================*/ [System.Security.SecurityCritical] // auto-generated public static Object LogicalGetData(String name) { return Thread.CurrentThread.GetExecutionContextReader().LogicalCallContext.GetData(name); } /*========================================================================= ** Get data on the illogical call context =========================================================================*/ private static Object IllogicalGetData(String name) { return Thread.CurrentThread.GetExecutionContextReader().IllogicalCallContext.GetData(name); } internal static IPrincipal Principal { [System.Security.SecurityCritical] // auto-generated get { return Thread.CurrentThread.GetExecutionContextReader().LogicalCallContext.Principal; } [System.Security.SecurityCritical] // auto-generated set { Thread.CurrentThread. GetMutableExecutionContext().LogicalCallContext.Principal = value; } } public static Object HostContext { [System.Security.SecurityCritical] // auto-generated get { ExecutionContext.Reader ec = Thread.CurrentThread.GetExecutionContextReader(); Object hC = ec.IllogicalCallContext.HostContext; if (hC == null) hC = ec.LogicalCallContext.HostContext; return hC; } [System.Security.SecurityCritical] // auto-generated_required set { ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext(); if (value is ILogicalThreadAffinative) { ec.IllogicalCallContext.HostContext = null; ec.LogicalCallContext.HostContext = value; } else { ec.IllogicalCallContext.HostContext = value; ec.LogicalCallContext.HostContext = null; } } } // < [System.Security.SecurityCritical] // auto-generated public static Object GetData(String name) { Object o = LogicalGetData(name); if (o == null) { return IllogicalGetData(name); } else { return o; } } [System.Security.SecurityCritical] // auto-generated public static void SetData(String name, Object data) { if (data is ILogicalThreadAffinative) { LogicalSetData(name, data); } else { ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext(); ec.LogicalCallContext.FreeNamedDataSlot(name); ec.IllogicalCallContext.SetData(name, data); } } [System.Security.SecurityCritical] // auto-generated public static void LogicalSetData(String name, Object data) { ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext(); ec.IllogicalCallContext.FreeNamedDataSlot(name); ec.LogicalCallContext.SetData(name, data); } [System.Security.SecurityCritical] // auto-generated public static Header[] GetHeaders() { // Header is mutable, so we need to get these from a mutable ExecutionContext LogicalCallContext lcc = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext; return lcc.InternalGetHeaders(); } // GetHeaders [System.Security.SecurityCritical] // auto-generated public static void SetHeaders(Header[] headers) { LogicalCallContext lcc = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext; lcc.InternalSetHeaders(headers); } // SetHeaders } // class CallContext [System.Runtime.InteropServices.ComVisible(true)] public interface ILogicalThreadAffinative { } internal class IllogicalCallContext { private Hashtable m_Datastore; private Object m_HostContext; internal struct Reader { IllogicalCallContext m_ctx; public Reader(IllogicalCallContext ctx) { m_ctx = ctx; } public bool IsNull { get { return m_ctx == null; } } [System.Security.SecurityCritical] public Object GetData(String name) { return IsNull ? null : m_ctx.GetData(name); } public Object HostContext { get { return IsNull ? null : m_ctx.HostContext; } } } private Hashtable Datastore { get { if (null == m_Datastore) { // The local store has not yet been created for this thread. m_Datastore = new Hashtable(); } return m_Datastore; } } internal Object HostContext { get { return m_HostContext; } set { m_HostContext = value; } } internal bool HasUserData { get { return ((m_Datastore != null) && (m_Datastore.Count > 0));} } /*========================================================================= ** Frees a named data slot. =========================================================================*/ public void FreeNamedDataSlot(String name) { Datastore.Remove(name); } public Object GetData(String name) { return Datastore[name]; } public void SetData(String name, Object data) { Datastore[name] = data; } public IllogicalCallContext CreateCopy() { IllogicalCallContext ilcc = new IllogicalCallContext(); ilcc.HostContext = this.HostContext; if (HasUserData) { IDictionaryEnumerator de = this.m_Datastore.GetEnumerator(); while (de.MoveNext()) { ilcc.Datastore[(String)de.Key] = de.Value; } } return ilcc; } } // This class handles the actual call context functionality. It leverages on the // implementation of local data store ... except that the local store manager is // not static. That is to say, allocating a slot in one call context has no effect // on another call contexts. Different call contexts are entirely unrelated. [System.Security.SecurityCritical] // auto-generated_required [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public sealed class LogicalCallContext : ISerializable, ICloneable { // Private static data private static Type s_callContextType = typeof(LogicalCallContext); private const string s_CorrelationMgrSlotName = "System.Diagnostics.Trace.CorrelationManagerSlot"; /*========================================================================= ** Data accessed from managed code that needs to be defined in ** LogicalCallContextObject to maintain alignment between the two classes. ** DON'T CHANGE THESE UNLESS YOU MODIFY LogicalContextObject in vm\object.h =========================================================================*/ // Private member data private Hashtable m_Datastore; private CallContextRemotingData m_RemotingData = null; private CallContextSecurityData m_SecurityData = null; private Object m_HostContext = null; private bool m_IsCorrelationMgr = false; // _sendHeaders is for Headers that should be sent out on the next call. // _recvHeaders are for Headers that came from a response. private Header[] _sendHeaders = null; private Header[] _recvHeaders = null; internal LogicalCallContext() { } internal struct Reader { LogicalCallContext m_ctx; public Reader(LogicalCallContext ctx) { m_ctx = ctx; } public bool IsNull { get { return m_ctx == null; } } public bool HasInfo { get { return IsNull ? false : m_ctx.HasInfo; } } public LogicalCallContext Clone() { return (LogicalCallContext)m_ctx.Clone(); } public IPrincipal Principal { get { return IsNull ? null : m_ctx.Principal; } } [System.Security.SecurityCritical] public Object GetData(String name) { return IsNull ? null : m_ctx.GetData(name); } public Object HostContext { get { return IsNull ? null : m_ctx.HostContext; } } } [System.Security.SecurityCritical] // auto-generated internal LogicalCallContext(SerializationInfo info, StreamingContext context) { SerializationInfoEnumerator e = info.GetEnumerator(); while (e.MoveNext()) { if (e.Name.Equals("__RemotingData")) { m_RemotingData = (CallContextRemotingData) e.Value; } else if (e.Name.Equals("__SecurityData")) { if (context.State == StreamingContextStates.CrossAppDomain) { m_SecurityData = (CallContextSecurityData) e.Value; } else { BCLDebug.Assert(false, "Security data should only be serialized in cross appdomain case."); } } else if (e.Name.Equals("__HostContext")) { m_HostContext = e.Value; } else if (e.Name.Equals("__CorrelationMgrSlotPresent")) { m_IsCorrelationMgr = (bool)e.Value; } else { Datastore[e.Name] = e.Value; } } } [System.Security.SecurityCritical] // auto-generated_required public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); info.SetType(s_callContextType); if (m_RemotingData != null) { info.AddValue("__RemotingData", m_RemotingData); } if (m_SecurityData != null) { if (context.State == StreamingContextStates.CrossAppDomain) { info.AddValue("__SecurityData", m_SecurityData); } } if (m_HostContext != null) { info.AddValue("__HostContext", m_HostContext); } if (m_IsCorrelationMgr) { info.AddValue("__CorrelationMgrSlotPresent", m_IsCorrelationMgr); } if (HasUserData) { IDictionaryEnumerator de = m_Datastore.GetEnumerator(); while (de.MoveNext()) { info.AddValue((String)de.Key, de.Value); } } } // ICloneable::Clone // Used to create a deep copy of the call context when an async // call starts. // < [System.Security.SecuritySafeCritical] // overrides public transparent member public Object Clone() { LogicalCallContext lc = new LogicalCallContext(); if (m_RemotingData != null) lc.m_RemotingData = (CallContextRemotingData)m_RemotingData.Clone(); if (m_SecurityData != null) lc.m_SecurityData = (CallContextSecurityData)m_SecurityData.Clone(); if (m_HostContext != null) lc.m_HostContext = m_HostContext; lc.m_IsCorrelationMgr = m_IsCorrelationMgr; if (HasUserData) { IDictionaryEnumerator de = m_Datastore.GetEnumerator(); if (!m_IsCorrelationMgr) { while (de.MoveNext()) { lc.Datastore[(String)de.Key] = de.Value; } } else { while (de.MoveNext()) { String key = (String)de.Key; // Deep clone "System.Diagnostics.Trace.CorrelationManagerSlot" if (key.Equals(s_CorrelationMgrSlotName)) { lc.Datastore[key] = ((ICloneable)de.Value).Clone(); } else lc.Datastore[key] = de.Value; } } } return lc; } // Used to do a (limited) merge the call context from a returning async call [System.Security.SecurityCritical] // auto-generated internal void Merge(LogicalCallContext lc) { // we ignore the RemotingData & SecurityData // and only merge the user sections of the two call contexts // the idea being that if the original call had any // identity/remoting callID that should remain unchanged // If we have a non-null callContext and it is not the same // as the one on the current thread (can happen in x-context async) // and there is any userData in the callContext, do the merge if ((lc != null) && (this != lc) && lc.HasUserData) { IDictionaryEnumerator de = lc.Datastore.GetEnumerator(); while (de.MoveNext()) { Datastore[(String)de.Key] = de.Value; } } } public bool HasInfo { [System.Security.SecurityCritical] // auto-generated get { bool fInfo = false; // Set the flag to true if there is either remoting data, or // security data or user data if( (m_RemotingData != null && m_RemotingData.HasInfo) || (m_SecurityData != null && m_SecurityData.HasInfo) || (m_HostContext != null) || HasUserData ) { fInfo = true; } return fInfo; } } private bool HasUserData { get { return ((m_Datastore != null) && (m_Datastore.Count > 0));} } internal CallContextRemotingData RemotingData { get { if (m_RemotingData == null) m_RemotingData = new CallContextRemotingData(); return m_RemotingData; } } internal CallContextSecurityData SecurityData { get { if (m_SecurityData == null) m_SecurityData = new CallContextSecurityData(); return m_SecurityData; } } internal Object HostContext { get { return m_HostContext; } set { m_HostContext = value; } } private Hashtable Datastore { get { if (null == m_Datastore) { // The local store has not yet been created for this thread. m_Datastore = new Hashtable(); } return m_Datastore; } } // This is used for quick access to the current principal when going // between appdomains. internal IPrincipal Principal { get { // This MUST not fault in the security data object if it doesn't exist. if (m_SecurityData != null) return m_SecurityData.Principal; return null; } // get [System.Security.SecurityCritical] // auto-generated set { SecurityData.Principal = value; } // set } // Principal /*========================================================================= ** Frees a named data slot. =========================================================================*/ [System.Security.SecurityCritical] // auto-generated public void FreeNamedDataSlot(String name) { Datastore.Remove(name); } [System.Security.SecurityCritical] // auto-generated public Object GetData(String name) { return Datastore[name]; } [System.Security.SecurityCritical] // auto-generated public void SetData(String name, Object data) { Datastore[name] = data; if (name.Equals(s_CorrelationMgrSlotName)) m_IsCorrelationMgr = true; } private Header[] InternalGetOutgoingHeaders() { Header[] outgoingHeaders = _sendHeaders; _sendHeaders = null; // A new remote call is being made, so we null out the // current received headers so these can't be confused // with a response from the next call. _recvHeaders = null; return outgoingHeaders; } // InternalGetOutgoingHeaders internal void InternalSetHeaders(Header[] headers) { _sendHeaders = headers; _recvHeaders = null; } // InternalSetHeaders internal Header[] InternalGetHeaders() { // If _sendHeaders is currently set, we always want to return them. if (_sendHeaders != null) return _sendHeaders; // Either _recvHeaders is non-null and those are the ones we want to // return, or there are no currently set headers, so we'll return // null. return _recvHeaders; } // InternalGetHeaders // Nulls out the principal if its not serializable. // Since principals do flow for x-appdomain cases // we need to handle this behaviour both during invoke // and response [System.Security.SecurityCritical] // auto-generated internal IPrincipal RemovePrincipalIfNotSerializable() { IPrincipal currentPrincipal = this.Principal; // If the principal is not serializable, we need to // null it out. if (currentPrincipal != null) { if (!currentPrincipal.GetType().IsSerializable) this.Principal = null; } return currentPrincipal; } // Takes outgoing headers and inserts them [System.Security.SecurityCritical] // auto-generated internal void PropagateOutgoingHeadersToMessage(IMessage msg) { Header[] headers = InternalGetOutgoingHeaders(); if (headers != null) { BCLDebug.Assert(msg != null, "Why is the message null?"); IDictionary properties = msg.Properties; BCLDebug.Assert(properties != null, "Why are the properties null?"); foreach (Header header in headers) { // add header to the message dictionary if (header != null) { // The header key is composed from its name and namespace. String name = GetPropertyKeyForHeader(header); properties[name] = header; } } } } // PropagateOutgoingHeadersToMessage // Retrieve key to use for header. internal static String GetPropertyKeyForHeader(Header header) { if (header == null) return null; if (header.HeaderNamespace != null) return header.Name + ", " + header.HeaderNamespace; else return header.Name; } // GetPropertyKeyForHeader // Take headers out of message and stores them in call context [System.Security.SecurityCritical] // auto-generated internal void PropagateIncomingHeadersToCallContext(IMessage msg) { BCLDebug.Assert(msg != null, "Why is the message null?"); // If it's an internal message, we can quickly tell if there are any // headers. IInternalMessage iim = msg as IInternalMessage; if (iim != null) { if (!iim.HasProperties()) { // If there are no properties just return immediately. return; } } IDictionary properties = msg.Properties; BCLDebug.Assert(properties != null, "Why are the properties null?"); IDictionaryEnumerator e = (IDictionaryEnumerator) properties.GetEnumerator(); // cycle through the properties to get a count of the headers int count = 0; while (e.MoveNext()) { String key = (String)e.Key; if (!key.StartsWith("__", StringComparison.Ordinal)) { // We don't want to have to check for special values, so we // blanketly state that header names can't start with // double underscore. if (e.Value is Header) count++; } } // If there are headers, create array and set it to the received header property Header[] headers = null; if (count > 0) { headers = new Header[count]; count = 0; e.Reset(); while (e.MoveNext()) { String key = (String)e.Key; if (!key.StartsWith("__", StringComparison.Ordinal)) { Header header = e.Value as Header; if (header != null) headers[count++] = header; } } } _recvHeaders = headers; _sendHeaders = null; } // PropagateIncomingHeadersToCallContext } // class LogicalCallContext [Serializable] internal class CallContextSecurityData : ICloneable { // This is used for the special getter/setter for security related // info in the callContext. IPrincipal _principal; // < internal IPrincipal Principal { get {return _principal;} set {_principal = value;} } // Checks if there is any useful data to be serialized internal bool HasInfo { get { return (null != _principal); } } public Object Clone() { CallContextSecurityData sd = new CallContextSecurityData(); sd._principal = _principal; return sd; } } [Serializable] internal class CallContextRemotingData : ICloneable { // This is used for the special getter/setter for remoting related // info in the callContext. String _logicalCallID; internal String LogicalCallID { get {return _logicalCallID;} set {_logicalCallID = value;} } // Checks if there is any useful data to be serialized internal bool HasInfo { get { // Keep this updated if we add more stuff to remotingData! return (_logicalCallID!=null); } } public Object Clone() { CallContextRemotingData rd = new CallContextRemotingData(); rd.LogicalCallID = LogicalCallID; return rd; } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System.Diagnostics; namespace System.Management.Automation.Interpreter { internal abstract class MulInstruction : Instruction { private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } private MulInstruction() { } internal sealed class MulInt32 : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(unchecked((Int32)l * (Int32)r)); frame.StackIndex--; return +1; } } internal sealed class MulInt16 : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Int16)unchecked((Int16)l * (Int16)r); frame.StackIndex--; return +1; } } internal sealed class MulInt64 : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Int64)unchecked((Int64)l * (Int64)r); frame.StackIndex--; return +1; } } internal sealed class MulUInt16 : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt16)unchecked((UInt16)l * (UInt16)r); frame.StackIndex--; return +1; } } internal sealed class MulUInt32 : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt32)unchecked((UInt32)l * (UInt32)r); frame.StackIndex--; return +1; } } internal sealed class MulUInt64 : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt64)unchecked((Int16)l * (Int16)r); frame.StackIndex--; return +1; } } internal sealed class MulSingle : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Single)((Single)l * (Single)r); frame.StackIndex--; return +1; } } internal sealed class MulDouble : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Double)l * (Double)r; frame.StackIndex--; return +1; } } public static Instruction Create(Type type) { Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { case TypeCode.Int16: return s_int16 ?? (s_int16 = new MulInt16()); case TypeCode.Int32: return s_int32 ?? (s_int32 = new MulInt32()); case TypeCode.Int64: return s_int64 ?? (s_int64 = new MulInt64()); case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new MulUInt16()); case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new MulUInt32()); case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new MulUInt64()); case TypeCode.Single: return s_single ?? (s_single = new MulSingle()); case TypeCode.Double: return s_double ?? (s_double = new MulDouble()); default: throw Assert.Unreachable; } } public override string ToString() { return "Mul()"; } } internal abstract class MulOvfInstruction : Instruction { private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } private MulOvfInstruction() { } internal sealed class MulOvfInt32 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(checked((Int32)l * (Int32)r)); frame.StackIndex--; return +1; } } internal sealed class MulOvfInt16 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Int16)checked((Int16)l * (Int16)r); frame.StackIndex--; return +1; } } internal sealed class MulOvfInt64 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Int64)checked((Int64)l * (Int64)r); frame.StackIndex--; return +1; } } internal sealed class MulOvfUInt16 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt16)checked((UInt16)l * (UInt16)r); frame.StackIndex--; return +1; } } internal sealed class MulOvfUInt32 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt32)checked((UInt32)l * (UInt32)r); frame.StackIndex--; return +1; } } internal sealed class MulOvfUInt64 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt64)checked((Int16)l * (Int16)r); frame.StackIndex--; return +1; } } internal sealed class MulOvfSingle : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Single)((Single)l * (Single)r); frame.StackIndex--; return +1; } } internal sealed class MulOvfDouble : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Double)l * (Double)r; frame.StackIndex--; return +1; } } public static Instruction Create(Type type) { Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { case TypeCode.Int16: return s_int16 ?? (s_int16 = new MulOvfInt16()); case TypeCode.Int32: return s_int32 ?? (s_int32 = new MulOvfInt32()); case TypeCode.Int64: return s_int64 ?? (s_int64 = new MulOvfInt64()); case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new MulOvfUInt16()); case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new MulOvfUInt32()); case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new MulOvfUInt64()); case TypeCode.Single: return s_single ?? (s_single = new MulOvfSingle()); case TypeCode.Double: return s_double ?? (s_double = new MulOvfDouble()); default: throw Assert.Unreachable; } } public override string ToString() { return "MulOvf()"; } } }
// 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. using System; using WebsitePanel.EnterpriseServer; using WebsitePanel.Providers.Mail; namespace WebsitePanel.Portal { public partial class MailAccountsEditAccount : WebsitePanelModuleBase { MailAccount item = null; protected void Page_Load(object sender, EventArgs e) { btnDelete.Visible = (PanelRequest.ItemID > 0); // bind item BindItem(); } private void BindItem() { try { if (!IsPostBack) { // load item if required if (PanelRequest.ItemID > 0) { // existing item try { item = ES.Services.MailServers.GetMailAccount(PanelRequest.ItemID); } catch (Exception ex) { ShowErrorMessage("MAIL_GET_ACCOUNT", ex); return; } if (item != null) { // save package info ViewState["PackageId"] = item.PackageId; mailEditAddress.PackageId = item.PackageId; passwordControl.SetPackagePolicy(item.PackageId, UserSettings.MAIL_POLICY, "AccountPasswordPolicy"); } else RedirectToBrowsePage(); } else { // new item ViewState["PackageId"] = PanelSecurity.PackageId; mailEditAddress.PackageId = PanelSecurity.PackageId; passwordControl.SetPackagePolicy(PanelSecurity.PackageId, UserSettings.MAIL_POLICY, "AccountPasswordPolicy"); } } // load provider control LoadProviderControl((int)ViewState["PackageId"], "Mail", providerControl, "EditAccount.ascx"); // load package context PackageContext cntx = PackagesHelper.GetCachedPackageContext((int)ViewState["PackageId"]); if (!IsPostBack) { // set messagebox size textbox visibility HandleMaxMailboxSizeLimitDisplay(cntx); // bind item to controls if (item != null) { // bind item to controls mailEditAddress.Email = item.Name; mailEditAddress.EditMode = true; passwordControl.EditMode = true; // Display currently set max mailbox size limit SetMaxMailboxSizeLimit(item.MaxMailboxSize); // other controls IMailEditAccountControl ctrl = (IMailEditAccountControl)providerControl.Controls[0]; ctrl.BindItem(item); } } } catch { ShowWarningMessage("INIT_SERVICE_ITEM_FORM"); DisableFormControls(this, btnCancel); return; } } private void HandleMaxMailboxSizeLimitDisplay(PackageContext cntx) { if (cntx.Quotas.ContainsKey(Quotas.MAIL_DISABLESIZEEDIT)) { // Obtain quotas from the plan assigned bool maxMailboxSizeChangeable = (cntx.Quotas[Quotas.MAIL_DISABLESIZEEDIT].QuotaAllocatedValue == 0); int maxMailboxSizeLimit = cntx.Quotas[Quotas.MAIL_MAXBOXSIZE].QuotaAllocatedValue; // Ensure all validation controls, markup and layout is rendered consistently if (maxMailboxSizeLimit == -1 && maxMailboxSizeChangeable == false) { lblMaxMailboxSizeLimit.Visible = true; txtMailBoxSizeLimit.Visible = false; } // else if (maxMailboxSizeLimit >= 0 && maxMailboxSizeChangeable == false) { lblMaxMailboxSizeLimit.Visible = true; txtMailBoxSizeLimit.Visible = false; } else if(maxMailboxSizeLimit == -1 && maxMailboxSizeChangeable == true) { lblMaxMailboxSizeLimit.Visible = false; txtMailBoxSizeLimit.Visible = true; } else // this is the cue for the fallback clause: if (maxMailboxSizeLimit >= 0 && maxMailboxSizeChangeable == true) { lblMaxMailboxSizeLimit.Visible = false; txtMailBoxSizeLimit.Visible = true; } // Set the value being displayed for both controls in either case, as the logic above addresses all rendering concerns. SetMaxMailboxSizeLimit(maxMailboxSizeLimit); // Configure required field & range validators appropriately RequiredFieldValidator1.Enabled = txtMailBoxSizeLimit.Visible; MaxMailboxSizeLimitValidator.Enabled = txtMailBoxSizeLimit.Visible; CompareValidator1.Enabled = txtMailBoxSizeLimit.Visible; // Ensure the validator has its mimimun & maximum values adjusted correspondingly if (maxMailboxSizeLimit == -1 || maxMailboxSizeLimit == 0) { MaxMailboxSizeLimitValidator.Enabled = false; CompareValidator1.Enabled = false; } else { MaxMailboxSizeLimitValidator.MinimumValue = "1"; MaxMailboxSizeLimitValidator.MaximumValue = maxMailboxSizeLimit.ToString(); } // Format the validator's error message MaxMailboxSizeLimitValidator.ErrorMessage = String.Format(MaxMailboxSizeLimitValidator.ErrorMessage, MaxMailboxSizeLimitValidator.MinimumValue, MaxMailboxSizeLimitValidator.MaximumValue); } } private void SetMaxMailboxSizeLimit(int sizeLimit) { txtMailBoxSizeLimit.Text = sizeLimit.ToString(); // Ensure we use correct wording when the mailbox size limit is disabled for editing if (sizeLimit == -1 || sizeLimit == 0) lblMaxMailboxSizeLimit.Text = GetSharedLocalizedString("Text.Unlimited"); else lblMaxMailboxSizeLimit.Text = sizeLimit.ToString(); } private void SaveItem() { if (!Page.IsValid) return; // get form data MailAccount item = new MailAccount(); item.Id = PanelRequest.ItemID; item.PackageId = PanelSecurity.PackageId; item.Name = mailEditAddress.Email; item.Password = passwordControl.Password; item.MaxMailboxSize = Utils.ParseInt(txtMailBoxSizeLimit.Text); // Only check for conflicting names if creating new item if (PanelRequest.ItemID == 0) { //checking if account name is different from existing e-mail lists MailList[] lists = ES.Services.MailServers.GetMailLists(PanelSecurity.PackageId, true); foreach (MailList list in lists) { if (item.Name == list.Name) { ShowWarningMessage("MAIL_ACCOUNT_NAME"); return; } } //checking if account name is different from existing e-mail groups MailGroup[] mailgroups = ES.Services.MailServers.GetMailGroups(PanelSecurity.PackageId, true); foreach (MailGroup group in mailgroups) { if (item.Name == group.Name) { ShowWarningMessage("MAIL_ACCOUNT_NAME"); return; } } //checking if account name is different from existing forwardings MailAlias[] forwardings = ES.Services.MailServers.GetMailForwardings(PanelSecurity.PackageId, true); foreach (MailAlias forwarding in forwardings) { if (item.Name == forwarding.Name) { ShowWarningMessage("MAIL_ACCOUNT_NAME"); return; } } } // get other props IMailEditAccountControl ctrl = (IMailEditAccountControl)providerControl.Controls[0]; ctrl.SaveItem(item); if (PanelRequest.ItemID == 0) { // new item try { int result = ES.Services.MailServers.AddMailAccount(item); if (result == BusinessErrorCodes.ERROR_MAIL_ACCOUNT_PASSWORD_NOT_COMPLEXITY) { ShowErrorMessage("MAIL_ACCOUNT_PASSWORD_NOT_COMPLEXITY"); return; } if (result == BusinessErrorCodes.ERROR_MAIL_LICENSE_DOMAIN_QUOTA) { ShowResultMessage(result); return; } if (result == BusinessErrorCodes.ERROR_MAIL_LICENSE_USERS_QUOTA) { ShowResultMessage(result); return; } if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("MAIL_ADD_ACCOUNT", ex); return; } } else { // existing item try { int result = ES.Services.MailServers.UpdateMailAccount(item); if (result == BusinessErrorCodes.ERROR_MAIL_ACCOUNT_PASSWORD_NOT_COMPLEXITY) { ShowErrorMessage("MAIL_ACCOUNT_PASSWORD_NOT_COMPLEXITY"); return; } if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("MAIL_UPDATE_ACCOUNT", ex); return; } } // return RedirectSpaceHomePage(); } private void DeleteItem() { // delete try { int result = ES.Services.MailServers.DeleteMailAccount(PanelRequest.ItemID); if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("MAIL_DELETE_ACCOUNT", ex); return; } // return RedirectSpaceHomePage(); } protected void btnSave_Click(object sender, EventArgs e) { SaveItem(); } protected void btnCancel_Click(object sender, EventArgs e) { // return RedirectSpaceHomePage(); } protected void btnDelete_Click(object sender, EventArgs e) { DeleteItem(); } } }
// 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.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Collections.ObjectModel { [DebuggerTypeProxy(typeof(CollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] public abstract class KeyedCollection<TKey, TItem> : Collection<TItem> { private const int defaultThreshold = 0; private readonly IEqualityComparer<TKey> _comparer; private Dictionary<TKey, TItem> _dict; private int _keyCount; private readonly int _threshold; protected KeyedCollection() : this(null, defaultThreshold) { } protected KeyedCollection(IEqualityComparer<TKey> comparer) : this(comparer, defaultThreshold) { } protected KeyedCollection(IEqualityComparer<TKey> comparer, int dictionaryCreationThreshold) { if (comparer == null) { comparer = EqualityComparer<TKey>.Default; } if (dictionaryCreationThreshold == -1) { dictionaryCreationThreshold = int.MaxValue; } if (dictionaryCreationThreshold < -1) { throw new ArgumentOutOfRangeException("dictionaryCreationThreshold", SR.ArgumentOutOfRange_InvalidThreshold); } _comparer = comparer; _threshold = dictionaryCreationThreshold; } public IEqualityComparer<TKey> Comparer { get { return _comparer; } } public TItem this[TKey key] { get { if (key == null) { throw new ArgumentNullException("key"); } if (_dict != null) { return _dict[key]; } foreach (TItem item in Items) { if (_comparer.Equals(GetKeyForItem(item), key)) return item; } throw new KeyNotFoundException(); } } public bool Contains(TKey key) { if (key == null) { throw new ArgumentNullException("key"); } if (_dict != null) { return _dict.ContainsKey(key); } if (key != null) { foreach (TItem item in Items) { if (_comparer.Equals(GetKeyForItem(item), key)) return true; } } return false; } private bool ContainsItem(TItem item) { TKey key; if ((_dict == null) || ((key = GetKeyForItem(item)) == null)) { return Items.Contains(item); } TItem itemInDict; bool exist = _dict.TryGetValue(key, out itemInDict); if (exist) { return EqualityComparer<TItem>.Default.Equals(itemInDict, item); } return false; } public bool Remove(TKey key) { if (key == null) { throw new ArgumentNullException("key"); } if (_dict != null) { TItem item; return _dict.TryGetValue(key, out item) && Remove(item); } if (key != null) { for (int i = 0; i < Items.Count; i++) { if (_comparer.Equals(GetKeyForItem(Items[i]), key)) { RemoveItem(i); return true; } } } return false; } protected IDictionary<TKey, TItem> Dictionary { get { return _dict; } } protected void ChangeItemKey(TItem item, TKey newKey) { // check if the item exists in the collection if (!ContainsItem(item)) { throw new ArgumentException(SR.Argument_ItemNotExist); } TKey oldKey = GetKeyForItem(item); if (!_comparer.Equals(oldKey, newKey)) { if (newKey != null) { AddKey(newKey, item); } if (oldKey != null) { RemoveKey(oldKey); } } } protected override void ClearItems() { base.ClearItems(); if (_dict != null) { _dict.Clear(); } _keyCount = 0; } protected abstract TKey GetKeyForItem(TItem item); protected override void InsertItem(int index, TItem item) { TKey key = GetKeyForItem(item); if (key != null) { AddKey(key, item); } base.InsertItem(index, item); } protected override void RemoveItem(int index) { TKey key = GetKeyForItem(Items[index]); if (key != null) { RemoveKey(key); } base.RemoveItem(index); } protected override void SetItem(int index, TItem item) { TKey newKey = GetKeyForItem(item); TKey oldKey = GetKeyForItem(Items[index]); if (_comparer.Equals(oldKey, newKey)) { if (newKey != null && _dict != null) { _dict[newKey] = item; } } else { if (newKey != null) { AddKey(newKey, item); } if (oldKey != null) { RemoveKey(oldKey); } } base.SetItem(index, item); } private void AddKey(TKey key, TItem item) { if (_dict != null) { _dict.Add(key, item); } else if (_keyCount == _threshold) { CreateDictionary(); _dict.Add(key, item); } else { if (Contains(key)) { throw new ArgumentException(SR.Argument_AddingDuplicate); } _keyCount++; } } private void CreateDictionary() { _dict = new Dictionary<TKey, TItem>(_comparer); foreach (TItem item in Items) { TKey key = GetKeyForItem(item); if (key != null) { _dict.Add(key, item); } } } private void RemoveKey(TKey key) { Debug.Assert(key != null, "key shouldn't be null!"); if (_dict != null) { _dict.Remove(key); } else { _keyCount--; } } } }
// // 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 Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Reflection; namespace Microsoft.Azure.Commands.Compute.Automation { public abstract class ComputeAutomationBaseCmdlet : Microsoft.Azure.Commands.Compute.ComputeClientBaseCmdlet { public override void ExecuteCmdlet() { base.ExecuteCmdlet(); ComputeAutomationAutoMapperProfile.Initialize(); } protected static PSArgument[] ConvertFromObjectsToArguments(string[] names, object[] objects) { var arguments = new PSArgument[objects.Length]; for (int index = 0; index < objects.Length; index++) { arguments[index] = new PSArgument { Name = names[index], Type = objects[index].GetType(), Value = objects[index] }; } return arguments; } protected static object[] ConvertFromArgumentsToObjects(object[] arguments) { if (arguments == null) { return null; } var objects = new object[arguments.Length]; for (int index = 0; index < arguments.Length; index++) { if (arguments[index] is PSArgument) { objects[index] = ((PSArgument)arguments[index]).Value; } else { objects[index] = arguments[index]; } } return objects; } public IAvailabilitySetsOperations AvailabilitySetsClient { get { return ComputeClient.ComputeManagementClient.AvailabilitySets; } } public IContainerServicesOperations ContainerServicesClient { get { return ComputeClient.ComputeManagementClient.ContainerServices; } } public IDisksOperations DisksClient { get { return ComputeClient.ComputeManagementClient.Disks; } } public IImagesOperations ImagesClient { get { return ComputeClient.ComputeManagementClient.Images; } } public IResourceSkusOperations ResourceSkusClient { get { return ComputeClient.ComputeManagementClient.ResourceSkus; } } public ISnapshotsOperations SnapshotsClient { get { return ComputeClient.ComputeManagementClient.Snapshots; } } public IVirtualMachineRunCommandsOperations VirtualMachineRunCommandsClient { get { return ComputeClient.ComputeManagementClient.VirtualMachineRunCommands; } } public IVirtualMachineScaleSetsOperations VirtualMachineScaleSetsClient { get { return ComputeClient.ComputeManagementClient.VirtualMachineScaleSets; } } public IVirtualMachineScaleSetVMsOperations VirtualMachineScaleSetVMsClient { get { return ComputeClient.ComputeManagementClient.VirtualMachineScaleSetVMs; } } public IVirtualMachinesOperations VirtualMachinesClient { get { return ComputeClient.ComputeManagementClient.VirtualMachines; } } public static string FormatObject(Object obj) { var objType = obj.GetType(); System.Reflection.PropertyInfo[] pros = objType.GetProperties(); string result = "\n"; var resultTuples = new List<Tuple<string, string, int>>(); var totalTab = GetTabLength(obj, 0, 0, resultTuples) + 1; foreach (var t in resultTuples) { string preTab = new string(' ', t.Item3 * 2); string postTab = new string(' ', totalTab - t.Item3 * 2 - t.Item1.Length); result += preTab + t.Item1 + postTab + ": " + t.Item2 + "\n"; } return result; } private static int GetTabLength(Object obj, int max, int depth, List<Tuple<string, string, int>> tupleList) { var objType = obj.GetType(); var propertySet = new List<PropertyInfo>(); if (objType.BaseType != null) { foreach (var property in objType.BaseType.GetProperties()) { propertySet.Add(property); } } foreach (var property in objType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)) { propertySet.Add(property); } foreach (var property in propertySet) { Object childObject = property.GetValue(obj, null); var isJObject = childObject as Newtonsoft.Json.Linq.JObject; if (isJObject != null) { var objStringValue = Newtonsoft.Json.JsonConvert.SerializeObject(childObject); int i = objStringValue.IndexOf("xmlCfg"); if (i >= 0) { var xmlCfgString = objStringValue.Substring(i + 7); int start = xmlCfgString.IndexOf('"'); int end = xmlCfgString.IndexOf('"', start + 1); xmlCfgString = xmlCfgString.Substring(start + 1, end - start - 1); objStringValue = objStringValue.Replace(xmlCfgString, "..."); } tupleList.Add(MakeTuple(property.Name, objStringValue, depth)); max = Math.Max(max, depth * 2 + property.Name.Length); } else { var elem = childObject as IList; if (elem != null) { if (elem.Count != 0) { max = Math.Max(max, depth * 2 + property.Name.Length + 4); for (int i = 0; i < elem.Count; i++) { Type propType = elem[i].GetType(); if (propType.IsSerializable) { tupleList.Add(MakeTuple(property.Name + "[" + i + "]", elem[i].ToString(), depth)); } else { tupleList.Add(MakeTuple(property.Name + "[" + i + "]", "", depth)); max = Math.Max(max, GetTabLength((Object)elem[i], max, depth + 1, tupleList)); } } } } else { if (property.PropertyType.IsSerializable) { if (childObject != null) { tupleList.Add(MakeTuple(property.Name, childObject.ToString(), depth)); max = Math.Max(max, depth * 2 + property.Name.Length); } } else { var isDictionary = childObject as IDictionary; if (isDictionary != null) { tupleList.Add(MakeTuple(property.Name, Newtonsoft.Json.JsonConvert.SerializeObject(childObject), depth)); max = Math.Max(max, depth * 2 + property.Name.Length); } else if (childObject != null) { tupleList.Add(MakeTuple(property.Name, "", depth)); max = Math.Max(max, GetTabLength(childObject, max, depth + 1, tupleList)); } } } } } return max; } private static Tuple<string, string, int> MakeTuple(string key, string value, int depth) { return new Tuple<string, string, int>(key, value, depth); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.Forms.dll // Description: The Windows Forms user interface layer for the DotSpatial.Symbology library. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 10/6/2009 8:53:01 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace DotSpatial.Symbology.Forms { /// <summary> /// TabColorControl /// </summary> [DefaultEvent("ColorChanged"), ToolboxItem(false)] public class TabColorControl : UserControl { #region Events /// <summary> /// Occurs when the color is changed. /// </summary> public event EventHandler<ColorRangeEventArgs> ColorChanged; #endregion #region Private Variables private Color _endColor; private int _endHue; private float _endLight; private float _endSat; private bool _hsl; private int _hueShift; private bool _ignoreUpdates; private Color _startColor; private int _startHue; private float _startLight; private float _startSat; private Button btnHueShift; private Button btnReverseHue; private Button btnReverseLight; private Button btnReverseSat; private ColorButton cbEndColor; private ColorButton cbStartColor; private CheckBox chkUseColorRange; private GroupBox groupBox1; private Label lblEndColor; private Label lblHueRange; private Label lblLightnessRange; private Label lblSaturationRange; private Label lblStartColor; private RampSlider rampSlider1; private RampSlider rampSlider2; private HueSlider sldHue; private TwoColorSlider sldLightness; private TwoColorSlider sldSaturation; private TabControl tabColorRange; private TabPage tabHSL; private TabPage tabRGB; private Timer tmrHueShift; #endregion #region Constructors /// <summary> /// Creates a new instance of TabColorControl /// </summary> public TabColorControl() { InitializeComponent(); Configure(); } private void Configure() { tmrHueShift = new Timer { Interval = 100 }; tmrHueShift.Tick += tmrHueShift_Tick; btnHueShift.MouseDown += btnHueShift_MouseDown; btnHueShift.MouseUp += btnHueShift_MouseUp; } #endregion #region Methods /// <summary> /// Initializes a new instance of this control using the specified values. /// </summary> /// <param name="args">The ColorRangeEventArgs that stores the initial values.</param> public void Initialize(ColorRangeEventArgs args) { _endColor = args.EndColor; _hsl = args.HSL; _hueShift = args.HueShift; _startColor = args.StartColor; chkUseColorRange.Checked = args.UseColorRange; SetStartHsl(); SetEndHsl(); UpdateControls(); } private void SetStartHsl() { _startHue = (int)_startColor.GetHue(); _startSat = _startColor.GetSaturation(); _startLight = _startColor.GetBrightness(); } private void SetEndHsl() { _endHue = (int)_endColor.GetHue(); _endSat = _endColor.GetSaturation(); _endLight = _endColor.GetBrightness(); } #endregion #region Properties /// <summary> /// Gets or sets the start color, which controls the RGB start colors and the HSL left ranges /// </summary> [Category("Colors"), Description("Gets or sets the start color, which controls the RGB colors and the HSL range")] public Color StartColor { get { return _startColor; } set { _startColor = value; SetStartHsl(); cbStartColor.Color = value; } } /// <summary> /// Gets or sets the end color, which controls the RGB end color and the right HSL ranges /// </summary> [Category("Colors"), Description("Gets or sets the end color, which controls the RGB end color and the right HSL ranges")] public Color EndColor { get { return _endColor; } set { _endColor = value; SetEndHsl(); cbEndColor.Color = value; } } /// <summary> /// Gets or sets the integer hue shift marking how much the hue slider should be shifted /// </summary> [Category("Behavior"), Description("Gets or sets the integer hue shift marking how much the hue slider should be shifted")] public int HueShift { get { return _hueShift; } set { _hueShift = value; } } /// <summary> /// Gets or sets a boolean indicating whether or not the hue range is to be used. /// </summary> [Category("Behavior"), Description("Gets or sets a boolean indicating whether or not the hue range is to be used.")] public bool UseRangeChecked { get { return chkUseColorRange.Checked; } set { chkUseColorRange.Checked = value; } } #endregion #region Windows Form Designer generated code /// <summary> /// Disposes the unmanaged memory or controls /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { base.Dispose(disposing); } private void InitializeComponent() { this.groupBox1 = new System.Windows.Forms.GroupBox(); this.tabColorRange = new System.Windows.Forms.TabControl(); this.tabHSL = new System.Windows.Forms.TabPage(); this.btnReverseLight = new System.Windows.Forms.Button(); this.btnReverseSat = new System.Windows.Forms.Button(); this.btnReverseHue = new System.Windows.Forms.Button(); this.sldLightness = new DotSpatial.Symbology.Forms.TwoColorSlider(); this.sldSaturation = new DotSpatial.Symbology.Forms.TwoColorSlider(); this.btnHueShift = new System.Windows.Forms.Button(); this.sldHue = new DotSpatial.Symbology.Forms.HueSlider(); this.lblHueRange = new System.Windows.Forms.Label(); this.lblSaturationRange = new System.Windows.Forms.Label(); this.lblLightnessRange = new System.Windows.Forms.Label(); this.tabRGB = new System.Windows.Forms.TabPage(); this.rampSlider2 = new DotSpatial.Symbology.Forms.RampSlider(); this.cbEndColor = new DotSpatial.Symbology.Forms.ColorButton(); this.rampSlider1 = new DotSpatial.Symbology.Forms.RampSlider(); this.cbStartColor = new DotSpatial.Symbology.Forms.ColorButton(); this.lblEndColor = new System.Windows.Forms.Label(); this.lblStartColor = new System.Windows.Forms.Label(); this.chkUseColorRange = new System.Windows.Forms.CheckBox(); this.groupBox1.SuspendLayout(); this.tabColorRange.SuspendLayout(); this.tabHSL.SuspendLayout(); this.tabRGB.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.tabColorRange); this.groupBox1.Controls.Add(this.chkUseColorRange); this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox1.Location = new System.Drawing.Point(0, 0); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(227, 219); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; // // tabColorRange // this.tabColorRange.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tabColorRange.Controls.Add(this.tabHSL); this.tabColorRange.Controls.Add(this.tabRGB); this.tabColorRange.Location = new System.Drawing.Point(6, 23); this.tabColorRange.Name = "tabColorRange"; this.tabColorRange.SelectedIndex = 0; this.tabColorRange.Size = new System.Drawing.Size(217, 189); this.tabColorRange.TabIndex = 12; // // tabHSL // this.tabHSL.Controls.Add(this.btnReverseLight); this.tabHSL.Controls.Add(this.btnReverseSat); this.tabHSL.Controls.Add(this.btnReverseHue); this.tabHSL.Controls.Add(this.sldLightness); this.tabHSL.Controls.Add(this.sldSaturation); this.tabHSL.Controls.Add(this.btnHueShift); this.tabHSL.Controls.Add(this.sldHue); this.tabHSL.Controls.Add(this.lblHueRange); this.tabHSL.Controls.Add(this.lblSaturationRange); this.tabHSL.Controls.Add(this.lblLightnessRange); this.tabHSL.Location = new System.Drawing.Point(4, 25); this.tabHSL.Name = "tabHSL"; this.tabHSL.Padding = new System.Windows.Forms.Padding(3); this.tabHSL.Size = new System.Drawing.Size(209, 160); this.tabHSL.TabIndex = 0; this.tabHSL.Text = "HSL"; this.tabHSL.UseVisualStyleBackColor = true; // // btnReverseLight // this.btnReverseLight.Image = global::DotSpatial.Symbology.Forms.SymbologyFormsImages.redbluearrows; this.btnReverseLight.Location = new System.Drawing.Point(144, 127); this.btnReverseLight.Name = "btnReverseLight"; this.btnReverseLight.Size = new System.Drawing.Size(28, 23); this.btnReverseLight.TabIndex = 9; this.btnReverseLight.UseVisualStyleBackColor = true; this.btnReverseLight.Click += new System.EventHandler(this.btnReverseLight_Click); // // btnReverseSat // this.btnReverseSat.Image = global::DotSpatial.Symbology.Forms.SymbologyFormsImages.redbluearrows; this.btnReverseSat.Location = new System.Drawing.Point(144, 78); this.btnReverseSat.Name = "btnReverseSat"; this.btnReverseSat.Size = new System.Drawing.Size(28, 23); this.btnReverseSat.TabIndex = 6; this.btnReverseSat.UseVisualStyleBackColor = true; this.btnReverseSat.Click += new System.EventHandler(this.btnReverseSat_Click); // // btnReverseHue // this.btnReverseHue.BackColor = System.Drawing.Color.Transparent; this.btnReverseHue.Image = global::DotSpatial.Symbology.Forms.SymbologyFormsImages.redbluearrows; this.btnReverseHue.Location = new System.Drawing.Point(144, 29); this.btnReverseHue.Name = "btnReverseHue"; this.btnReverseHue.Size = new System.Drawing.Size(28, 23); this.btnReverseHue.TabIndex = 2; this.btnReverseHue.UseVisualStyleBackColor = false; this.btnReverseHue.Click += new System.EventHandler(this.btnReverseHue_Click); // // sldLightness // this.sldLightness.Inverted = false; this.sldLightness.LeftHandle.Color = System.Drawing.Color.SteelBlue; this.sldLightness.LeftHandle.IsLeft = true; this.sldLightness.LeftHandle.Position = 0.0406504F; this.sldLightness.LeftHandle.RoundingRadius = 2; this.sldLightness.LeftHandle.Visible = true; this.sldLightness.LeftHandle.Width = 5; this.sldLightness.LeftValue = 0.0406504F; this.sldLightness.Location = new System.Drawing.Point(15, 127); this.sldLightness.Maximum = 1F; this.sldLightness.MaximumColor = System.Drawing.Color.White; this.sldLightness.Minimum = 0F; this.sldLightness.MinimumColor = System.Drawing.Color.Black; this.sldLightness.Name = "sldLightness"; this.sldLightness.RightHandle.Color = System.Drawing.Color.SteelBlue; this.sldLightness.RightHandle.IsLeft = false; this.sldLightness.RightHandle.Position = 0.8F; this.sldLightness.RightHandle.RoundingRadius = 2; this.sldLightness.RightHandle.Visible = true; this.sldLightness.RightHandle.Width = 5; this.sldLightness.RightValue = 0.8F; this.sldLightness.Size = new System.Drawing.Size(123, 23); this.sldLightness.TabIndex = 8; this.sldLightness.Text = "twoColorSlider2"; this.sldLightness.PositionChanging += new System.EventHandler(this.sldLightness_PositionChanging); // // sldSaturation // this.sldSaturation.Inverted = false; this.sldSaturation.LeftHandle.Color = System.Drawing.Color.SteelBlue; this.sldSaturation.LeftHandle.IsLeft = true; this.sldSaturation.LeftHandle.Position = 0.04098361F; this.sldSaturation.LeftHandle.RoundingRadius = 2; this.sldSaturation.LeftHandle.Visible = true; this.sldSaturation.LeftHandle.Width = 5; this.sldSaturation.LeftValue = 0.04098361F; this.sldSaturation.Location = new System.Drawing.Point(15, 78); this.sldSaturation.Maximum = 1F; this.sldSaturation.MaximumColor = System.Drawing.Color.Blue; this.sldSaturation.Minimum = 0F; this.sldSaturation.MinimumColor = System.Drawing.Color.White; this.sldSaturation.Name = "sldSaturation"; this.sldSaturation.RightHandle.Color = System.Drawing.Color.SteelBlue; this.sldSaturation.RightHandle.IsLeft = false; this.sldSaturation.RightHandle.Position = 0.8F; this.sldSaturation.RightHandle.RoundingRadius = 2; this.sldSaturation.RightHandle.Visible = true; this.sldSaturation.RightHandle.Width = 5; this.sldSaturation.RightValue = 0.8F; this.sldSaturation.Size = new System.Drawing.Size(122, 23); this.sldSaturation.TabIndex = 5; this.sldSaturation.Text = "twoColorSlider1"; this.sldSaturation.PositionChanging += new System.EventHandler(this.sldSaturation_PositionChanging); // // btnHueShift // this.btnHueShift.Image = global::DotSpatial.Symbology.Forms.SymbologyFormsImages.RunModel; this.btnHueShift.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.btnHueShift.Location = new System.Drawing.Point(178, 29); this.btnHueShift.Name = "btnHueShift"; this.btnHueShift.Size = new System.Drawing.Size(21, 23); this.btnHueShift.TabIndex = 3; this.btnHueShift.UseVisualStyleBackColor = true; // // sldHue // this.sldHue.HueShift = 0; this.sldHue.Inverted = false; this.sldHue.LeftHandle.Color = System.Drawing.Color.SteelBlue; this.sldHue.LeftHandle.Left = true; this.sldHue.LeftHandle.Position = 14.7541F; this.sldHue.LeftHandle.RoundingRadius = 2; this.sldHue.LeftHandle.Visible = true; this.sldHue.LeftHandle.Width = 5; this.sldHue.LeftValue = 14.7541F; this.sldHue.Location = new System.Drawing.Point(16, 29); this.sldHue.Maximum = 360; this.sldHue.Minimum = 0; this.sldHue.Name = "sldHue"; this.sldHue.RightHandle.Color = System.Drawing.Color.SteelBlue; this.sldHue.RightHandle.Left = false; this.sldHue.RightHandle.Position = 288F; this.sldHue.RightHandle.RoundingRadius = 2; this.sldHue.RightHandle.Visible = true; this.sldHue.RightHandle.Width = 5; this.sldHue.RightValue = 288F; this.sldHue.Size = new System.Drawing.Size(122, 23); this.sldHue.TabIndex = 1; this.sldHue.Text = "hueSlider1"; this.sldHue.PositionChanging += new System.EventHandler(this.sldHue_PositionChanging); // // lblHueRange // this.lblHueRange.AutoSize = true; this.lblHueRange.Location = new System.Drawing.Point(9, 13); this.lblHueRange.Name = "lblHueRange"; this.lblHueRange.Size = new System.Drawing.Size(84, 17); this.lblHueRange.TabIndex = 0; this.lblHueRange.Text = "Hue Range:"; // // lblSaturationRange // this.lblSaturationRange.AutoSize = true; this.lblSaturationRange.Location = new System.Drawing.Point(9, 62); this.lblSaturationRange.Name = "lblSaturationRange"; this.lblSaturationRange.Size = new System.Drawing.Size(123, 17); this.lblSaturationRange.TabIndex = 4; this.lblSaturationRange.Text = "Saturation Range:"; // // lblLightnessRange // this.lblLightnessRange.AutoSize = true; this.lblLightnessRange.Location = new System.Drawing.Point(9, 111); this.lblLightnessRange.Name = "lblLightnessRange"; this.lblLightnessRange.Size = new System.Drawing.Size(119, 17); this.lblLightnessRange.TabIndex = 7; this.lblLightnessRange.Text = "Lightness Range:"; // // tabRGB // this.tabRGB.Controls.Add(this.rampSlider2); this.tabRGB.Controls.Add(this.rampSlider1); this.tabRGB.Controls.Add(this.lblEndColor); this.tabRGB.Controls.Add(this.lblStartColor); this.tabRGB.Controls.Add(this.cbEndColor); this.tabRGB.Controls.Add(this.cbStartColor); this.tabRGB.Location = new System.Drawing.Point(4, 25); this.tabRGB.Name = "tabRGB"; this.tabRGB.Padding = new System.Windows.Forms.Padding(3); this.tabRGB.Size = new System.Drawing.Size(209, 160); this.tabRGB.TabIndex = 1; this.tabRGB.Text = "RGB"; this.tabRGB.UseVisualStyleBackColor = true; // // rampSlider2 // this.rampSlider2.ColorButton = this.cbEndColor; this.rampSlider2.FlipRamp = false; this.rampSlider2.FlipText = false; this.rampSlider2.InvertRamp = false; this.rampSlider2.Location = new System.Drawing.Point(93, 106); this.rampSlider2.Maximum = 1D; this.rampSlider2.MaximumColor = System.Drawing.Color.Blue; this.rampSlider2.Minimum = 0D; this.rampSlider2.MinimumColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(128)))), ((int)(((byte)(0))))); this.rampSlider2.Name = "rampSlider2"; this.rampSlider2.NumberFormat = "#.00"; this.rampSlider2.Orientation = System.Windows.Forms.Orientation.Horizontal; this.rampSlider2.RampRadius = 10F; this.rampSlider2.RampText = "Opacity"; this.rampSlider2.RampTextAlignment = System.Drawing.ContentAlignment.MiddleCenter; this.rampSlider2.RampTextBehindRamp = true; this.rampSlider2.RampTextColor = System.Drawing.Color.Black; this.rampSlider2.RampTextFont = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.rampSlider2.ShowMaximum = false; this.rampSlider2.ShowMinimum = false; this.rampSlider2.ShowTicks = false; this.rampSlider2.ShowValue = false; this.rampSlider2.Size = new System.Drawing.Size(97, 25); this.rampSlider2.SliderColor = System.Drawing.Color.Blue; this.rampSlider2.SliderRadius = 4F; this.rampSlider2.TabIndex = 5; this.rampSlider2.Text = "rampSlider2"; this.rampSlider2.TickColor = System.Drawing.Color.DarkGray; this.rampSlider2.TickSpacing = 5F; this.rampSlider2.Value = 1D; // // cbEndColor // this.cbEndColor.BevelRadius = 2; this.cbEndColor.Color = System.Drawing.Color.Navy; this.cbEndColor.LaunchDialogOnClick = true; this.cbEndColor.Location = new System.Drawing.Point(33, 106); this.cbEndColor.Name = "cbEndColor"; this.cbEndColor.RoundingRadius = 4; this.cbEndColor.Size = new System.Drawing.Size(40, 25); this.cbEndColor.TabIndex = 2; this.cbEndColor.Text = "colorButton2"; this.cbEndColor.ColorChanged += new System.EventHandler(this.cbEndColor_ColorChanged); // // rampSlider1 // this.rampSlider1.ColorButton = this.cbStartColor; this.rampSlider1.FlipRamp = false; this.rampSlider1.FlipText = false; this.rampSlider1.InvertRamp = false; this.rampSlider1.Location = new System.Drawing.Point(93, 38); this.rampSlider1.Maximum = 1D; this.rampSlider1.MaximumColor = System.Drawing.Color.Blue; this.rampSlider1.Minimum = 0D; this.rampSlider1.MinimumColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(128)))), ((int)(((byte)(0))))); this.rampSlider1.Name = "rampSlider1"; this.rampSlider1.NumberFormat = "#.00"; this.rampSlider1.Orientation = System.Windows.Forms.Orientation.Horizontal; this.rampSlider1.RampRadius = 10F; this.rampSlider1.RampText = "Opacity"; this.rampSlider1.RampTextAlignment = System.Drawing.ContentAlignment.MiddleCenter; this.rampSlider1.RampTextBehindRamp = true; this.rampSlider1.RampTextColor = System.Drawing.Color.Black; this.rampSlider1.RampTextFont = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.rampSlider1.ShowMaximum = false; this.rampSlider1.ShowMinimum = false; this.rampSlider1.ShowTicks = false; this.rampSlider1.ShowValue = false; this.rampSlider1.Size = new System.Drawing.Size(97, 25); this.rampSlider1.SliderColor = System.Drawing.Color.Blue; this.rampSlider1.SliderRadius = 4F; this.rampSlider1.TabIndex = 4; this.rampSlider1.Text = "rampSlider1"; this.rampSlider1.TickColor = System.Drawing.Color.DarkGray; this.rampSlider1.TickSpacing = 5F; this.rampSlider1.Value = 1D; // // cbStartColor // this.cbStartColor.BevelRadius = 2; this.cbStartColor.Color = System.Drawing.Color.LightBlue; this.cbStartColor.LaunchDialogOnClick = true; this.cbStartColor.Location = new System.Drawing.Point(33, 38); this.cbStartColor.Name = "cbStartColor"; this.cbStartColor.RoundingRadius = 4; this.cbStartColor.Size = new System.Drawing.Size(40, 25); this.cbStartColor.TabIndex = 0; this.cbStartColor.Text = "colorButton1"; this.cbStartColor.ColorChanged += new System.EventHandler(this.cbStartColor_ColorChanged); // // lblEndColor // this.lblEndColor.AutoSize = true; this.lblEndColor.Location = new System.Drawing.Point(8, 80); this.lblEndColor.Name = "lblEndColor"; this.lblEndColor.Size = new System.Drawing.Size(70, 17); this.lblEndColor.TabIndex = 3; this.lblEndColor.Text = "&End Color"; // // lblStartColor // this.lblStartColor.AutoSize = true; this.lblStartColor.Location = new System.Drawing.Point(8, 12); this.lblStartColor.Name = "lblStartColor"; this.lblStartColor.Size = new System.Drawing.Size(75, 17); this.lblStartColor.TabIndex = 1; this.lblStartColor.Text = "&Start Color"; // // chkUseColorRange // this.chkUseColorRange.AutoSize = true; this.chkUseColorRange.Checked = true; this.chkUseColorRange.CheckState = System.Windows.Forms.CheckState.Checked; this.chkUseColorRange.Location = new System.Drawing.Point(6, 0); this.chkUseColorRange.Name = "chkUseColorRange"; this.chkUseColorRange.Size = new System.Drawing.Size(138, 21); this.chkUseColorRange.TabIndex = 11; this.chkUseColorRange.Text = "Use Color &Range"; this.chkUseColorRange.UseVisualStyleBackColor = true; this.chkUseColorRange.CheckedChanged += new System.EventHandler(this.chkUseColorRange_CheckedChanged); // // TabColorControl // this.Controls.Add(this.groupBox1); this.Name = "TabColorControl"; this.Size = new System.Drawing.Size(227, 219); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.tabColorRange.ResumeLayout(false); this.tabHSL.ResumeLayout(false); this.tabHSL.PerformLayout(); this.tabRGB.ResumeLayout(false); this.tabRGB.PerformLayout(); this.ResumeLayout(false); } #endregion private void btnHueShift_MouseUp(object sender, MouseEventArgs e) { tmrHueShift.Stop(); } private void btnHueShift_MouseDown(object sender, MouseEventArgs e) { tmrHueShift.Start(); } private void sldHue_PositionChanging(object sender, EventArgs e) { SetHsl(); } private void tmrHueShift_Tick(object sender, EventArgs e) { int shift = sldHue.Inverted ? 36 : -36; _ignoreUpdates = true; sldHue.HueShift = (sldHue.HueShift + shift) % 360; //sldHue.LeftValue = sldHue.LeftValue; //sldHue.RightValue = sldHue.RightValue; SetHsl(); } private void btnReverseHue_Click(object sender, EventArgs e) { sldHue.Inverted = !sldHue.Inverted; SetHsl(); } private void btnReverseSat_Click(object sender, EventArgs e) { sldSaturation.Inverted = !sldSaturation.Inverted; SetHsl(); } private void btnReverseLight_Click(object sender, EventArgs e) { sldLightness.Inverted = !sldLightness.Inverted; SetHsl(); } private void sldSaturation_PositionChanging(object sender, EventArgs e) { SetHsl(); } private void sldLightness_PositionChanging(object sender, EventArgs e) { SetHsl(); } private void cbStartColor_ColorChanged(object sender, EventArgs e) { SetRgb(); } private void cbEndColor_ColorChanged(object sender, EventArgs e) { SetRgb(); } // Reads the current control settings to the cached values. private void SetHsl() { if (_ignoreUpdates) return; _hueShift = sldHue.HueShift; int h = (int)(sldHue.LeftValue + (_hueShift) % 360); float s = sldSaturation.LeftValue; float l = sldLightness.LeftValue; float a = _startColor.A / 255f; _startColor = SymbologyGlobal.ColorFromHsl(h, s, l).ToTransparent(a); _startHue = h; _startSat = s; _startLight = l; h = (int)(sldHue.RightValue + _hueShift) % 360; s = sldSaturation.RightValue; l = sldLightness.RightValue; a = _endColor.A / 255f; _endHue = h; _endSat = s; _endLight = l; _endColor = SymbologyGlobal.ColorFromHsl(h, s, l).ToTransparent(a); _hsl = true; chkUseColorRange.Checked = true; _ignoreUpdates = true; cbStartColor.Color = _startColor; cbEndColor.Color = _endColor; _ignoreUpdates = false; UpdateControls(); } // Updates private void SetRgb() { if (_ignoreUpdates) return; _startColor = cbStartColor.Color; _endColor = cbEndColor.Color; SetStartHsl(); SetEndHsl(); chkUseColorRange.Checked = true; _hsl = false; UpdateControls(); } private void UpdateControls() { // Prevent infinite loops if (_ignoreUpdates) return; _ignoreUpdates = true; if (_hsl) { // Don't use the colors directly, here mainly because saturation // loses information when going back and forth from a color. if (_startHue != _endHue) sldHue.Inverted = _startHue > _endHue; sldHue.LeftValue = _startHue; sldHue.RightValue = _endHue; if (_startSat != _endSat) sldSaturation.Inverted = _startSat > _endSat; sldSaturation.LeftValue = _startSat; sldSaturation.RightValue = _endSat; if (_startLight != _endLight) sldLightness.Inverted = _startLight > _endLight; sldLightness.LeftValue = _startLight; sldLightness.RightValue = _endLight; } else { sldHue.SetRange(_startColor, _endColor); sldSaturation.SetSaturation(_startColor, _endColor); sldLightness.SetLightness(_startColor, _endColor); sldHue.HueShift = _hueShift; cbStartColor.Color = _startColor; cbEndColor.Color = _endColor; } tabColorRange.SelectedTab = _hsl ? tabHSL : tabRGB; _ignoreUpdates = false; OnColorChanged(); } /// <summary> /// Fires the ColorChanged event /// </summary> protected virtual void OnColorChanged() { if (ColorChanged != null) ColorChanged(this, new ColorRangeEventArgs(_startColor, _endColor, _hueShift, _hsl, chkUseColorRange.Checked)); } private void chkUseColorRange_CheckedChanged(object sender, EventArgs e) { OnColorChanged(); } } }
using System; using System.Collections.Concurrent; using System.Threading.Tasks; using Akka.Actor; using Akka.Configuration; using Akka.Event; using Google.ProtocolBuffers; using Helios.Exceptions; using Helios.Net; using Helios.Topology; namespace Akka.Remote.Transport.Helios { /// <summary> /// INTERNAL API /// </summary> static class ChannelLocalActor { private static ConcurrentDictionary<IConnection, IHandleEventListener> _channelActors = new ConcurrentDictionary<IConnection, IHandleEventListener>(); public static void Set(IConnection channel, IHandleEventListener listener = null) { _channelActors.AddOrUpdate(channel, listener, (connection, eventListener) => listener); } public static void Remove(IConnection channel) { IHandleEventListener listener; _channelActors.TryRemove(channel, out listener); } public static void Notify(IConnection channel, IHandleEvent msg) { IHandleEventListener listener; if (_channelActors.TryGetValue(channel, out listener)) { listener.Notify(msg); } } } /// <summary> /// INTERNAL API /// </summary> abstract class TcpHandlers : CommonHandlers { protected TcpHandlers(IConnection underlyingConnection) : base(underlyingConnection) { } protected override void RegisterListener(IConnection channel, IHandleEventListener listener, NetworkData msg, INode remoteAddress) { ChannelLocalActor.Set(channel, listener); BindEvents(channel); } protected override AssociationHandle CreateHandle(IConnection channel, Address localAddress, Address remoteAddress) { return new TcpAssociationHandle(localAddress, remoteAddress, WrappedTransport, channel); } protected override void OnDisconnect(HeliosConnectionException cause, IConnection closedChannel) { if(cause != null) ChannelLocalActor.Notify(closedChannel, new UnderlyingTransportError(cause, "Undlerying transport closed.")); if (cause != null && cause.Type == ExceptionType.Closed) ChannelLocalActor.Notify(closedChannel, new Disassociated(DisassociateInfo.Shutdown)); else { ChannelLocalActor.Notify(closedChannel, new Disassociated(DisassociateInfo.Unknown)); } ChannelLocalActor.Remove(closedChannel); } protected override void OnMessage(NetworkData data, IConnection responseChannel) { if (data.Length > 0) { ChannelLocalActor.Notify(responseChannel, new InboundPayload(FromData(data))); } } protected override void OnException(Exception ex, IConnection erroredChannel) { ChannelLocalActor.Notify(erroredChannel, new UnderlyingTransportError(ex, "Non-fatal network error occurred inside underlying transport")); } public override void Dispose() { ChannelLocalActor.Remove(UnderlyingConnection); base.Dispose(); } } class TcpServerHandler : TcpHandlers { private Task<IAssociationEventListener> _associationListenerTask; public TcpServerHandler(HeliosTransport wrappedTransport, Task<IAssociationEventListener> associationListenerTask, IConnection underlyingConnection) : base(underlyingConnection) { WrappedTransport = wrappedTransport; _associationListenerTask = associationListenerTask; } protected void InitInbound(IConnection connection, INode remoteSocketAddress, NetworkData msg) { _associationListenerTask.ContinueWith(r => { var listener = r.Result; var remoteAddress = HeliosTransport.NodeToAddress(remoteSocketAddress, WrappedTransport.SchemeIdentifier, WrappedTransport.System.Name); if (remoteAddress == null) throw new HeliosNodeException("Unknown inbound remote address type {0}", remoteSocketAddress); AssociationHandle handle; Init(connection, remoteSocketAddress, remoteAddress, msg, out handle); listener.Notify(new InboundAssociation(handle)); }, TaskContinuationOptions.AttachedToParent & TaskContinuationOptions.ExecuteSynchronously & TaskContinuationOptions.NotOnCanceled & TaskContinuationOptions.NotOnFaulted); } protected override void OnConnect(INode remoteAddress, IConnection responseChannel) { InitInbound(responseChannel, remoteAddress, NetworkData.Create(Node.Empty(), new byte[0], 0)); } } class TcpClientHandler : TcpHandlers { protected readonly TaskCompletionSource<AssociationHandle> StatusPromise = new TaskCompletionSource<AssociationHandle>(); public TcpClientHandler(HeliosTransport heliosWrappedTransport, Address remoteAddress, IConnection underlyingConnection) : base(underlyingConnection) { WrappedTransport = heliosWrappedTransport; RemoteAddress = remoteAddress; } public Task<AssociationHandle> StatusFuture { get { return StatusPromise.Task; } } protected Address RemoteAddress; protected void InitOutbound(IConnection channel, INode remoteSocketAddress, NetworkData msg) { AssociationHandle handle; Init(channel, remoteSocketAddress, RemoteAddress, msg, out handle); StatusPromise.SetResult(handle); } protected override void OnConnect(INode remoteAddress, IConnection responseChannel) { InitOutbound(responseChannel, remoteAddress, NetworkData.Create(Node.Empty(), new byte[0], 0)); } protected override void OnDisconnect(HeliosConnectionException cause, IConnection closedChannel) { base.OnDisconnect(cause, closedChannel); } } /// <summary> /// INTERNAL API /// </summary> class TcpAssociationHandle : AssociationHandle { private IConnection _channel; private HeliosTransport _transport; public TcpAssociationHandle(Address localAddress, Address remoteAddress, HeliosTransport transport, IConnection connection) : base(localAddress, remoteAddress) { _channel = connection; _transport = transport; } public override bool Write(ByteString payload) { if (_channel.IsOpen()) { _channel.Send(HeliosHelpers.ToData(payload, RemoteAddress)); return true; } return false; } public override void Disassociate() { if(!_channel.WasDisposed) _channel.Close(); } } class HeliosTcpTransport : HeliosTransport { public HeliosTcpTransport(ActorSystem system, Config config) : base(system, config) { } protected override Task<AssociationHandle> AssociateInternal(Address remoteAddress) { var client = NewClient(remoteAddress); var socketAddress = client.RemoteHost; client.Open(); return ((TcpClientHandler) client).StatusFuture; } } }
/* * Copyright 2010-2014 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. */ /* * Do not modify this file. This file is generated from the ec2-2014-10-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { /// <summary> /// Describes a Reserved Instance. /// </summary> public partial class ReservedInstances { private string _availabilityZone; private CurrencyCodeValues _currencyCode; private long? _duration; private DateTime? _end; private float? _fixedPrice; private int? _instanceCount; private Tenancy _instanceTenancy; private InstanceType _instanceType; private OfferingTypeValues _offeringType; private RIProductDescription _productDescription; private List<RecurringCharge> _recurringCharges = new List<RecurringCharge>(); private string _reservedInstancesId; private DateTime? _start; private ReservedInstanceState _state; private List<Tag> _tags = new List<Tag>(); private float? _usagePrice; /// <summary> /// Gets and sets the property AvailabilityZone. /// <para> /// The Availability Zone in which the Reserved Instance can be used. /// </para> /// </summary> public string AvailabilityZone { get { return this._availabilityZone; } set { this._availabilityZone = value; } } // Check to see if AvailabilityZone property is set internal bool IsSetAvailabilityZone() { return this._availabilityZone != null; } /// <summary> /// Gets and sets the property CurrencyCode. /// <para> /// The currency of the Reserved Instance. It's specified using ISO 4217 standard currency /// codes. At this time, the only supported currency is <code>USD</code>. /// </para> /// </summary> public CurrencyCodeValues CurrencyCode { get { return this._currencyCode; } set { this._currencyCode = value; } } // Check to see if CurrencyCode property is set internal bool IsSetCurrencyCode() { return this._currencyCode != null; } /// <summary> /// Gets and sets the property Duration. /// <para> /// The duration of the Reserved Instance, in seconds. /// </para> /// </summary> public long Duration { get { return this._duration.GetValueOrDefault(); } set { this._duration = value; } } // Check to see if Duration property is set internal bool IsSetDuration() { return this._duration.HasValue; } /// <summary> /// Gets and sets the property End. /// <para> /// The time when the Reserved Instance expires. /// </para> /// </summary> public DateTime End { get { return this._end.GetValueOrDefault(); } set { this._end = value; } } // Check to see if End property is set internal bool IsSetEnd() { return this._end.HasValue; } /// <summary> /// Gets and sets the property FixedPrice. /// <para> /// The purchase price of the Reserved Instance. /// </para> /// </summary> public float FixedPrice { get { return this._fixedPrice.GetValueOrDefault(); } set { this._fixedPrice = value; } } // Check to see if FixedPrice property is set internal bool IsSetFixedPrice() { return this._fixedPrice.HasValue; } /// <summary> /// Gets and sets the property InstanceCount. /// <para> /// The number of Reserved Instances purchased. /// </para> /// </summary> public int InstanceCount { get { return this._instanceCount.GetValueOrDefault(); } set { this._instanceCount = value; } } // Check to see if InstanceCount property is set internal bool IsSetInstanceCount() { return this._instanceCount.HasValue; } /// <summary> /// Gets and sets the property InstanceTenancy. /// <para> /// The tenancy of the reserved instance. /// </para> /// </summary> public Tenancy InstanceTenancy { get { return this._instanceTenancy; } set { this._instanceTenancy = value; } } // Check to see if InstanceTenancy property is set internal bool IsSetInstanceTenancy() { return this._instanceTenancy != null; } /// <summary> /// Gets and sets the property InstanceType. /// <para> /// The instance type on which the Reserved Instance can be used. /// </para> /// </summary> public InstanceType InstanceType { get { return this._instanceType; } set { this._instanceType = value; } } // Check to see if InstanceType property is set internal bool IsSetInstanceType() { return this._instanceType != null; } /// <summary> /// Gets and sets the property OfferingType. /// <para> /// The Reserved Instance offering type. /// </para> /// </summary> public OfferingTypeValues OfferingType { get { return this._offeringType; } set { this._offeringType = value; } } // Check to see if OfferingType property is set internal bool IsSetOfferingType() { return this._offeringType != null; } /// <summary> /// Gets and sets the property ProductDescription. /// <para> /// The Reserved Instance description. /// </para> /// </summary> public RIProductDescription ProductDescription { get { return this._productDescription; } set { this._productDescription = value; } } // Check to see if ProductDescription property is set internal bool IsSetProductDescription() { return this._productDescription != null; } /// <summary> /// Gets and sets the property RecurringCharges. /// <para> /// The recurring charge tag assigned to the resource. /// </para> /// </summary> public List<RecurringCharge> RecurringCharges { get { return this._recurringCharges; } set { this._recurringCharges = value; } } // Check to see if RecurringCharges property is set internal bool IsSetRecurringCharges() { return this._recurringCharges != null && this._recurringCharges.Count > 0; } /// <summary> /// Gets and sets the property ReservedInstancesId. /// <para> /// The ID of the Reserved Instance. /// </para> /// </summary> public string ReservedInstancesId { get { return this._reservedInstancesId; } set { this._reservedInstancesId = value; } } // Check to see if ReservedInstancesId property is set internal bool IsSetReservedInstancesId() { return this._reservedInstancesId != null; } /// <summary> /// Gets and sets the property Start. /// <para> /// The date and time the Reserved Instance started. /// </para> /// </summary> public DateTime Start { get { return this._start.GetValueOrDefault(); } set { this._start = value; } } // Check to see if Start property is set internal bool IsSetStart() { return this._start.HasValue; } /// <summary> /// Gets and sets the property State. /// <para> /// The state of the Reserved Instance purchase. /// </para> /// </summary> public ReservedInstanceState State { get { return this._state; } set { this._state = value; } } // Check to see if State property is set internal bool IsSetState() { return this._state != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// Any tags assigned to the resource. /// </para> /// </summary> public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } /// <summary> /// Gets and sets the property UsagePrice. /// <para> /// The usage price of the Reserved Instance, per hour. /// </para> /// </summary> public float UsagePrice { get { return this._usagePrice.GetValueOrDefault(); } set { this._usagePrice = value; } } // Check to see if UsagePrice property is set internal bool IsSetUsagePrice() { return this._usagePrice.HasValue; } } }
using System; using System.Collections.Generic; using DevExpress.CodeRush.StructuralParser; using DevExpress.CodeRush.Core; using System.Text.RegularExpressions; namespace CR_SuperSiblingNav { public class ElementLocation { LanguageElementType _ElementType; bool _IsDetailNode; int _PreviousMatchingSiblings; ElementLocation _Child; CaretVector _Vector; private static int CalculatePreviousMatchingSiblings(ElementLocation elementLocation, LanguageElement testElement) { int previousSiblings = 0; NodeList nodes; LanguageElement testElementParent = testElement.Parent; if (testElementParent == null) return 0; if (testElement.IsDetailNode) nodes = testElementParent.DetailNodes; else nodes = testElementParent.Nodes; foreach (LanguageElement element in nodes) { if (element == testElement) break; if (element.ElementType == elementLocation._ElementType) previousSiblings++; } return previousSiblings; } private static void AddAllVectors(List<CaretVector> locations, LanguageElement element, SourcePoint target) { locations.Add(CaretVector.From(target, element.Range.Start, ElementPosition.Start)); locations.Add(CaretVector.From(target, element.Range.End, ElementPosition.End)); locations.Add(CaretVector.From(target, element.NameRange.Start, ElementPosition.NameRangeStart)); locations.Add(CaretVector.From(target, element.NameRange.End, ElementPosition.NameRangeEnd)); if (element is ICapableBlock) { ICapableBlock iCapableBlock = (ICapableBlock)element; if (iCapableBlock.HasDelimitedBlock) { locations.Add(CaretVector.From(target, iCapableBlock.BlockStart.End, ElementPosition.BlockBegin)); locations.Add(CaretVector.From(target, iCapableBlock.BlockEnd.Start, ElementPosition.BlockEnd)); } } if (element.FirstChild != null) locations.Add(CaretVector.From(target, element.FirstChild.Range.Start, ElementPosition.FirstChildStart)); if (element.LastChild != null) locations.Add(CaretVector.From(target, element.LastChild.Range.End, ElementPosition.LastChildEnd)); if (element.FirstDetail != null) locations.Add(CaretVector.From(target, element.FirstDetail.Range.Start, ElementPosition.FirstDetailStart)); if (element.LastDetail != null) locations.Add(CaretVector.From(target, element.LastDetail.Range.End, ElementPosition.LastDetailEnd)); } private static SourcePoint GetPosition(SourcePoint sourcePoint, CaretVector vector) { return sourcePoint.OffsetPoint(vector.LineDelta, vector.OffsetDelta); } private SourcePoint GetSourcePoint(LanguageElement element, CaretVector vector) { if (element == null || vector == null) return SourcePoint.Empty; ICapableBlock iCapableBlock = null; switch (vector.ElementPosition) { case ElementPosition.Start: return GetPosition(element.Range.Start, vector); case ElementPosition.End: return GetPosition(element.Range.End, vector); case ElementPosition.NameRangeStart: return GetPosition(element.NameRange.Start, vector); case ElementPosition.NameRangeEnd: return GetPosition(element.NameRange.End, vector); case ElementPosition.BlockBegin: iCapableBlock = element as ICapableBlock; if (iCapableBlock != null) return GetPosition(iCapableBlock.BlockStart.End, vector); else return GetPosition(element.Range.Start, vector); case ElementPosition.BlockEnd: iCapableBlock = element as ICapableBlock; if (iCapableBlock != null) return GetPosition(iCapableBlock.BlockEnd.Start, vector); else return GetPosition(element.Range.End, vector); case ElementPosition.FirstChildStart: LanguageElement firstChild = element.FirstChild; if (firstChild == null) return SourcePoint.Empty; return GetPosition(firstChild.Range.Start, vector); case ElementPosition.LastChildEnd: LanguageElement lastChild = element.LastChild; if (lastChild == null) return SourcePoint.Empty; return GetPosition(lastChild.Range.End, vector); case ElementPosition.FirstDetailStart: LanguageElement firstDetail = element.FirstDetail; if (firstDetail == null) return SourcePoint.Empty; return GetPosition(firstDetail.Range.Start, vector); case ElementPosition.LastDetailEnd: LanguageElement lastDetail = element.LastDetail; if (lastDetail == null) return SourcePoint.Empty; return GetPosition(lastDetail.Range.End, vector); } throw new Exception("Unexpected ElementPosition enum element."); } private LanguageElement FindNthElement(NodeList nodes, int count, LanguageElementType elementType) { LanguageElement lastElementFound = null; if (nodes == null) return null; int numFound = 0; foreach (LanguageElement element in nodes) { if (element.ElementType == elementType) { numFound++; if (numFound == count) return element; lastElementFound = element; } } return lastElementFound; } private LanguageElement GetChildElement(LanguageElement element, ElementLocation location) { if (element == null || location == null) return null; NodeList nodes; if (location._IsDetailNode) nodes = element.DetailNodes; else nodes = element.Nodes; return FindNthElement(nodes, location._PreviousMatchingSiblings + 1, location._ElementType); } private SourcePoint GetDefaultPosition(LanguageElement element) { return GetSourcePoint(element, new CaretVector(_Vector.ElementPosition)); } public SourcePoint GetBestLocation(LanguageElement element) { int smallestLineDeltaSoFar = int.MaxValue; int smallestOffsetDeltaSoFar = int.MaxValue; ElementLocation location = this; SourcePoint result = SourcePoint.Empty; LanguageElement parent = null; while (location != null && element != null) { CaretVector vector = location._Vector; int lineDeltaSize = Math.Abs(vector.LineDelta); int offsetDeltaSize = Math.Abs(vector.OffsetDelta); if (lineDeltaSize < smallestLineDeltaSoFar || (lineDeltaSize == smallestLineDeltaSoFar && offsetDeltaSize < smallestOffsetDeltaSoFar)) { // Found a smaller vector... SourcePoint newPosition = GetSourcePoint(element, vector); if (newPosition != SourcePoint.Empty) { result = newPosition; smallestLineDeltaSoFar = lineDeltaSize; smallestOffsetDeltaSoFar = offsetDeltaSize; if (lineDeltaSize == 0 && offsetDeltaSize == 0) if (vector.ElementPosition != ElementPosition.LastDetailEnd || element.ElementType != LanguageElementType.Method && element.ElementType != LanguageElementType.Property) return result; } } location = location._Child; parent = element; element = GetChildElement(element, location); if (location != null && element == null) { // We were expecting a child but found nothing... if (location._ElementType == LanguageElementType.Parameter) { Method method = parent as Method; if (method != null) return method.ParamOpenRange.End; else { Property property = parent as Property; if (property != null) return property.NameRange.End; } } else { SourcePoint newDefaultPosition = GetDefaultPosition(parent); if (newDefaultPosition != SourcePoint.Empty) return newDefaultPosition; } } } return result; } private static CaretVector GetClosestVector(LanguageElement element, SourcePoint target) { List<CaretVector> locations = new List<CaretVector>(); AddAllVectors(locations, element, target); locations.Sort(new VectorComparer()); if (locations.Count > 0) return locations[0]; return null; } private static ElementLocation FromLanguageElement(LanguageElement element, SourcePoint target) { ElementLocation elementLocation = new ElementLocation(); elementLocation._ElementType = element.ElementType; elementLocation._IsDetailNode = element.IsDetailNode; elementLocation._PreviousMatchingSiblings = CalculatePreviousMatchingSiblings(elementLocation, element); elementLocation._Vector = GetClosestVector(element, target); return elementLocation; } public static ElementLocation From(LanguageElement methodOrProperty, SourcePoint sourcePoint) { LanguageElement element = CodeRush.Source.GetNodeAt(sourcePoint); if (element == null) return null; ElementLocation elementLocation = null; ElementLocation childLocation = null; while (true) { elementLocation = FromLanguageElement(element, sourcePoint); elementLocation._Child = childLocation; childLocation = elementLocation; if (element == methodOrProperty) break; element = element.Parent; if (element == null) break; } return elementLocation; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; namespace Microsoft.Azure.Management.Automation { public static partial class RunbookDraftOperationsExtensions { /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the publish runbook operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResultResponse BeginPublish(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, RunbookDraftPublishParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookDraftOperations)s).BeginPublishAsync(resourceGroupName, automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the publish runbook operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResultResponse> BeginPublishAsync(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, RunbookDraftPublishParameters parameters) { return operations.BeginPublishAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None); } /// <summary> /// Updates the runbook draft with runbookStream as its content. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The runbook draft update parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResultResponse BeginUpdate(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookDraftOperations)s).BeginUpdateAsync(resourceGroupName, automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the runbook draft with runbookStream as its content. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The runbook draft update parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResultResponse> BeginUpdateAsync(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters) { return operations.BeginUpdateAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None); } /// <summary> /// Updates the runbook draft with runbookStream as its content. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The runbook draft update parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResultResponse BeginUpdateGraph(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookDraftOperations)s).BeginUpdateGraphAsync(resourceGroupName, automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the runbook draft with runbookStream as its content. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The runbook draft update parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResultResponse> BeginUpdateGraphAsync(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters) { return operations.BeginUpdateGraphAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None); } /// <summary> /// Retrieve the content of runbook draft identified by runbook name. /// (see http://aka.ms/azureautomationsdk/runbookdraftoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the runbook content operation. /// </returns> public static RunbookContentResponse Content(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, string runbookName) { return Task.Factory.StartNew((object s) => { return ((IRunbookDraftOperations)s).ContentAsync(resourceGroupName, automationAccount, runbookName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the content of runbook draft identified by runbook name. /// (see http://aka.ms/azureautomationsdk/runbookdraftoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the runbook content operation. /// </returns> public static Task<RunbookContentResponse> ContentAsync(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, string runbookName) { return operations.ContentAsync(resourceGroupName, automationAccount, runbookName, CancellationToken.None); } /// <summary> /// Retrieve the runbook draft identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the get runbook draft operation. /// </returns> public static RunbookDraftGetResponse Get(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, string runbookName) { return Task.Factory.StartNew((object s) => { return ((IRunbookDraftOperations)s).GetAsync(resourceGroupName, automationAccount, runbookName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the runbook draft identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the get runbook draft operation. /// </returns> public static Task<RunbookDraftGetResponse> GetAsync(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, string runbookName) { return operations.GetAsync(resourceGroupName, automationAccount, runbookName, CancellationToken.None); } /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the publish runbook operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResultResponse Publish(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, RunbookDraftPublishParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookDraftOperations)s).PublishAsync(resourceGroupName, automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the publish runbook operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResultResponse> PublishAsync(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, RunbookDraftPublishParameters parameters) { return operations.PublishAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None); } /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the undoedit runbook operation. /// </returns> public static RunbookDraftUndoEditResponse UndoEdit(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, string runbookName) { return Task.Factory.StartNew((object s) => { return ((IRunbookDraftOperations)s).UndoEditAsync(resourceGroupName, automationAccount, runbookName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the undoedit runbook operation. /// </returns> public static Task<RunbookDraftUndoEditResponse> UndoEditAsync(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, string runbookName) { return operations.UndoEditAsync(resourceGroupName, automationAccount, runbookName, CancellationToken.None); } /// <summary> /// Updates the runbook draft with runbookStream as its content. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The runbook draft update parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResultResponse Update(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookDraftOperations)s).UpdateAsync(resourceGroupName, automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the runbook draft with runbookStream as its content. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The runbook draft update parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResultResponse> UpdateAsync(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None); } /// <summary> /// Updates the runbook draft with runbookStream as its content. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The runbook draft update parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResultResponse UpdateGraph(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookDraftOperations)s).UpdateGraphAsync(resourceGroupName, automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the runbook draft with runbookStream as its content. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The runbook draft update parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResultResponse> UpdateGraphAsync(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters) { return operations.UpdateGraphAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; namespace System.Diagnostics.Eventing { public class EventProviderTraceListener : TraceListener { // // The listener uses the EtwProvider base class. // Because Listener data is not schematized at the moment the listener will // log events using WriteMessageEvent method. // // Because WriteMessageEvent takes a string as the event payload // all the overridden logging methods convert the arguments into strings. // Event payload is "delimiter" separated, which can be configured // // private EventProvider _provider; private const string s_nullStringValue = "null"; private const string s_nullStringComaValue = "null,"; private const string s_nullCStringValue = ": null"; private string _delimiter = ";"; private const uint s_keyWordMask = 0xFFFFFF00; private const int s_defaultPayloadSize = 512; [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public string Delimiter { get { return _delimiter; } [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] set { if (value == null) throw new ArgumentNullException(nameof(Delimiter)); if (value.Length == 0) throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter); _delimiter = value; } } /// <summary> /// This method creates an instance of the ETW provider. /// The guid argument must be a valid GUID or a format exception will be /// thrown when creating an instance of the ControlGuid. /// We need to be running on Vista or above. If not an /// PlatformNotSupported exception will be thrown by the EventProvider. /// </summary> public EventProviderTraceListener(string providerId) { InitProvider(providerId); } public EventProviderTraceListener(string providerId, string name) : base(name) { InitProvider(providerId); } public EventProviderTraceListener(string providerId, string name, string delimiter) : base(name) { if (delimiter == null) throw new ArgumentNullException(nameof(delimiter)); if (delimiter.Length == 0) throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter); _delimiter = delimiter; InitProvider(providerId); } private void InitProvider(string providerId) { Guid controlGuid = new(providerId); // // Create The ETW TraceProvider // _provider = new EventProvider(controlGuid); } // // override Listener methods // public sealed override void Flush() { } public sealed override bool IsThreadSafe { get { return true; } } protected override void Dispose(bool disposing) { if (disposing) { _provider.Close(); } } public sealed override void Write(string message) { if (!_provider.IsEnabled()) { return; } _provider.WriteMessageEvent(message, (byte)TraceEventType.Information, 0); } public sealed override void WriteLine(string message) { Write(message); } // // For all the methods below the string to be logged contains: // m_delimiter separated data converted to string // // The source parameter is ignored. // public sealed override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) { if (!_provider.IsEnabled()) { return; } if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) { return; } StringBuilder dataString = new(s_defaultPayloadSize); if (data != null) { dataString.Append(data.ToString()); } else { dataString.Append(s_nullCStringValue); } _provider.WriteMessageEvent(dataString.ToString(), (byte)eventType, (long)eventType & s_keyWordMask); } public sealed override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, params object[] data) { if (!_provider.IsEnabled()) { return; } if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) { return; } int index; StringBuilder dataString = new(s_defaultPayloadSize); if ((data != null) && (data.Length > 0)) { for (index = 0; index < (data.Length - 1); index++) { if (data[index] != null) { dataString.Append(data[index].ToString()); dataString.Append(Delimiter); } else { dataString.Append(s_nullStringComaValue); } } if (data[index] != null) { dataString.Append(data[index].ToString()); } else { dataString.Append(s_nullStringValue); } } else { dataString.Append(s_nullStringValue); } _provider.WriteMessageEvent(dataString.ToString(), (byte)eventType, (long)eventType & s_keyWordMask); } public sealed override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id) { if (!_provider.IsEnabled()) { return; } if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) { return; } _provider.WriteMessageEvent(string.Empty, (byte)eventType, (long)eventType & s_keyWordMask); } public sealed override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { if (!_provider.IsEnabled()) { return; } if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) { return; } StringBuilder dataString = new(s_defaultPayloadSize); dataString.Append(message); _provider.WriteMessageEvent(dataString.ToString(), (byte)eventType, (long)eventType & s_keyWordMask); } public sealed override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) { if (!_provider.IsEnabled()) { return; } if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) { return; } if (args == null) { _provider.WriteMessageEvent(format, (byte)eventType, (long)eventType & s_keyWordMask); } else { _provider.WriteMessageEvent(string.Format(CultureInfo.InvariantCulture, format, args), (byte)eventType, (long)eventType & s_keyWordMask); } } public override void Fail(string message, string detailMessage) { StringBuilder failMessage = new(message); if (detailMessage != null) { failMessage.Append(' '); failMessage.Append(detailMessage); } this.TraceEvent(null, null, TraceEventType.Error, 0, failMessage.ToString()); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace MVCApiTest.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Text { // An Encoder is used to encode a sequence of blocks of characters into // a sequence of blocks of bytes. Following instantiation of an encoder, // sequential blocks of characters are converted into blocks of bytes through // calls to the GetBytes method. The encoder maintains state between the // conversions, allowing it to correctly encode character sequences that span // adjacent blocks. // // Instances of specific implementations of the Encoder abstract base // class are typically obtained through calls to the GetEncoder method // of Encoding objects. // public abstract class Encoder { internal EncoderFallback? _fallback = null; internal EncoderFallbackBuffer? _fallbackBuffer = null; protected Encoder() { // We don't call default reset because default reset probably isn't good if we aren't initialized. } public EncoderFallback? Fallback { get => _fallback; set { if (value == null) throw new ArgumentNullException(nameof(value)); // Can't change fallback if buffer is wrong if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) throw new ArgumentException( SR.Argument_FallbackBufferNotEmpty, nameof(value)); _fallback = value; _fallbackBuffer = null; } } // Note: we don't test for threading here because async access to Encoders and Decoders // doesn't work anyway. public EncoderFallbackBuffer FallbackBuffer { get { if (_fallbackBuffer == null) { if (_fallback != null) _fallbackBuffer = _fallback.CreateFallbackBuffer(); else _fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer(); } return _fallbackBuffer; } } internal bool InternalHasFallbackBuffer => _fallbackBuffer != null; // Reset the Encoder // // Normally if we call GetBytes() and an error is thrown we don't change the state of the encoder. This // would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.) // // If the caller doesn't want to try again after GetBytes() throws an error, then they need to call Reset(). // // Virtual implementation has to call GetBytes with flush and a big enough buffer to clear a 0 char string // We avoid GetMaxByteCount() because a) we can't call the base encoder and b) it might be really big. public virtual void Reset() { char[] charTemp = Array.Empty<char>(); byte[] byteTemp = new byte[GetByteCount(charTemp, 0, 0, true)]; GetBytes(charTemp, 0, 0, byteTemp, 0, true); if (_fallbackBuffer != null) _fallbackBuffer.Reset(); } // Returns the number of bytes the next call to GetBytes will // produce if presented with the given range of characters and the given // value of the flush parameter. The returned value takes into // account the state in which the encoder was left following the last call // to GetBytes. The state of the encoder is not affected by a call // to this method. // public abstract int GetByteCount(char[] chars, int index, int count, bool flush); // We expect this to be the workhorse for NLS encodings // unfortunately for existing overrides, it has to call the [] version, // which is really slow, so avoid this method if you might be calling external encodings. [CLSCompliant(false)] public virtual unsafe int GetByteCount(char* chars, int count, bool flush) { // Validate input parameters if (chars == null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); char[] arrChar = new char[count]; int index; for (index = 0; index < count; index++) arrChar[index] = chars[index]; return GetByteCount(arrChar, 0, count, flush); } public virtual unsafe int GetByteCount(ReadOnlySpan<char> chars, bool flush) { fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) { return GetByteCount(charsPtr, chars.Length, flush); } } // Encodes a range of characters in a character array into a range of bytes // in a byte array. The method encodes charCount characters from // chars starting at index charIndex, storing the resulting // bytes in bytes starting at index byteIndex. The encoding // takes into account the state in which the encoder was left following the // last call to this method. The flush parameter indicates whether // the encoder should flush any shift-states and partial characters at the // end of the conversion. To ensure correct termination of a sequence of // blocks of encoded bytes, the last call to GetBytes should specify // a value of true for the flush parameter. // // An exception occurs if the byte array is not large enough to hold the // complete encoding of the characters. The GetByteCount method can // be used to determine the exact number of bytes that will be produced for // a given range of characters. Alternatively, the GetMaxByteCount // method of the Encoding that produced this encoder can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // public abstract int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush); // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implementation) // // WARNING WARNING WARNING // // WARNING: If this breaks it could be a security threat. Obviously we // call this internally, so you need to make sure that your pointers, counts // and indexes are correct when you call this method. // // In addition, we have internal code, which will be marked as "safe" calling // this code. However this code is dependent upon the implementation of an // external GetBytes() method, which could be overridden by a third party and // the results of which cannot be guaranteed. We use that result to copy // the byte[] to our byte* output buffer. If the result count was wrong, we // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow byteCount either. [CLSCompliant(false)] public virtual unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { // Validate input parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Get the char array to convert char[] arrChar = new char[charCount]; int index; for (index = 0; index < charCount; index++) arrChar[index] = chars[index]; // Get the byte array to fill byte[] arrByte = new byte[byteCount]; // Do the work int result = GetBytes(arrChar, 0, charCount, arrByte, 0, flush); Debug.Assert(result <= byteCount, "Returned more bytes than we have space for"); // Copy the byte array // WARNING: We MUST make sure that we don't copy too many bytes. We can't // rely on result because it could be a 3rd party implementation. We need // to make sure we never copy more than byteCount bytes no matter the value // of result if (result < byteCount) byteCount = result; // Don't copy too many bytes! for (index = 0; index < byteCount; index++) bytes[index] = arrByte[index]; return byteCount; } public virtual unsafe int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool flush) { fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { return GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length, flush); } } // This method is used to avoid running out of output buffer space. // It will encode until it runs out of chars, and then it will return // true if it the entire input was converted. In either case it // will also return the number of converted chars and output bytes used. // It will only throw a buffer overflow exception if the entire lenght of bytes[] is // too small to store the next byte. (like 0 or maybe 1 or 4 for some encodings) // We're done processing this buffer only if completed returns true. // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input chars are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many chars as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) public virtual void Convert(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); charsUsed = charCount; // Its easy to do if it won't overrun our buffer. // Note: We don't want to call unsafe version because that might be an untrusted version // which could be really unsafe and we don't want to mix it up. while (charsUsed > 0) { if (GetByteCount(chars, charIndex, charsUsed, flush) <= byteCount) { bytesUsed = GetBytes(chars, charIndex, charsUsed, bytes, byteIndex, flush); completed = (charsUsed == charCount && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; charsUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(SR.Argument_ConversionOverflow); } // Same thing, but using pointers // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input chars are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many chars as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) [CLSCompliant(false)] public virtual unsafe void Convert(char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate input parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Get ready to do it charsUsed = charCount; // Its easy to do if it won't overrun our buffer. while (charsUsed > 0) { if (GetByteCount(chars, charsUsed, flush) <= byteCount) { bytesUsed = GetBytes(chars, charsUsed, bytes, byteCount, flush); completed = (charsUsed == charCount && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; charsUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(SR.Argument_ConversionOverflow); } public virtual unsafe void Convert(ReadOnlySpan<char> chars, Span<byte> bytes, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { Convert(charsPtr, chars.Length, bytesPtr, bytes.Length, flush, out charsUsed, out bytesUsed, out completed); } } } }
// // const.cs: Constant declarations. // // Author: // Miguel de Icaza (miguel@ximian.com) // Marek Safar (marek.safar@seznam.cz) // // Copyright 2001-2003 Ximian, Inc. // Copyright 2003-2008 Novell, Inc. // #if STATIC using IKVM.Reflection; #else using System.Reflection; #endif namespace Mono.CSharp { public class Const : FieldBase { const Modifiers AllowedModifiers = Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE; public Const (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs) : base (parent, type, mod_flags, AllowedModifiers, name, attrs) { ModFlags |= Modifiers.STATIC; } /// <summary> /// Defines the constant in the @parent /// </summary> public override bool Define () { if (!base.Define ()) return false; if (!member_type.IsConstantCompatible) { Error_InvalidConstantType (member_type, Location, Report); } FieldAttributes field_attr = FieldAttributes.Static | ModifiersExtensions.FieldAttr (ModFlags); // Decimals cannot be emitted into the constant blob. So, convert to 'readonly'. if (member_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) { field_attr |= FieldAttributes.InitOnly; } else { field_attr |= FieldAttributes.Literal; } FieldBuilder = Parent.TypeBuilder.DefineField (Name, MemberType.GetMetaInfo (), field_attr); spec = new ConstSpec (Parent.Definition, this, MemberType, FieldBuilder, ModFlags, initializer); Parent.MemberCache.AddMember (spec); if ((field_attr & FieldAttributes.InitOnly) != 0) Parent.PartialContainer.RegisterFieldForInitialization (this, new FieldInitializer (this, initializer, Location)); if (declarators != null) { var t = new TypeExpression (MemberType, TypeExpression.Location); foreach (var d in declarators) { var c = new Const (Parent, t, ModFlags & ~Modifiers.STATIC, new MemberName (d.Name.Value, d.Name.Location), OptAttributes); c.initializer = d.Initializer; ((ConstInitializer) c.initializer).Name = d.Name.Value; c.Define (); Parent.PartialContainer.Members.Add (c); } } return true; } public void DefineValue () { var rc = new ResolveContext (this); ((ConstSpec) spec).GetConstant (rc); } /// <summary> /// Emits the field value by evaluating the expression /// </summary> public override void Emit () { var c = ((ConstSpec) spec).Value as Constant; if (c.Type.BuiltinType == BuiltinTypeSpec.Type.Decimal) { Module.PredefinedAttributes.DecimalConstant.EmitAttribute (FieldBuilder, (decimal) c.GetValue (), c.Location); } else { FieldBuilder.SetConstant (c.GetValue ()); } base.Emit (); } public static void Error_InvalidConstantType (TypeSpec t, Location loc, Report Report) { if (t.IsGenericParameter) { Report.Error (1959, loc, "Type parameter `{0}' cannot be declared const", t.GetSignatureForError ()); } else { Report.Error (283, loc, "The type `{0}' cannot be declared const", t.GetSignatureForError ()); } } public override void Accept (StructuralVisitor visitor) { visitor.Visit (this); } public override void PrepareEmit () { base.PrepareEmit (); DefineValue (); } } public class ConstSpec : FieldSpec { Expression value; public ConstSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, FieldInfo fi, Modifiers mod, Expression value) : base (declaringType, definition, memberType, fi, mod) { this.value = value; } // // This expresion is guarantee to be a constant at emit phase only // public Expression Value { get { return value; } } // // For compiled constants we have to resolve the value as there could be constant dependecies. This // is needed for imported constants too to get the right context type // public Constant GetConstant (ResolveContext rc) { if (value.eclass != ExprClass.Value) value = value.Resolve (rc); return (Constant) value; } } public class ConstInitializer : ShimExpression { bool in_transit; readonly FieldBase field; public ConstInitializer (FieldBase field, Expression value, Location loc) : base (value) { this.loc = loc; this.field = field; } public string Name { get; set; } protected override Expression DoResolve (ResolveContext unused) { if (type != null) return expr; var opt = ResolveContext.Options.ConstantScope; if (field is EnumMember) opt |= ResolveContext.Options.EnumScope; // // Use a context in which the constant was declared and // not the one in which is referenced // var rc = new ResolveContext (field, opt); expr = DoResolveInitializer (rc); type = expr.Type; return expr; } protected virtual Expression DoResolveInitializer (ResolveContext rc) { if (in_transit) { field.Compiler.Report.Error (110, expr.Location, "The evaluation of the constant value for `{0}' involves a circular definition", GetSignatureForError ()); expr = null; } else { in_transit = true; expr = expr.Resolve (rc); } in_transit = false; if (expr != null) { Constant c = expr as Constant; if (c != null) c = field.ConvertInitializer (rc, c); if (c == null) { if (TypeSpec.IsReferenceType (field.MemberType)) Error_ConstantCanBeInitializedWithNullOnly (rc, field.MemberType, expr.Location, GetSignatureForError ()); else if (!(expr is Constant)) Error_ExpressionMustBeConstant (rc, expr.Location, GetSignatureForError ()); else expr.Error_ValueCannotBeConverted (rc, field.MemberType, false); } expr = c; } if (expr == null) { expr = New.Constantify (field.MemberType, Location); if (expr == null) expr = Constant.CreateConstantFromValue (field.MemberType, null, Location); expr = expr.Resolve (rc); } return expr; } public override string GetSignatureForError () { if (Name == null) return field.GetSignatureForError (); return field.Parent.GetSignatureForError () + "." + Name; } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } }
// StrangeCRC.cs - computes a crc used in the bziplib // // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. // 2010-08-13 Sky Sanders - Modified for Silverlight 3/4 and Windows Phone 7 using System; namespace ICSharpCode.SharpZipLib.Checksums { /// <summary> /// Bzip2 checksum algorithm /// </summary> class StrangeCRC : IChecksum { readonly static uint[] crc32Table = { 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95, 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3, 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 }; int globalCrc; /// <summary> /// Initialise a default instance of <see cref="StrangeCRC"></see> /// </summary> public StrangeCRC() { Reset(); } /// <summary> /// Reset the state of Crc. /// </summary> public void Reset() { globalCrc = -1; } /// <summary> /// Get the current Crc value. /// </summary> public long Value { get { return ~globalCrc; } } /// <summary> /// Update the Crc value. /// </summary> /// <param name="value">data update is based on</param> public void Update(int value) { int temp = (globalCrc >> 24) ^ value; if (temp < 0) { temp = 256 + temp; } globalCrc = unchecked((int)((globalCrc << 8) ^ crc32Table[temp])); } /// <summary> /// Update Crc based on a block of data /// </summary> /// <param name="buffer">The buffer containing data to update the crc with.</param> public void Update(byte[] buffer) { if (buffer == null) { throw new ArgumentNullException("buffer"); } Update(buffer, 0, buffer.Length); } /// <summary> /// Update Crc based on a portion of a block of data /// </summary> /// <param name="buffer">block of data</param> /// <param name="offset">index of first byte to use</param> /// <param name="count">number of bytes to use</param> public void Update(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if ( offset < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("offset"); #else throw new ArgumentOutOfRangeException("offset", "cannot be less than zero"); #endif } if ( count < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "cannot be less than zero"); #endif } if ( offset + count > buffer.Length ) { throw new ArgumentOutOfRangeException("count"); } for (int i = 0; i < count; ++i) { Update(buffer[offset++]); } } } }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Threading; using WebSocketSharp; namespace Example1 { internal class AudioStreamer : IDisposable { private Dictionary<uint, Queue> _audioBox; private Timer _heartbeatTimer; private uint? _id; private string _name; private Notifier _notifier; private WebSocket _websocket; public AudioStreamer (string url) { _websocket = new WebSocket (url); _audioBox = new Dictionary<uint, Queue> (); _heartbeatTimer = new Timer (sendHeartbeat, null, -1, -1); _id = null; _notifier = new Notifier (); configure (); } private void configure () { #if DEBUG _websocket.Log.Level = LogLevel.Trace; #endif _websocket.OnOpen += (sender, e) => _websocket.Send (createTextMessage ("connection", String.Empty)); _websocket.OnMessage += (sender, e) => { if (e.Type == Opcode.Text) { _notifier.Notify (convertTextMessage (e.Data)); } else { var msg = convertBinaryMessage (e.RawData); if (msg.user_id == _id) return; if (_audioBox.ContainsKey (msg.user_id)) { _audioBox[msg.user_id].Enqueue (msg.buffer_array); return; } var queue = Queue.Synchronized (new Queue ()); queue.Enqueue (msg.buffer_array); _audioBox.Add (msg.user_id, queue); } }; _websocket.OnError += (sender, e) => _notifier.Notify ( new NotificationMessage { Summary = "AudioStreamer (error)", Body = e.Message, Icon = "notification-message-im" }); _websocket.OnClose += (sender, e) => _notifier.Notify ( new NotificationMessage { Summary = "AudioStreamer (disconnect)", Body = String.Format ("code: {0} reason: {1}", e.Code, e.Reason), Icon = "notification-message-im" }); } private AudioMessage convertBinaryMessage (byte[] data) { var id = data.SubArray (0, 4).To<uint> (ByteOrder.Big); var chNum = data.SubArray (4, 1)[0]; var buffLen = data.SubArray (5, 4).To<uint> (ByteOrder.Big); var buffArr = new float[chNum, buffLen]; var offset = 9; ((int) chNum).Times ( i => buffLen.Times ( j => { buffArr[i, j] = data.SubArray (offset, 4).To<float> (ByteOrder.Big); offset += 4; })); return new AudioMessage { user_id = id, ch_num = chNum, buffer_length = buffLen, buffer_array = buffArr }; } private NotificationMessage convertTextMessage (string data) { var json = JObject.Parse (data); var id = (uint) json["user_id"]; var name = (string) json["name"]; var type = (string) json["type"]; string body; if (type == "message") { body = String.Format ("{0}: {1}", name, (string) json["message"]); } else if (type == "start_music") { body = String.Format ("{0}: Started playing music!", name); } else if (type == "connection") { var users = (JArray) json["message"]; var buff = new StringBuilder ("Now keeping connections:"); foreach (JToken user in users) buff.AppendFormat ( "\n- user_id: {0} name: {1}", (uint) user["user_id"], (string) user["name"]); body = buff.ToString (); } else if (type == "connected") { _id = id; _heartbeatTimer.Change (30000, 30000); body = String.Format ("user_id: {0} name: {1}", id, name); } else { body = "Received unknown type message."; } return new NotificationMessage { Summary = String.Format ("AudioStreamer ({0})", type), Body = body, Icon = "notification-message-im" }; } private byte[] createBinaryMessage (float[,] bufferArray) { var msg = new List<byte> (); var id = (uint) _id; var chNum = bufferArray.GetLength (0); var buffLen = bufferArray.GetLength (1); msg.AddRange (id.ToByteArray (ByteOrder.Big)); msg.Add ((byte) chNum); msg.AddRange (((uint) buffLen).ToByteArray (ByteOrder.Big)); chNum.Times ( i => buffLen.Times ( j => msg.AddRange (bufferArray[i, j].ToByteArray (ByteOrder.Big)))); return msg.ToArray (); } private string createTextMessage (string type, string message) { return JsonConvert.SerializeObject ( new TextMessage { user_id = _id, name = _name, type = type, message = message }); } private void sendHeartbeat (object state) { _websocket.Send (createTextMessage ("heartbeat", String.Empty)); } public void Connect (string username) { _name = username; _websocket.Connect (); } public void Disconnect () { _heartbeatTimer.Change (-1, -1); _websocket.Close (CloseStatusCode.Away); _audioBox.Clear (); _id = null; _name = null; } public void Write (string message) { _websocket.Send (createTextMessage ("message", message)); } void IDisposable.Dispose () { Disconnect (); _heartbeatTimer.Dispose (); _notifier.Close (); } } }
using System; using MonoMac.Foundation; using MonoMac.ObjCRuntime; namespace MonoMac.CoreData { [BaseType (typeof (NSPersistentStore))] public interface NSAtomicStore { [Export ("initWithPersistentStoreCoordinator:configurationName:URL:options:")] IntPtr Constructor (NSPersistentStoreCoordinator coordinator, string configurationName, NSUrl url, NSDictionary options); [Export ("load:")] bool Load (out NSError error); [Export ("save:")] bool Save (out NSError error); [Export ("newCacheNodeForManagedObject:")] NSAtomicStoreCacheNode NewCacheNodeForManagedObject (NSManagedObject managedObject); [Export ("updateCacheNode:fromManagedObject:")] void UpdateCacheNode (NSAtomicStoreCacheNode node, NSManagedObject managedObject); [Export ("cacheNodes")] NSSet CacheNodes { get; } [Export ("addCacheNodes:")] void AddCacheNodes (NSSet cacheNodes); [Export ("willRemoveCacheNodes:")] void WillRemoveCacheNodes (NSSet cacheNodes); [Export ("cacheNodeForObjectID:")] NSAtomicStoreCacheNode CacheNodeForObjectID (NSManagedObjectID objectID); [Export ("objectIDForEntity:referenceObject:")] NSManagedObjectID ObjectIDForEntity (NSEntityDescription entity, NSObject data); [Export ("newReferenceObjectForManagedObject:")] NSAtomicStore NewReferenceObjectForManagedObject (NSManagedObject managedObject); [Export ("referenceObjectForObjectID:")] NSAtomicStore ReferenceObjectForObjectID (NSManagedObjectID objectID); } [BaseType (typeof (NSObject))] public interface NSAtomicStoreCacheNode { [Export ("initWithObjectID:")] IntPtr Constructor (NSManagedObjectID moid); [Export ("objectID")] NSManagedObjectID ObjectID { get; } [Export ("propertyCache")] NSDictionary PropertyCache { get; set; } [Export ("valueForKey:")] NSAtomicStoreCacheNode ValueForKey (string key); [Export ("setValue:forKey:")] void SetValue (NSObject value, string key); } [BaseType (typeof (NSPropertyDescription))] public interface NSAttributeDescription { [Export ("attributeType")] NSAttributeType AttributeType { get; set; } [Export ("attributeValueClassName")] string AttributeValueClassName { get; set; } [Export ("defaultValue")] NSAttributeDescription DefaultValue { get; } [Export ("setDefaultValue:")] void SetDefaultValue (NSObject value); [Export ("versionHash")] NSData VersionHash { get; } [Export ("valueTransformerName")] string ValueTransformerName { get; set; } } [BaseType (typeof (NSObject))] public interface NSEntityDescription { [Static, Export ("entityForName:inManagedObjectContext:")] NSEntityDescription EntityForName (string entityName, NSManagedObjectContext context); [Static, Export ("insertNewObjectForEntityForName:inManagedObjectContext:")] NSObject InsertNewObjectForEntityForName (string entityName, NSManagedObjectContext context); [Export ("managedObjectModel")] NSManagedObjectModel ManagedObjectModel { get; } [Export ("managedObjectClassName")] string ManagedObjectClassName { get; set; } [Export ("name")] string Name { get; set; } [Export ("isAbstract")] bool Abstract { [Bind("isAbstract")] get; set; } [Export ("subentitiesByName")] NSDictionary SubentitiesByName { get; } [Export ("subentities")] NSEntityDescription[] Subentities { get; set; } [Export ("superentity")] NSEntityDescription Superentity { get; } [Export ("propertiesByName")] NSDictionary PropertiesByName { get; } [Export ("properties")] NSPropertyDescription[] Properties { get; set; } [Export ("userInfo")] NSDictionary UserInfo { get; set; } [Export ("attributesByName")] NSDictionary AttributesByName { get; } [Export ("relationshipsByName")] NSDictionary RelationshipsByName { get; } [Export ("relationshipsWithDestinationEntity:")] NSRelationshipDescription[] RelationshipsWithDestinationEntity (NSEntityDescription entity); [Export ("isKindOfEntity:")] bool IsKindOfEntity (NSEntityDescription entity); [Export ("versionHash")] NSData VersionHash { get; } [Export ("versionHashModifier")] string VersionHashModifier { get; set; } } [BaseType (typeof (NSObject))] public interface NSEntityMapping { [Export ("name")] string Name { get; set; } [Export ("mappingType")] NSEntityMappingType MappingType { get; set; } [Export ("sourceEntityName")] string SourceEntityName { get; set; } [Export ("sourceEntityVersionHash")] NSData SourceEntityVersionHash { get; set; } [Export ("destinationEntityName")] string DestinationEntityName { get; set; } [Export ("destinationEntityVersionHash")] NSData DestinationEntityVersionHash { get; set; } [Export ("attributeMappings")] NSPropertyMapping[] AttributeMappings { get; set; } [Export ("relationshipMappings")] NSPropertyMapping[] RelationshipMappings { get; set; } [Export ("sourceExpression")] NSExpression SourceExpression { get; set; } [Export ("userInfo")] NSDictionary UserInfo { get; set; } [Export ("entityMigrationPolicyClassName")] string EntityMigrationPolicyClassName { get; set; } } [BaseType (typeof (NSObject))] public interface NSEntityMigrationPolicy { [Export ("beginEntityMapping:manager:error:")] bool BeginEntityMapping (NSEntityMapping mapping, NSMigrationManager manager, out NSError error); [Export ("createDestinationInstancesForSourceInstance:entityMapping:manager:error:")] bool CreateDestinationInstancesForSourceInstance (NSManagedObject sInstance, NSEntityMapping mapping, NSMigrationManager manager, out NSError error); [Export ("endInstanceCreationForEntityMapping:manager:error:")] bool EndInstanceCreationForEntityMapping (NSEntityMapping mapping, NSMigrationManager manager, out NSError error); [Export ("createRelationshipsForDestinationInstance:entityMapping:manager:error:")] bool CreateRelationshipsForDestinationInstance (NSManagedObject dInstance, NSEntityMapping mapping, NSMigrationManager manager, out NSError error); [Export ("endRelationshipCreationForEntityMapping:manager:error:")] bool EndRelationshipCreationForEntityMapping (NSEntityMapping mapping, NSMigrationManager manager, out NSError error); [Export ("performCustomValidationForEntityMapping:manager:error:")] bool PerformCustomValidationForEntityMapping (NSEntityMapping mapping, NSMigrationManager manager, out NSError error); [Export ("endEntityMapping:manager:error:")] bool EndEntityMapping (NSEntityMapping mapping, NSMigrationManager manager, out NSError error); } [BaseType (typeof (NSPropertyDescription))] public interface NSFetchedPropertyDescription { [Export ("fetchRequest")] NSFetchRequest FetchRequest { get; set; } } [BaseType (typeof (NSObject))] public interface NSFetchRequest { [Export ("entity")] NSEntityDescription Entity { get; set; } [Export ("predicate")] NSPredicate Predicate { get; set; } [Export ("sortDescriptors")] NSSortDescriptor[] SortDescriptors { get; set; } [Export ("fetchLimit")] uint FetchLimit { get; set; } [Export ("affectedStores")] NSPersistentStore[] AffectedStores { get; set; } [Export ("resultType")] NSFetchRequestResultType ResultType { get; set; } [Export ("includesSubentities")] bool IncludesSubentities { get; set; } [Export ("includesPropertyValues")] bool IncludesPropertyValues { get; set; } [Export ("returnsObjectsAsFaults")] bool ReturnsObjectsAsFaults { get; set; } [Export ("relationshipKeyPathsForPrefetching")] string[] RelationshipKeyPathsForPrefetching { get; set; } } [BaseType (typeof (NSObject))] public interface NSManagedObject { [Export ("initWithEntity:insertIntoManagedObjectContext:")] IntPtr Constructor (NSEntityDescription entity, NSManagedObjectContext context); [Export ("managedObjectContext")] NSManagedObjectContext ManagedObjectContext { get; } [Export ("entity")] NSEntityDescription Entity { get; } [Export ("objectID")] NSManagedObjectID ObjectID { get; } [Export ("isInserted")] bool IsInserted { get; } [Export ("isUpdated")] bool IsUpdated { get; } [Export ("isDeleted")] bool IsDeleted { get; } [Export ("isFault")] bool IsFault { get; } [Export ("hasFaultForRelationshipNamed:")] bool HasFaultForRelationshipNamed (string key); [Export ("willAccessValueForKey:")] void WillAccessValueForKey (string key); [Export ("didAccessValueForKey:")] void DidAccessValueForKey (string key); [Export ("willChangeValueForKey:")] void WillChangeValueForKey (string key); [Export ("didChangeValueForKey:")] void DidChangeValueForKey (string key); [Export ("willChangeValueForKey:withSetMutation:usingObjects:")] void WillChangeValueForKey (string inKey, NSKeyValueSetMutationKind inMutationKind, NSSet inObjects); [Export ("didChangeValueForKey:withSetMutation:usingObjects:")] void DidChangeValueForKey (string inKey, NSKeyValueSetMutationKind inMutationKind, NSSet inObjects); [Export ("observationInfo")] IntPtr ObservationInfo { get; set; } [Export ("awakeFromFetch")] void AwakeFromFetch (); [Export ("awakeFromInsert")] void AwakeFromInsert (); [Export ("willSave")] void WillSave (); [Export ("didSave")] void DidSave (); [Export ("willTurnIntoFault")] void WillTurnIntoFault (); [Export ("didTurnIntoFault")] void DidTurnIntoFault (); [Export ("valueForKey:")] IntPtr ValueForKey (string key); [Export ("setValue:forKey:")] void SetValue (IntPtr value, string key); [Export ("primitiveValueForKey:")] IntPtr PrimitiveValueForKey (string key); [Export ("setPrimitiveValue:forKey:")] void SetPrimitiveValue (IntPtr value, string key); [Export ("committedValuesForKeys:")] NSDictionary CommittedValuesForKeys (string[] keys); [Export ("changedValues")] NSDictionary ChangedValues { get; } [Export ("validateValue:forKey:error:")] bool ValidateValue (NSObject value, string key, out NSError error); [Export ("validateForDelete:")] bool ValidateForDelete (out NSError error); [Export ("validateForInsert:")] bool ValidateForInsert (out NSError error); [Export ("validateForUpdate:")] bool ValidateForUpdate (out NSError error); } [BaseType (typeof (NSObject))] public interface NSManagedObjectContext { [Export ("persistentStoreCoordinator")] NSPersistentStoreCoordinator PersistentStoreCoordinator { get; set; } [Export ("undoManager")] NSUndoManager UndoManager { get; set; } [Export ("hasChanges")] bool HasChanges { get; } [Export ("objectRegisteredForID:")] NSManagedObject ObjectRegisteredForID (NSManagedObjectID objectID); [Export ("objectWithID:")] NSManagedObject ObjectWithID (NSManagedObjectID objectID); [Export ("executeFetchRequest:error:")] NSObject[] ExecuteFetchRequest (NSFetchRequest request, out NSError error); [Export ("countForFetchRequest:error:")] uint CountForFetchRequest (NSFetchRequest request, out NSError error); [Export ("insertObject:")] void InsertObject (NSManagedObject object1); [Export ("deleteObject:")] void DeleteObject (NSManagedObject object1); [Export ("refreshObject:mergeChanges:")] void RefreshObject (NSManagedObject object1, bool flag); [Export ("detectConflictsForObject:")] void DetectConflictsForObject (NSManagedObject object1); [Export ("observeValueForKeyPath:ofObject:change:context:")] void ObserveValueForKeyPath (string keyPath, IntPtr object1, NSDictionary change, IntPtr context); [Export ("processPendingChanges")] void ProcessPendingChanges (); [Export ("assignObject:toPersistentStore:")] void AssignObject (IntPtr object1, NSPersistentStore store); [Export ("insertedObjects")] NSSet InsertedObjects { get; } [Export ("updatedObjects")] NSSet UpdatedObjects { get; } [Export ("deletedObjects")] NSSet DeletedObjects { get; } [Export ("registeredObjects")] NSSet RegisteredObjects { get; } [Export ("undo")] void Undo (); [Export ("redo")] void Redo (); [Export ("reset")] void Reset (); [Export ("rollback")] void Rollback (); [Export ("save:")] bool Save (out NSError error); [Export ("lock")] void Lock (); [Export ("unlock")] void Unlock (); [Export ("tryLock")] bool TryLock { get; } [Export ("propagatesDeletesAtEndOfEvent")] bool PropagatesDeletesAtEndOfEvent { get; set; } [Export ("retainsRegisteredObjects")] bool RetainsRegisteredObjects { get; set; } [Export ("stalenessInterval")] double StalenessInterval { get; set; } [Export ("mergePolicy")] IntPtr MergePolicy { get; set; } [Export ("obtainPermanentIDsForObjects:error:")] bool ObtainPermanentIDsForObjects (NSManagedObject[] objects, out NSError error); [Export ("mergeChangesFromContextDidSaveNotification:")] void MergeChangesFromContextDidSaveNotification (NSNotification notification); } [BaseType (typeof (NSObject))] public interface NSManagedObjectID { [Export ("entity")] NSEntityDescription Entity { get; } [Export ("persistentStore")] NSPersistentStore PersistentStore { get; } [Export ("isTemporaryID")] bool IsTemporaryID { get; } [Export ("URIRepresentation")] NSUrl URIRepresentation { get; } } [BaseType (typeof (NSObject))] public interface NSManagedObjectModel { [Static, Export ("mergedModelFromBundles:")] NSManagedObjectModel MergedModelFromBundles (NSBundle[] bundles); [Static, Export ("modelByMergingModels:")] NSManagedObjectModel ModelByMergingModels (NSManagedObjectModel[] models); [Export ("init")] IntPtr Init { get; } [Export ("initWithContentsOfURL:")] IntPtr Constructor (NSUrl url); [Export ("entitiesByName")] NSDictionary EntitiesByName { get; } [Export ("entities")] NSEntityDescription[] Entities { get; set; } [Export ("configurations")] string[] Configurations { get; } [Export ("entitiesForConfiguration:")] string[] EntitiesForConfiguration (string configuration); [Export ("setEntities:forConfiguration:")] void SetEntities (NSEntityDescription[] entities, string configuration); [Export ("setFetchRequestTemplate:forName:")] void SetFetchRequestTemplate (NSFetchRequest fetchRequestTemplate, string name); [Export ("fetchRequestTemplateForName:")] NSFetchRequest FetchRequestTemplateForName (string name); [Export ("fetchRequestFromTemplateWithName:substitutionVariables:")] NSFetchRequest FetchRequestFromTemplateWithName (string name, NSDictionary variables); [Export ("localizationDictionary")] NSDictionary LocalizationDictionary { get; set; } [Static, Export ("mergedModelFromBundles:forStoreMetadata:")] NSManagedObjectModel MergedModelFromBundles (NSBundle[] bundles, NSDictionary metadata); [Static, Export ("modelByMergingModels:forStoreMetadata:")] NSManagedObjectModel ModelByMergingModels (NSManagedObjectModel[] models, NSDictionary metadata); [Export ("fetchRequestTemplatesByName")] NSDictionary FetchRequestTemplatesByName { get; } [Export ("versionIdentifiers")] NSSet VersionIdentifiers { get; set; } [Export ("isConfiguration:compatibleWithStoreMetadata:")] bool IsConfiguration (string configuration, NSDictionary metadata); [Export ("entityVersionHashesByName")] NSDictionary EntityVersionHashesByName { get; } } [BaseType (typeof (NSObject))] public interface NSMappingModel { [Static, Export ("mappingModelFromBundles:forSourceModel:destinationModel:")] NSMappingModel MappingModelFromBundles (NSBundle[] bundles, NSManagedObjectModel sourceModel, NSManagedObjectModel destinationModel); [Export ("initWithContentsOfURL:")] IntPtr Constructor (NSUrl url); [Export ("entityMappings")] NSEntityMapping[] EntityMappings { get; set; } [Export ("entityMappingsByName")] NSDictionary EntityMappingsByName { get; } } [BaseType (typeof (NSObject))] public interface NSMigrationManager { [Export ("initWithSourceModel:destinationModel:")] IntPtr Constructor (NSManagedObjectModel sourceModel, NSManagedObjectModel destinationModel); [Export ("migrateStoreFromURL:type:options:withMappingModel:toDestinationURL:destinationType:destinationOptions:error:")] bool MigrateStoreFromUrl (NSUrl sourceURL, string sStoreType, NSDictionary sOptions, NSMappingModel mappings, NSUrl dURL, string dStoreType, NSDictionary dOptions, out NSError error); [Export ("reset")] void Reset (); [Export ("mappingModel")] NSMappingModel MappingModel { get; } [Export ("sourceModel")] NSManagedObjectModel SourceModel { get; } [Export ("destinationModel")] NSManagedObjectModel DestinationModel { get; } [Export ("sourceContext")] NSManagedObjectContext SourceContext { get; } [Export ("destinationContext")] NSManagedObjectContext DestinationContext { get; } [Export ("sourceEntityForEntityMapping:")] NSEntityDescription SourceEntityForEntityMapping (NSEntityMapping mEntity); [Export ("destinationEntityForEntityMapping:")] NSEntityDescription DestinationEntityForEntityMapping (NSEntityMapping mEntity); [Export ("associateSourceInstance:withDestinationInstance:forEntityMapping:")] void AssociateSourceInstance (NSManagedObject sourceInstance, NSManagedObject destinationInstance, NSEntityMapping entityMapping); [Export ("destinationInstancesForEntityMappingNamed:sourceInstances:")] NSManagedObject[] DestinationInstancesForEntityMappingNamed (string mappingName, NSManagedObject[] sourceInstances); [Export ("sourceInstancesForEntityMappingNamed:destinationInstances:")] NSManagedObject[] SourceInstancesForEntityMappingNamed (string mappingName, NSManagedObject[] destinationInstances); [Export ("currentEntityMapping")] NSEntityMapping CurrentEntityMapping { get; } [Export ("migrationProgress")] float MigrationProgress { get; } [Export ("userInfo")] NSDictionary UserInfo { get; set; } [Export ("cancelMigrationWithError:")] void CancelMigrationWithError (NSError error); } [BaseType (typeof (NSObject))] public interface NSPersistentStore { [Static, Export ("metadataForPersistentStoreWithURL:error:")] NSDictionary MetadataForPersistentStoreWithUrl (NSUrl url, out NSError error); [Static, Export ("setMetadata:forPersistentStoreWithURL:error:")] bool SetMetadata (NSDictionary metadata, NSUrl url, out NSError error); [Export ("initWithPersistentStoreCoordinator:configurationName:URL:options:")] IntPtr Constructor (NSPersistentStoreCoordinator root, string name, NSUrl url, NSDictionary options); [Export ("persistentStoreCoordinator")] NSPersistentStoreCoordinator PersistentStoreCoordinator { get; } [Export ("configurationName")] string ConfigurationName { get; } [Export ("options")] NSDictionary Options { get; } [Export ("URL")] NSUrl Url { get; set; } [Export ("identifier")] string Identifier { get; set; } [Export ("type")] string Type { get; } [Export ("isReadOnly")] bool ReadOnly { get; [Bind("setReadOnly:")] set; } [Export ("metadata")] NSDictionary Metadata { get; set; } [Export ("didAddToPersistentStoreCoordinator:")] void DidAddToPersistentStoreCoordinator (NSPersistentStoreCoordinator coordinator); [Export ("willRemoveFromPersistentStoreCoordinator:")] void WillRemoveFromPersistentStoreCoordinator (NSPersistentStoreCoordinator coordinator); } [BaseType (typeof (NSObject))] public interface NSPersistentStoreCoordinator { [Static, Export ("registeredStoreTypes")] NSDictionary RegisteredStoreTypes { get; } [Static, Export ("registerStoreClass:forStoreType:")] void RegisterStoreClass (Class storeClass, string storeType); [Static, Export ("metadataForPersistentStoreOfType:URL:error:")] NSDictionary MetadataForPersistentStoreOfType (string storeType, NSUrl url, out NSError error); [Static, Export ("setMetadata:forPersistentStoreOfType:URL:error:")] bool SetMetadata (NSDictionary metadata, string storeType, NSUrl url, out NSError error); [Export ("setMetadata:forPersistentStore:")] void SetMetadata (NSDictionary metadata, NSPersistentStore store); [Export ("metadataForPersistentStore:")] NSDictionary MetadataForPersistentStore (NSPersistentStore store); [Export ("initWithManagedObjectModel:")] IntPtr Constructor (NSManagedObjectModel model); [Export ("managedObjectModel")] NSManagedObjectModel ManagedObjectModel { get; } [Export ("persistentStores")] NSPersistentStore[] PersistentStores { get; } [Export ("persistentStoreForURL:")] NSPersistentStore PersistentStoreForUrl (NSUrl URL); [Export ("URLForPersistentStore:")] NSUrl UrlForPersistentStore (NSPersistentStore store); [Export ("setURL:forPersistentStore:")] bool SetUrl (NSUrl url, NSPersistentStore store); [Export ("addPersistentStoreWithType:configuration:URL:options:error:")] NSPersistentStore AddPersistentStoreWithType (string storeType, string configuration, NSUrl storeURL, NSDictionary options, out NSError error); [Export ("removePersistentStore:error:")] bool RemovePersistentStore (NSPersistentStore store, out NSError error); [Export ("migratePersistentStore:toURL:options:withType:error:")] NSPersistentStore MigratePersistentStore (NSPersistentStore store, NSUrl URL, NSDictionary options, string storeType, out NSError error); [Export ("managedObjectIDForURIRepresentation:")] NSManagedObjectID ManagedObjectIDForURIRepresentation (NSUrl url); [Export ("lock")] void Lock (); [Export ("unlock")] void Unlock (); [Export ("tryLock")] bool TryLock { get; } [Obsolete("Deprecated in MAC OSX 10.5 and later")] [Static, Export ("metadataForPersistentStoreWithURL:error:")] NSDictionary MetadataForPersistentStoreWithUrl (NSUrl url, out NSError error); } [BaseType (typeof (NSObject))] public interface NSPropertyDescription { [Export ("entity")] NSEntityDescription Entity { get; } [Export ("name")] string Name { get; set; } [Export ("isOptional")] bool Optional { get; [Bind("setOptional:")] set; } [Export ("isTransient")] bool Transient { get; [Bind("setTransient:")] set; } [Export ("validationPredicates")] NSPredicate[] ValidationPredicates { get; } [Export ("validationWarnings")] string[] ValidationWarnings { get; } [Export ("setValidationPredicates:withValidationWarnings:")] void SetValidationPredicates (NSPredicate[] validationPredicates, string[] validationWarnings); [Export ("userInfo")] NSDictionary UserInfo { get; set; } [Export ("isIndexed")] bool Indexed { get; [Bind("setIndexed:")] set; } [Export ("versionHash")] NSData VersionHash { get; } [Export ("versionHashModifier")] string VersionHashModifier { get; set; } } [BaseType (typeof (NSObject))] public interface NSPropertyMapping { [Export ("name")] string Name { get; set; } [Export ("valueExpression")] NSExpression ValueExpression { get; set; } [Export ("userInfo")] NSDictionary UserInfo { get; set; } } [BaseType (typeof (NSPropertyDescription))] public interface NSRelationshipDescription { [Export ("destinationEntity")] NSEntityDescription DestinationEntity { get; set; } [Export ("inverseRelationship")] NSRelationshipDescription InverseRelationship { get; set; } [Export ("maxCount")] uint MaxCount { get; set; } [Export ("minCount")] uint MinCount { get; set; } [Export ("deleteRule")] NSDeleteRule DeleteRule { get; set; } [Export ("isToMany")] bool IsToMany { get; } [Export ("versionHash")] NSData VersionHash { get; } } }
/* * 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 LSLInteger = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase { public partial class ScriptBaseClass { public const int ACTIVE = 2; public const int AGENT = 1; public const int AGENT_ALWAYS_RUN = 4096; public const int AGENT_ATTACHMENTS = 2; public const int AGENT_AWAY = 64; public const int AGENT_BUSY = 2048; public const int AGENT_BY_LEGACY_NAME = 1; public const int AGENT_BY_USERNAME = 0x10; public const int AGENT_CROUCHING = 1024; public const int AGENT_FLYING = 1; public const int AGENT_IN_AIR = 256; // for llGetAgentList public const int AGENT_LIST_PARCEL = 1; public const int AGENT_LIST_PARCEL_OWNER = 2; public const int AGENT_LIST_REGION = 4; public const int AGENT_MOUSELOOK = 8; public const int AGENT_ON_OBJECT = 32; public const int AGENT_SCRIPTED = 4; public const int AGENT_SITTING = 16; public const int AGENT_TYPING = 512; public const int AGENT_WALKING = 128; public const int ALL_SIDES = -1; public const int ANIM_ON = 1; public const int ATTACH_AVATAR_CENTER = 40; public const int ATTACH_BACK = 9; public const int ATTACH_BELLY = 28; public const int ATTACH_CHEST = 1; public const int ATTACH_CHIN = 12; public const int ATTACH_HEAD = 2; public const int ATTACH_HUD_BOTTOM = 37; public const int ATTACH_HUD_BOTTOM_LEFT = 36; public const int ATTACH_HUD_BOTTOM_RIGHT = 38; public const int ATTACH_HUD_CENTER_1 = 35; public const int ATTACH_HUD_CENTER_2 = 31; public const int ATTACH_HUD_TOP_CENTER = 33; public const int ATTACH_HUD_TOP_LEFT = 34; public const int ATTACH_HUD_TOP_RIGHT = 32; public const int ATTACH_LEAR = 13; public const int ATTACH_LEFT_PEC = 29; public const int ATTACH_LEYE = 15; public const int ATTACH_LFOOT = 7; public const int ATTACH_LHAND = 5; public const int ATTACH_LHIP = 25; public const int ATTACH_LLARM = 21; public const int ATTACH_LLLEG = 27; public const int ATTACH_LPEC = 30; public const int ATTACH_LSHOULDER = 3; public const int ATTACH_LUARM = 20; public const int ATTACH_LULEG = 26; public const int ATTACH_MOUTH = 11; public const int ATTACH_NECK = 39; public const int ATTACH_NOSE = 17; public const int ATTACH_PELVIS = 10; public const int ATTACH_REAR = 14; public const int ATTACH_REYE = 16; public const int ATTACH_RFOOT = 8; public const int ATTACH_RHAND = 6; public const int ATTACH_RHIP = 22; // Same value as ATTACH_RPEC, see https://jira.secondlife.com/browse/SVC-580 public const int ATTACH_RIGHT_PEC = 30; public const int ATTACH_RLARM = 19; public const int ATTACH_RLLEG = 24; public const int ATTACH_RPEC = 29; public const int ATTACH_RSHOULDER = 4; public const int ATTACH_RUARM = 18; public const int ATTACH_RULEG = 23; public const int CAMERA_ACTIVE = 12; public const int CAMERA_BEHINDNESS_ANGLE = 8; public const int CAMERA_BEHINDNESS_LAG = 9; public const int CAMERA_DISTANCE = 7; public const int CAMERA_FOCUS = 17; public const int CAMERA_FOCUS_LAG = 6; public const int CAMERA_FOCUS_LOCKED = 22; public const int CAMERA_FOCUS_OFFSET = 1; public const int CAMERA_FOCUS_OFFSET_X = 2; public const int CAMERA_FOCUS_OFFSET_Y = 3; public const int CAMERA_FOCUS_OFFSET_Z = 4; public const int CAMERA_FOCUS_THRESHOLD = 11; public const int CAMERA_FOCUS_X = 18; public const int CAMERA_FOCUS_Y = 19; public const int CAMERA_FOCUS_Z = 20; // constants for llSetCameraParams public const int CAMERA_PITCH = 0; public const int CAMERA_POSITION = 13; public const int CAMERA_POSITION_LAG = 5; public const int CAMERA_POSITION_LOCKED = 21; public const int CAMERA_POSITION_THRESHOLD = 10; public const int CAMERA_POSITION_X = 14; public const int CAMERA_POSITION_Y = 15; public const int CAMERA_POSITION_Z = 16; public const int CHANGED_ALLOWED_DROP = 64; public const int CHANGED_ANIMATION = 16384; public const int CHANGED_COLOR = 2; public const int CHANGED_INVENTORY = 1; public const int CHANGED_LINK = 32; public const int CHANGED_MEDIA = 2048; public const int CHANGED_OWNER = 128; public const int CHANGED_REGION = 256; public const int CHANGED_REGION_RESTART = 1024; public const int CHANGED_REGION_START = 1024; public const int CHANGED_SCALE = 8; public const int CHANGED_SHAPE = 4; public const int CHANGED_TELEPORT = 512; public const int CHANGED_TEXTURE = 16; public const int CLICK_ACTION_BUY = 2; // constants for llSetClickAction public const int CLICK_ACTION_NONE = 0; public const int CLICK_ACTION_OPEN = 4; public const int CLICK_ACTION_OPEN_MEDIA = 6; public const int CLICK_ACTION_PAY = 3; public const int CLICK_ACTION_PLAY = 5; public const int CLICK_ACTION_SIT = 1; public const int CLICK_ACTION_TOUCH = 0; public const int CLICK_ACTION_ZOOM = 7; public const int CONTENT_TYPE_ATOM = 4; public const int CONTENT_TYPE_FORM = 7; public const int CONTENT_TYPE_HTML = 1; //application/atom+xml public const int CONTENT_TYPE_JSON = 5; //application/json public const int CONTENT_TYPE_LLSD = 6; //application/llsd+xml //application/x-www-form-urlencoded public const int CONTENT_TYPE_RSS = 8; // llSetContentType public const int CONTENT_TYPE_TEXT = 0; public const int CONTENT_TYPE_XHTML = 3; //text/html public const int CONTENT_TYPE_XML = 2; public const int CONTROL_BACK = 2; public const int CONTROL_DOWN = 32; public const int CONTROL_FWD = 1; public const int CONTROL_LBUTTON = 268435456; public const int CONTROL_LEFT = 4; public const int CONTROL_ML_LBUTTON = 1073741824; public const int CONTROL_RIGHT = 8; public const int CONTROL_ROT_LEFT = 256; public const int CONTROL_ROT_RIGHT = 512; public const int CONTROL_UP = 16; public const int DATA_BORN = 3; public const int DATA_NAME = 2; //Agent Dataserver public const int DATA_ONLINE = 1; public const int DATA_PAYINFO = 8; public const int DATA_RATING = 4; public const int DATA_SIM_POS = 5; public const int DATA_SIM_RATING = 7; public const int DATA_SIM_RELEASE = 128; public const int DATA_SIM_STATUS = 6; public const int DEBUG_CHANNEL = 0x7FFFFFFF; public const double DEG_TO_RAD = 0.01745329238f; public const int DENSITY = 1; public const string EOF = "\n\n\n"; //llManageEstateAccess public const int ESTATE_ACCESS_ALLOWED_AGENT_ADD = 0; public const int ESTATE_ACCESS_ALLOWED_AGENT_REMOVE = 1; public const int ESTATE_ACCESS_ALLOWED_GROUP_ADD = 2; public const int ESTATE_ACCESS_ALLOWED_GROUP_REMOVE = 3; public const int ESTATE_ACCESS_BANNED_AGENT_ADD = 4; public const int ESTATE_ACCESS_BANNED_AGENT_REMOVE = 5; public const int FRICTION = 2; public const int GRAVITY_MULTIPLIER = 8; public const int HTTP_BODY_MAXLENGTH = 2; public const int HTTP_CUSTOM_HEADER = 5; //llHTTPRequest public const int HTTP_METHOD = 0; public const int HTTP_MIMETYPE = 1; public const int HTTP_PRAGMA_NO_CACHE = 6; public const int HTTP_VERBOSE_THROTTLE = 4; public const int HTTP_VERIFY_CERT = 3; public const int INVENTORY_ALL = -1; public const int INVENTORY_ANIMATION = 20; public const int INVENTORY_BODYPART = 13; public const int INVENTORY_CLOTHING = 5; public const int INVENTORY_GESTURE = 21; public const int INVENTORY_LANDMARK = 3; public const int INVENTORY_NONE = -1; public const int INVENTORY_NOTECARD = 7; public const int INVENTORY_OBJECT = 6; public const int INVENTORY_SCRIPT = 10; public const int INVENTORY_SOUND = 1; public const int INVENTORY_TEXTURE = 0; public const int KFM_CMD_PAUSE = 2; public const int KFM_CMD_PLAY = 0; public const int KFM_CMD_STOP = 1; public const int KFM_COMMAND = 0; public const int KFM_DATA = 2; public const int KFM_FORWARD = 0; public const int KFM_LOOP = 1; public const int KFM_MODE = 1; public const int KFM_PING_PONG = 2; public const int KFM_REVERSE = 3; public const int KFM_ROTATION = 1; public const int KFM_TRANSLATION = 2; public const int LAND_LARGE_BRUSH = 3; public const int LAND_LEVEL = 0; public const int LAND_LOWER = 2; public const int LAND_MEDIUM_BRUSH = 2; public const int LAND_NOISE = 4; public const int LAND_RAISE = 1; public const int LAND_REVERT = 5; public const int LAND_SMALL_BRUSH = 1; public const int LAND_SMOOTH = 3; public const int LINK_ALL_CHILDREN = -3; public const int LINK_ALL_OTHERS = -2; public const int LINK_ROOT = 1; public const int LINK_SET = -1; public const int LINK_THIS = -4; public const int LIST_STAT_GEOMETRIC_MEAN = 9; public const int LIST_STAT_HARMONIC_MEAN = 100; public const int LIST_STAT_MAX = 2; public const int LIST_STAT_MEAN = 3; public const int LIST_STAT_MEDIAN = 4; public const int LIST_STAT_MIN = 1; public const int LIST_STAT_NUM_COUNT = 8; public const int LIST_STAT_RANGE = 0; public const int LIST_STAT_STD_DEV = 5; public const int LIST_STAT_SUM = 6; public const int LIST_STAT_SUM_SQUARES = 7; public const int LOOP = 2; public const int MASK_BASE = 0; public const int MASK_EVERYONE = 3; public const int MASK_GROUP = 2; public const int MASK_NEXT = 4; public const int MASK_OWNER = 1; public const int NPC = 0x20; public const string NULL_KEY = "00000000-0000-0000-0000-000000000000"; public const int OBJECT_ATTACHED_POINT = 19; public const int OBJECT_CHARACTER_TIME = 17; public const int OBJECT_CREATOR = 8; public const int OBJECT_DESC = 2; public const int OBJECT_GROUP = 7; public const int OBJECT_NAME = 1; public const int OBJECT_OWNER = 6; public const int OBJECT_PATHFINDING_TYPE = 20; public const int OBJECT_PHANTOM = 22; public const int OBJECT_PHYSICS = 21; public const int OBJECT_PHYSICS_COST = 16; public const int OBJECT_POS = 3; public const int OBJECT_PRIM_EQUIVALENCE = 13; public const int OBJECT_ROOT = 18; public const int OBJECT_ROT = 4; public const int OBJECT_RUNNING_SCRIPT_COUNT = 9; public const int OBJECT_SCRIPT_MEMORY = 11; public const int OBJECT_SCRIPT_TIME = 12; public const int OBJECT_SERVER_COST = 14; public const int OBJECT_STREAMING_COST = 15; public const int OBJECT_TEMP_ON_REZ = 23; public const int OBJECT_TOTAL_SCRIPT_COUNT = 10; // Constants for llGetObjectDetails public const int OBJECT_UNKNOWN_DETAIL = -1; public const int OBJECT_VELOCITY = 5; public const int OPT_AVATAR = 1; public const int OPT_CHARACTER = 2; public const int OPT_EXCLUSION_VOLUME = 6; public const int OPT_LEGACY_LINKSET = 0; public const int OPT_MATERIAL_VOLUME = 5; // Pathfinding types public const int OPT_OTHER = -1; public const int OPT_STATIC_OBSTACLE = 4; public const int OPT_WALKABLE = 3; /// <summary> /// process message parameter as regex /// </summary> public const int OS_LISTEN_REGEX_MESSAGE = 0x2; /// <summary> /// process name parameter as regex /// </summary> public const int OS_LISTEN_REGEX_NAME = 0x1; public const int OS_NPC = 0x01000000; public const int OS_NPC_CREATOR_OWNED = 0x1; // Constants for osNpc* functions public const int OS_NPC_FLY = 0; public const int OS_NPC_LAND_AT_TARGET = 2; public const int OS_NPC_NO_FLY = 1; public const int OS_NPC_NOT_OWNED = 0x2; public const int OS_NPC_RUNNING = 4; public const int OS_NPC_SENSE_AS_AGENT = 0x4; public const int OS_NPC_SIT_NOW = 0; public const int PARCEL_COUNT_GROUP = 2; public const int PARCEL_COUNT_OTHER = 3; public const int PARCEL_COUNT_OWNER = 1; public const int PARCEL_COUNT_SELECTED = 4; public const int PARCEL_COUNT_TEMP = 5; //ParcelPrim Categories public const int PARCEL_COUNT_TOTAL = 0; public const int PARCEL_DETAILS_AREA = 4; //osSetParcelDetails public const int PARCEL_DETAILS_CLAIMDATE = 10; public const int PARCEL_DETAILS_DESC = 1; public const int PARCEL_DETAILS_GROUP = 3; public const int PARCEL_DETAILS_ID = 5; // constants for llGetParcelDetails public const int PARCEL_DETAILS_NAME = 0; public const int PARCEL_DETAILS_OWNER = 2; public const int PARCEL_DETAILS_SEE_AVATARS = 6; public const int PARCEL_FLAG_ALLOW_ALL_OBJECT_ENTRY = 0x8000000; public const int PARCEL_FLAG_ALLOW_CREATE_GROUP_OBJECTS = 0x4000000; public const int PARCEL_FLAG_ALLOW_CREATE_OBJECTS = 0x40; public const int PARCEL_FLAG_ALLOW_DAMAGE = 0x20; public const int PARCEL_FLAG_ALLOW_FLY = 0x1; // parcel allows group object creation // parcel allows objects owned by any user to enter public const int PARCEL_FLAG_ALLOW_GROUP_OBJECT_ENTRY = 0x10000000; public const int PARCEL_FLAG_ALLOW_GROUP_SCRIPTS = 0x2000000; public const int PARCEL_FLAG_ALLOW_LANDMARK = 0x8; // parcel allows flying public const int PARCEL_FLAG_ALLOW_SCRIPTS = 0x2; // parcel allows outside scripts // parcel allows landmarks to be created public const int PARCEL_FLAG_ALLOW_TERRAFORM = 0x10; public const int PARCEL_FLAG_LOCAL_SOUND_ONLY = 0x8000; // parcel restricts spatialized sound to the parcel public const int PARCEL_FLAG_RESTRICT_PUSHOBJECT = 0x200000; // parcel allows anyone to terraform the land // parcel allows damage // parcel allows anyone to create objects public const int PARCEL_FLAG_USE_ACCESS_GROUP = 0x100; // parcel limits access to a group public const int PARCEL_FLAG_USE_ACCESS_LIST = 0x200; // parcel limits access to a list of residents public const int PARCEL_FLAG_USE_BAN_LIST = 0x400; // parcel uses a ban list, including restricting access based on payment info public const int PARCEL_FLAG_USE_LAND_PASS_LIST = 0x800; public const int PARCEL_MEDIA_COMMAND_AGENT = 7; public const int PARCEL_MEDIA_COMMAND_AUTO_ALIGN = 9; public const int PARCEL_MEDIA_COMMAND_DESC = 12; public const int PARCEL_MEDIA_COMMAND_LOOP = 3; public const int PARCEL_MEDIA_COMMAND_PAUSE = 1; public const int PARCEL_MEDIA_COMMAND_PLAY = 2; public const int PARCEL_MEDIA_COMMAND_SIZE = 11; public const int PARCEL_MEDIA_COMMAND_STOP = 0; public const int PARCEL_MEDIA_COMMAND_TEXTURE = 4; public const int PARCEL_MEDIA_COMMAND_TIME = 6; public const int PARCEL_MEDIA_COMMAND_TYPE = 10; public const int PARCEL_MEDIA_COMMAND_UNLOAD = 8; public const int PARCEL_MEDIA_COMMAND_URL = 5; public const int PASSIVE = 4; public const int PERM_ALL = 2147483647; public const int PERM_COPY = 32768; public const int PERM_MODIFY = 16384; public const int PERM_MOVE = 524288; public const int PERM_TRANSFER = 8192; public const int PERMISSION_ATTACH = 32; public const int PERMISSION_CHANGE_JOINTS = 256; public const int PERMISSION_CHANGE_LINKS = 128; public const int PERMISSION_CHANGE_PERMISSIONS = 512; public const int PERMISSION_CONTROL_CAMERA = 2048; //Permissions public const int PERMISSION_DEBIT = 2; public const int PERMISSION_RELEASE_OWNERSHIP = 64; public const int PERMISSION_REMAP_CONTROLS = 8; public const int PERMISSION_TAKE_CONTROLS = 4; public const int PERMISSION_TRACK_CAMERA = 1024; public const int PERMISSION_TRIGGER_ANIMATION = 16; public const double PI = 3.14159274f; public const double PI_BY_TWO = 1.57079637f; public const int PING_PONG = 8; public const int PRIM_BUMP_BARK = 4; public const int PRIM_BUMP_BLOBS = 12; public const int PRIM_BUMP_BRICKS = 5; public const int PRIM_BUMP_BRIGHT = 1; public const int PRIM_BUMP_CHECKER = 6; public const int PRIM_BUMP_CONCRETE = 7; public const int PRIM_BUMP_DARK = 2; public const int PRIM_BUMP_DISKS = 10; public const int PRIM_BUMP_GRAVEL = 11; public const int PRIM_BUMP_LARGETILE = 14; public const int PRIM_BUMP_NONE = 0; public const int PRIM_BUMP_SHINY = 19; public const int PRIM_BUMP_SIDING = 13; public const int PRIM_BUMP_STONE = 9; public const int PRIM_BUMP_STUCCO = 15; public const int PRIM_BUMP_SUCTION = 16; public const int PRIM_BUMP_TILE = 8; public const int PRIM_BUMP_WEAVE = 17; public const int PRIM_BUMP_WOOD = 3; public const int PRIM_CAST_SHADOWS = 24; public const int PRIM_COLOR = 18; public const int PRIM_DESC = 28; public const int PRIM_FLEXIBLE = 21; public const int PRIM_FULLBRIGHT = 20; public const int PRIM_GLOW = 25; public const int PRIM_HOLE_CIRCLE = 16; public const int PRIM_HOLE_DEFAULT = 0; public const int PRIM_HOLE_SQUARE = 32; public const int PRIM_HOLE_TRIANGLE = 48; public const int PRIM_LINK_TARGET = 34; public const int PRIM_MATERIAL = 2; public const int PRIM_MATERIAL_FLESH = 4; public const int PRIM_MATERIAL_GLASS = 2; public const int PRIM_MATERIAL_LIGHT = 7; public const int PRIM_MATERIAL_METAL = 1; public const int PRIM_MATERIAL_PLASTIC = 5; public const int PRIM_MATERIAL_RUBBER = 6; public const int PRIM_MATERIAL_STONE = 0; public const int PRIM_MATERIAL_WOOD = 3; // constants for llGetPrimMediaParams/llSetPrimMediaParams public const int PRIM_MEDIA_ALT_IMAGE_ENABLE = 0; public const int PRIM_MEDIA_AUTO_LOOP = 4; public const int PRIM_MEDIA_AUTO_PLAY = 5; public const int PRIM_MEDIA_AUTO_SCALE = 6; public const int PRIM_MEDIA_AUTO_ZOOM = 7; public const int PRIM_MEDIA_CONTROLS = 1; public const int PRIM_MEDIA_CONTROLS_MINI = 1; public const int PRIM_MEDIA_CONTROLS_STANDARD = 0; public const int PRIM_MEDIA_CURRENT_URL = 2; public const int PRIM_MEDIA_FIRST_CLICK_INTERACT = 8; public const int PRIM_MEDIA_HEIGHT_PIXELS = 10; public const int PRIM_MEDIA_HOME_URL = 3; public const int PRIM_MEDIA_PERM_ANYONE = 4; public const int PRIM_MEDIA_PERM_GROUP = 2; public const int PRIM_MEDIA_PERM_NONE = 0; public const int PRIM_MEDIA_PERM_OWNER = 1; public const int PRIM_MEDIA_PERMS_CONTROL = 14; public const int PRIM_MEDIA_PERMS_INTERACT = 13; public const int PRIM_MEDIA_WHITELIST = 12; public const int PRIM_MEDIA_WHITELIST_ENABLE = 11; public const int PRIM_MEDIA_WIDTH_PIXELS = 9; public const int PRIM_NAME = 27; public const int PRIM_OMEGA = 32; public const int PRIM_PHANTOM = 5; //application/xml //application/xhtml+xml //application/rss+xml public const int PRIM_PHYSICS = 3; public const int PRIM_PHYSICS_MATERIAL = 31; public const int PRIM_PHYSICS_SHAPE_CONVEX = 2; public const int PRIM_PHYSICS_SHAPE_NONE = 1; public const int PRIM_PHYSICS_SHAPE_PRIM = 0; public const int PRIM_PHYSICS_SHAPE_TYPE = 30; // Not implemented, here for completeness sake public const int PRIM_POINT_LIGHT = 23; public const int PRIM_POS_LOCAL = 33; public const int PRIM_POSITION = 6; public const int PRIM_ROT_LOCAL = 29; public const int PRIM_ROTATION = 8; public const int PRIM_SCULPT_FLAG_INVERT = 64; public const int PRIM_SCULPT_FLAG_MIRROR = 128; public const int PRIM_SCULPT_TYPE_CYLINDER = 4; public const int PRIM_SCULPT_TYPE_PLANE = 3; public const int PRIM_SCULPT_TYPE_SPHERE = 1; public const int PRIM_SCULPT_TYPE_TORUS = 2; public const int PRIM_SHINY_HIGH = 3; public const int PRIM_SHINY_LOW = 1; public const int PRIM_SHINY_MEDIUM = 2; public const int PRIM_SHINY_NONE = 0; public const int PRIM_SIZE = 7; public const int PRIM_SLICE = 35; //text/plain public const int PRIM_TEMP_ON_REZ = 4; public const int PRIM_TEXGEN = 22; public const int PRIM_TEXGEN_DEFAULT = 0; public const int PRIM_TEXGEN_PLANAR = 1; // Huh? public const int PRIM_TEXT = 26; public const int PRIM_TEXTURE = 17; public const int PRIM_TYPE = 9; public const int PRIM_TYPE_BOX = 0; public const int PRIM_TYPE_CYLINDER = 1; public const int PRIM_TYPE_PRISM = 2; public const int PRIM_TYPE_RING = 6; public const int PRIM_TYPE_SCULPT = 7; public const int PRIM_TYPE_SPHERE = 3; public const int PRIM_TYPE_TORUS = 4; public const int PRIM_TYPE_TUBE = 5; public const int PROFILE_NONE = 0; public const int PROFILE_SCRIPT_MEMORY = 1; public const int PSYS_PART_BF_DEST_COLOR = 2; public const int PSYS_PART_BF_ONE = 0; public const int PSYS_PART_BF_ONE_MINUS_DEST_COLOR = 4; public const int PSYS_PART_BF_ONE_MINUS_SOURCE_ALPHA = 9; public const int PSYS_PART_BF_ONE_MINUS_SOURCE_COLOR = 5; public const int PSYS_PART_BF_SOURCE_ALPHA = 7; public const int PSYS_PART_BF_SOURCE_COLOR = 3; public const int PSYS_PART_BF_ZERO = 1; public const int PSYS_PART_BLEND_FUNC_DEST = 25; public const int PSYS_PART_BLEND_FUNC_SOURCE = 24; public const int PSYS_PART_BOUNCE_MASK = 4; public const int PSYS_PART_EMISSIVE_MASK = 256; public const int PSYS_PART_END_ALPHA = 4; public const int PSYS_PART_END_COLOR = 3; public const int PSYS_PART_END_GLOW = 27; public const int PSYS_PART_END_SCALE = 6; public const int PSYS_PART_FLAGS = 0; public const int PSYS_PART_FOLLOW_SRC_MASK = 16; public const int PSYS_PART_FOLLOW_VELOCITY_MASK = 32; //Particle Systems public const int PSYS_PART_INTERP_COLOR_MASK = 1; public const int PSYS_PART_INTERP_SCALE_MASK = 2; public const int PSYS_PART_MAX_AGE = 7; public const int PSYS_PART_RIBBON_MASK = 1024; public const int PSYS_PART_START_ALPHA = 2; public const int PSYS_PART_START_COLOR = 1; public const int PSYS_PART_START_GLOW = 26; public const int PSYS_PART_START_SCALE = 5; public const int PSYS_PART_TARGET_LINEAR_MASK = 128; public const int PSYS_PART_TARGET_POS_MASK = 64; public const int PSYS_PART_WIND_MASK = 8; public const int PSYS_SRC_ACCEL = 8; public const int PSYS_SRC_ANGLE_BEGIN = 22; public const int PSYS_SRC_ANGLE_END = 23; public const int PSYS_SRC_BURST_PART_COUNT = 15; public const int PSYS_SRC_BURST_RADIUS = 16; public const int PSYS_SRC_BURST_RATE = 13; public const int PSYS_SRC_BURST_SPEED_MAX = 18; public const int PSYS_SRC_BURST_SPEED_MIN = 17; public const int PSYS_SRC_INNERANGLE = 10; public const int PSYS_SRC_MAX_AGE = 19; public const int PSYS_SRC_OMEGA = 21; public const int PSYS_SRC_OUTERANGLE = 11; public const int PSYS_SRC_PATTERN = 9; public const int PSYS_SRC_PATTERN_ANGLE = 4; public const int PSYS_SRC_PATTERN_ANGLE_CONE = 8; public const int PSYS_SRC_PATTERN_ANGLE_CONE_EMPTY = 16; public const int PSYS_SRC_PATTERN_DROP = 1; public const int PSYS_SRC_PATTERN_EXPLODE = 2; public const int PSYS_SRC_TARGET_KEY = 20; public const int PSYS_SRC_TEXTURE = 12; public const int PUBLIC_CHANNEL = 0x00000000; public const double RAD_TO_DEG = 57.29578f; public const int REGION_FLAG_ALLOW_DAMAGE = 0x1; public const int REGION_FLAG_ALLOW_DIRECT_TELEPORT = 0x100000; public const int REGION_FLAG_BLOCK_FLY = 0x80000; public const int REGION_FLAG_BLOCK_TERRAFORM = 0x40; public const int REGION_FLAG_DISABLE_COLLISIONS = 0x1000; // region has disabled collisions public const int REGION_FLAG_DISABLE_PHYSICS = 0x4000; // region is entirely damage enabled public const int REGION_FLAG_FIXED_SUN = 0x10; // region has disabled physics // region blocks flying // region allows direct teleports public const int REGION_FLAG_RESTRICT_PUSHOBJECT = 0x400000; // region has a fixed sun position // region terraforming disabled public const int REGION_FLAG_SANDBOX = 0x100; //XML RPC Remote Data Channel public const int REMOTE_DATA_CHANNEL = 1; public const int REMOTE_DATA_REPLY = 3; public const int REMOTE_DATA_REQUEST = 2; public const int RESTITUTION = 4; public const int REVERSE = 4; public const int ROTATE = 32; public const int SCALE = 64; public const int SCRIPTED = 8; public const int SMOOTH = 16; public const double SQRT2 = 1.414213538f; public const int STATS_ACTIVE_PRIMS = 7; public const int STATS_ACTIVE_SCRIPTS = 19; public const int STATS_AGENT_MS = 16; public const int STATS_AGENT_UPDATES = 3; public const int STATS_CHILD_AGENTS = 5; public const int STATS_FRAME_MS = 8; public const int STATS_IMAGE_MS = 11; public const int STATS_IN_PACKETS_PER_SECOND = 13; public const int STATS_NET_MS = 9; public const int STATS_OTHER_MS = 12; public const int STATS_OUT_PACKETS_PER_SECOND = 14; public const int STATS_PENDING_DOWNLOADS = 17; public const int STATS_PENDING_UPLOADS = 18; public const int STATS_PHYSICS_FPS = 2; public const int STATS_PHYSICS_MS = 10; public const int STATS_ROOT_AGENTS = 4; public const int STATS_SCRIPT_LPS = 20; public const int STATS_SIM_FPS = 1; // Constants for osGetRegionStats public const int STATS_TIME_DILATION = 0; public const int STATS_TOTAL_PRIMS = 6; public const int STATS_UNACKED_BYTES = 15; public const int STATUS_BLOCK_GRAB = 64; public const int STATUS_CAST_SHADOWS = 512; public const int STATUS_DIE_AT_EDGE = 128; public const int STATUS_PHANTOM = 16; public const int STATUS_PHYSICS = 1; public const int STATUS_RETURN_AT_EDGE = 256; public const int STATUS_ROTATE_X = 2; public const int STATUS_ROTATE_Y = 4; public const int STATUS_ROTATE_Z = 8; public const int STATUS_SANDBOX = 32; public const int STRING_TRIM = 3; public const int STRING_TRIM_HEAD = 1; public const int STRING_TRIM_TAIL = 2; // Constants for default textures public const string TEXTURE_BLANK = "5748decc-f629-461c-9a36-a35a221fe21f"; public const string TEXTURE_DEFAULT = "89556747-24cb-43ed-920b-47caed15465f"; public const string TEXTURE_MEDIA = "8b5fec65-8d8d-9dc5-cda8-8fdf2716e361"; public const string TEXTURE_PLYWOOD = "89556747-24cb-43ed-920b-47caed15465f"; public const string TEXTURE_TRANSPARENT = "8dcd4a48-2d37-4909-9f78-f7a9eb4ef903"; // not implemented // constants for the llDetectedTouch* functions public const int TOUCH_INVALID_FACE = -1; public const double TWO_PI = 6.28318548f; public const int TYPE_FLOAT = 2; public const int TYPE_INTEGER = 1; //LL Changed the constant from CHANGED_REGION_RESTART public const int TYPE_INVALID = 0; public const int TYPE_KEY = 4; public const int TYPE_ROTATION = 6; public const int TYPE_STRING = 3; public const int TYPE_VECTOR = 5; public const string URL_REQUEST_DENIED = "URL_REQUEST_DENIED"; public const string URL_REQUEST_GRANTED = "URL_REQUEST_GRANTED"; public const int VEHICLE_ANGULAR_DEFLECTION_EFFICIENCY = 32; public const int VEHICLE_ANGULAR_DEFLECTION_TIMESCALE = 33; public const int VEHICLE_ANGULAR_FRICTION_TIMESCALE = 17; public const int VEHICLE_ANGULAR_MOTOR_DECAY_TIMESCALE = 35; public const int VEHICLE_ANGULAR_MOTOR_DIRECTION = 19; public const int VEHICLE_ANGULAR_MOTOR_TIMESCALE = 34; public const int VEHICLE_BANKING_EFFICIENCY = 38; public const int VEHICLE_BANKING_MIX = 39; public const int VEHICLE_BANKING_TIMESCALE = 40; public const int VEHICLE_BUOYANCY = 27; public const int VEHICLE_FLAG_CAMERA_DECOUPLED = 512; public const int VEHICLE_FLAG_HOVER_GLOBAL_HEIGHT = 16; public const int VEHICLE_FLAG_HOVER_TERRAIN_ONLY = 8; public const int VEHICLE_FLAG_HOVER_UP_ONLY = 32; public const int VEHICLE_FLAG_HOVER_WATER_ONLY = 4; public const int VEHICLE_FLAG_LIMIT_MOTOR_UP = 64; public const int VEHICLE_FLAG_LIMIT_ROLL_ONLY = 2; public const int VEHICLE_FLAG_LOCK_HOVER_HEIGHT = 8192; public const int VEHICLE_FLAG_LOCK_ROTATION = 32784; public const int VEHICLE_FLAG_MOUSELOOK_BANK = 256; public const int VEHICLE_FLAG_MOUSELOOK_STEER = 128; public const int VEHICLE_FLAG_NO_DEFLECTION = 16392; public const int VEHICLE_FLAG_NO_DEFLECTION_UP = 1; public const int VEHICLE_FLAG_NO_X = 1024; public const int VEHICLE_FLAG_NO_Y = 2048; public const int VEHICLE_FLAG_NO_Z = 4096; public const int VEHICLE_HOVER_EFFICIENCY = 25; public const int VEHICLE_HOVER_HEIGHT = 24; public const int VEHICLE_HOVER_TIMESCALE = 26; public const int VEHICLE_LINEAR_DEFLECTION_EFFICIENCY = 28; public const int VEHICLE_LINEAR_DEFLECTION_TIMESCALE = 29; public const int VEHICLE_LINEAR_FRICTION_TIMESCALE = 16; public const int VEHICLE_LINEAR_MOTOR_DECAY_TIMESCALE = 31; public const int VEHICLE_LINEAR_MOTOR_DIRECTION = 18; public const int VEHICLE_LINEAR_MOTOR_OFFSET = 20; public const int VEHICLE_LINEAR_MOTOR_TIMESCALE = 30; public const int VEHICLE_RANGE_BLOCK = 45; public const int VEHICLE_REFERENCE_FRAME = 44; public const int VEHICLE_ROLL_FRAME = 46; public const int VEHICLE_TYPE_AIRPLANE = 4; public const int VEHICLE_TYPE_BALLOON = 5; public const int VEHICLE_TYPE_BOAT = 3; public const int VEHICLE_TYPE_CAR = 2; public const int VEHICLE_TYPE_NONE = 0; public const int VEHICLE_TYPE_SLED = 1; public const int VEHICLE_VERTICAL_ATTRACTION_EFFICIENCY = 36; public const int VEHICLE_VERTICAL_ATTRACTION_TIMESCALE = 37; public static readonly LSLInteger FALSE = new LSLInteger(0); public static readonly LSLInteger LSL_STATUS_BOUNDS_ERROR = new LSLInteger(1002); public static readonly LSLInteger LSL_STATUS_INTERNAL_ERROR = new LSLInteger(1999); public static readonly LSLInteger LSL_STATUS_MALFORMED_PARAMS = new LSLInteger(1000); public static readonly LSLInteger LSL_STATUS_NOT_FOUND = new LSLInteger(1003); public static readonly LSLInteger LSL_STATUS_NOT_SUPPORTED = new LSLInteger(1004); // extra constants for llSetPrimMediaParams public static readonly LSLInteger LSL_STATUS_OK = new LSLInteger(0); public static readonly LSLInteger LSL_STATUS_TYPE_MISMATCH = new LSLInteger(1001); public static readonly LSLInteger LSL_STATUS_WHITELIST_FAILED = new LSLInteger(2001); public static readonly LSLInteger PAY_DEFAULT = new LSLInteger(-2); // region is a sandbox // region restricts llPushObject public static readonly LSLInteger PAY_HIDE = new LSLInteger(-1); public static readonly LSLInteger RC_DATA_FLAGS = 2; public static readonly LSLInteger RC_DETECT_PHANTOM = 1; public static readonly LSLInteger RC_GET_LINK_NUM = 4; public static readonly LSLInteger RC_GET_NORMAL = 1; public static readonly LSLInteger RC_GET_ROOT_KEY = 2; public static readonly LSLInteger RC_MAX_HITS = 3; public static readonly LSLInteger RC_REJECT_AGENTS = 1; public static readonly LSLInteger RC_REJECT_LAND = 8; public static readonly LSLInteger RC_REJECT_NONPHYSICAL = 4; public static readonly LSLInteger RC_REJECT_PHYSICAL = 2; public static readonly LSLInteger RC_REJECT_TYPES = 0; public static readonly LSLInteger RCERR_CAST_TIME_EXCEEDED = 3; public static readonly LSLInteger RCERR_SIM_PERF_LOW = -2; public static readonly LSLInteger RCERR_UNKNOWN = -1; public static readonly vector TOUCH_INVALID_TEXCOORD = new vector(-1.0, -1.0, 0.0); public static readonly vector TOUCH_INVALID_VECTOR = ZERO_VECTOR; // LSL CONSTANTS public static readonly LSLInteger TRUE = new LSLInteger(1); // Same value as ATTACH_LPEC, see https://jira.secondlife.com/browse/SVC-580 #region osMessageAttachments constants /// <summary> /// Instructs osMessageAttachements to send the message to attachments /// on every point. /// </summary> /// <remarks> /// One might expect this to be named OS_ATTACH_ALL, but then one might /// also expect functions designed to attach or detach or get /// attachments to work with it too. Attaching a no-copy item to /// many attachments could be dangerous. /// when combined with OS_ATTACH_MSG_INVERT_POINTS, will prevent the /// message from being sent. /// if combined with OS_ATTACH_MSG_OBJECT_CREATOR or /// OS_ATTACH_MSG_SCRIPT_CREATOR, could result in no message being /// sent- this is expected behaviour. /// </remarks> public const int OS_ATTACH_MSG_ALL = -65535; /// <summary> /// Instructs osMessageAttachements to invert how the attachment points /// list should be treated (e.g. go from inclusive operation to /// exclusive operation). /// </summary> /// <remarks> /// This might be used if you want to deliver a message to one set of /// attachments and a different message to everything else. With /// this flag, you only need to build one explicit list for both calls. /// </remarks> public const int OS_ATTACH_MSG_INVERT_POINTS = 1; /// <summary> /// Instructs osMessageAttachments to only send the message to /// attachments with a CreatorID that matches the host object CreatorID /// </summary> /// <remarks> /// This would be used if distributed in an object vendor/updater server. /// </remarks> public const int OS_ATTACH_MSG_OBJECT_CREATOR = 2; /// <summary> /// Instructs osMessageAttachments to only send the message to /// attachments with a CreatorID that matches the sending script CreatorID /// </summary> /// <remarks> /// This might be used if the script is distributed independently of a /// containing object. /// </remarks> public const int OS_ATTACH_MSG_SCRIPT_CREATOR = 4; #endregion osMessageAttachments constants public static readonly rotation ZERO_ROTATION = new rotation(0.0, 0.0, 0.0, 1.0); // parcel allows passes to be purchased // parcel restricts llPushObject // parcel allows scripts owned by group // parcel allows with the same group to enter // Can not be public const? public static readonly vector ZERO_VECTOR = new vector(0.0, 0.0, 0.0); } }
/* * Copyright (c) 2007-2009, openmetaverse.org * 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. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using OpenMetaverse.Messages.Linden; #if (COGBOT_LIBOMV || USE_STHREADS) using ThreadPoolUtil; using Thread = ThreadPoolUtil.Thread; using ThreadPool = ThreadPoolUtil.ThreadPool; using Monitor = ThreadPoolUtil.Monitor; #endif using System.Threading; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Globalization; using System.IO; using OpenMetaverse.Packets; using OpenMetaverse.StructuredData; using OpenMetaverse.Interfaces; using OpenMetaverse.Messages.Linden; namespace OpenMetaverse { /// <summary> /// NetworkManager is responsible for managing the network layer of /// OpenMetaverse. It tracks all the server connections, serializes /// outgoing traffic and deserializes incoming traffic, and provides /// instances of delegates for network-related events. /// </summary> public partial class NetworkManager { #region Enums /// <summary> /// Explains why a simulator or the grid disconnected from us /// </summary> public enum DisconnectType { /// <summary>The client requested the logout or simulator disconnect</summary> ClientInitiated, /// <summary>The server notified us that it is disconnecting</summary> ServerInitiated, /// <summary>Either a socket was closed or network traffic timed out</summary> NetworkTimeout, /// <summary>The last active simulator shut down</summary> SimShutdown } #endregion Enums #region Structs /// <summary> /// Holds a simulator reference and a decoded packet, these structs are put in /// the packet inbox for event handling /// </summary> public struct IncomingPacket { /// <summary>Reference to the simulator that this packet came from</summary> public Simulator Simulator; /// <summary>Packet that needs to be processed</summary> public Packet Packet; public IncomingPacket(Simulator simulator, Packet packet) { Simulator = simulator; Packet = packet; } } /// <summary> /// Holds a simulator reference and a serialized packet, these structs are put in /// the packet outbox for sending /// </summary> public class OutgoingPacket { /// <summary>Reference to the simulator this packet is destined for</summary> public readonly Simulator Simulator; /// <summary>Packet that needs to be sent</summary> public readonly UDPPacketBuffer Buffer; /// <summary>Sequence number of the wrapped packet</summary> public uint SequenceNumber; /// <summary>Number of times this packet has been resent</summary> public int ResendCount; /// <summary>Environment.TickCount when this packet was last sent over the wire</summary> public int TickCount; /// <summary>Type of the packet</summary> public PacketType Type; public OutgoingPacket(Simulator simulator, UDPPacketBuffer buffer, PacketType type) { Simulator = simulator; Buffer = buffer; this.Type = type; } } #endregion Structs #region Delegates /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<PacketSentEventArgs> m_PacketSent; ///<summary>Raises the PacketSent Event</summary> /// <param name="e">A PacketSentEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnPacketSent(PacketSentEventArgs e) { EventHandler<PacketSentEventArgs> handler = m_PacketSent; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_PacketSentLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<PacketSentEventArgs> PacketSent { add { lock (m_PacketSentLock) { m_PacketSent += value; } } remove { lock (m_PacketSentLock) { m_PacketSent -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<LoggedOutEventArgs> m_LoggedOut; ///<summary>Raises the LoggedOut Event</summary> /// <param name="e">A LoggedOutEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnLoggedOut(LoggedOutEventArgs e) { EventHandler<LoggedOutEventArgs> handler = m_LoggedOut; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_LoggedOutLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<LoggedOutEventArgs> LoggedOut { add { lock (m_LoggedOutLock) { m_LoggedOut += value; } } remove { lock (m_LoggedOutLock) { m_LoggedOut -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<SimConnectingEventArgs> m_SimConnecting; ///<summary>Raises the SimConnecting Event</summary> /// <param name="e">A SimConnectingEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnSimConnecting(SimConnectingEventArgs e) { EventHandler<SimConnectingEventArgs> handler = m_SimConnecting; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_SimConnectingLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<SimConnectingEventArgs> SimConnecting { add { lock (m_SimConnectingLock) { m_SimConnecting += value; } } remove { lock (m_SimConnectingLock) { m_SimConnecting -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<SimConnectedEventArgs> m_SimConnected; ///<summary>Raises the SimConnected Event</summary> /// <param name="e">A SimConnectedEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnSimConnected(SimConnectedEventArgs e) { EventHandler<SimConnectedEventArgs> handler = m_SimConnected; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_SimConnectedLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<SimConnectedEventArgs> SimConnected { add { lock (m_SimConnectedLock) { m_SimConnected += value; } } remove { lock (m_SimConnectedLock) { m_SimConnected -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<SimDisconnectedEventArgs> m_SimDisconnected; ///<summary>Raises the SimDisconnected Event</summary> /// <param name="e">A SimDisconnectedEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnSimDisconnected(SimDisconnectedEventArgs e) { EventHandler<SimDisconnectedEventArgs> handler = m_SimDisconnected; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_SimDisconnectedLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<SimDisconnectedEventArgs> SimDisconnected { add { lock (m_SimDisconnectedLock) { m_SimDisconnected += value; } } remove { lock (m_SimDisconnectedLock) { m_SimDisconnected -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<DisconnectedEventArgs> m_Disconnected; ///<summary>Raises the Disconnected Event</summary> /// <param name="e">A DisconnectedEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnDisconnected(DisconnectedEventArgs e) { EventHandler<DisconnectedEventArgs> handler = m_Disconnected; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_DisconnectedLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<DisconnectedEventArgs> Disconnected { add { lock (m_DisconnectedLock) { m_Disconnected += value; } } remove { lock (m_DisconnectedLock) { m_Disconnected -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<SimChangedEventArgs> m_SimChanged; ///<summary>Raises the SimChanged Event</summary> /// <param name="e">A SimChangedEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnSimChanged(SimChangedEventArgs e) { EventHandler<SimChangedEventArgs> handler = m_SimChanged; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_SimChangedLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<SimChangedEventArgs> SimChanged { add { lock (m_SimChangedLock) { m_SimChanged += value; } } remove { lock (m_SimChangedLock) { m_SimChanged -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<EventQueueRunningEventArgs> m_EventQueueRunning; ///<summary>Raises the EventQueueRunning Event</summary> /// <param name="e">A EventQueueRunningEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnEventQueueRunning(EventQueueRunningEventArgs e) { EventHandler<EventQueueRunningEventArgs> handler = m_EventQueueRunning; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_EventQueueRunningLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<EventQueueRunningEventArgs> EventQueueRunning { add { lock (m_EventQueueRunningLock) { m_EventQueueRunning += value; } } remove { lock (m_EventQueueRunningLock) { m_EventQueueRunning -= value; } } } #endregion Delegates #region Properties /// <summary>Unique identifier associated with our connections to /// simulators</summary> public uint CircuitCode { get { return _CircuitCode; } set { _CircuitCode = value; } } /// <summary>The simulator that the logged in avatar is currently /// occupying</summary> public Simulator CurrentSim { get { return _CurrentSim; } set { _CurrentSim = value; } } /// <summary>Shows whether the network layer is logged in to the /// grid or not</summary> public bool Connected { get { return connected; } } /// <summary>Number of packets in the incoming queue</summary> public int InboxCount { get { return PacketInbox.Count; } } /// <summary>Number of packets in the outgoing queue</summary> public int OutboxCount { get { return PacketOutbox.Count; } } #endregion Properties /// <summary>All of the simulators we are currently connected to</summary> public List<Simulator> Simulators = new List<Simulator>(); /// <summary>Handlers for incoming capability events</summary> internal CapsEventDictionary CapsEvents; /// <summary>Handlers for incoming packets</summary> internal PacketEventDictionary PacketEvents; /// <summary>Incoming packets that are awaiting handling</summary> internal BlockingQueue<IncomingPacket> PacketInbox = new BlockingQueue<IncomingPacket>(Settings.PACKET_INBOX_SIZE); /// <summary>Outgoing packets that are awaiting handling</summary> internal BlockingQueue<OutgoingPacket> PacketOutbox = new BlockingQueue<OutgoingPacket>(Settings.PACKET_INBOX_SIZE); private GridClient Client; private Timer DisconnectTimer; private uint _CircuitCode; private Simulator _CurrentSim = null; private bool connected = false; /// <summary> /// Default constructor /// </summary> /// <param name="client">Reference to the GridClient object</param> public NetworkManager(GridClient client) { Client = client; PacketEvents = new PacketEventDictionary(client); CapsEvents = new CapsEventDictionary(client); // Register internal CAPS callbacks RegisterEventCallback("EnableSimulator", new Caps.EventQueueCallback(EnableSimulatorHandler)); // Register the internal callbacks RegisterCallback(PacketType.RegionHandshake, RegionHandshakeHandler); RegisterCallback(PacketType.StartPingCheck, StartPingCheckHandler, false); RegisterCallback(PacketType.DisableSimulator, DisableSimulatorHandler); RegisterCallback(PacketType.KickUser, KickUserHandler); RegisterCallback(PacketType.LogoutReply, LogoutReplyHandler); RegisterCallback(PacketType.CompletePingCheck, CompletePingCheckHandler, false); RegisterCallback(PacketType.SimStats, SimStatsHandler, false); // GLOBAL SETTING: Don't force Expect-100: Continue headers on HTTP POST calls ServicePointManager.Expect100Continue = false; } /// <summary> /// Register an event handler for a packet. This is a low level event /// interface and should only be used if you are doing something not /// supported in the library /// </summary> /// <param name="type">Packet type to trigger events for</param> /// <param name="callback">Callback to fire when a packet of this type /// is received</param> public void RegisterCallback(PacketType type, EventHandler<PacketReceivedEventArgs> callback) { RegisterCallback(type, callback, true); } /// <summary> /// Register an event handler for a packet. This is a low level event /// interface and should only be used if you are doing something not /// supported in the library /// </summary> /// <param name="type">Packet type to trigger events for</param> /// <param name="callback">Callback to fire when a packet of this type /// is received</param> /// <param name="isAsync">True if the callback should be ran /// asynchronously. Only set this to false (synchronous for callbacks /// that will always complete quickly)</param> /// <remarks>If any callback for a packet type is marked as /// asynchronous, all callbacks for that packet type will be fired /// asynchronously</remarks> public void RegisterCallback(PacketType type, EventHandler<PacketReceivedEventArgs> callback, bool isAsync) { PacketEvents.RegisterEvent(type, callback, isAsync); } /// <summary> /// Unregister an event handler for a packet. This is a low level event /// interface and should only be used if you are doing something not /// supported in the library /// </summary> /// <param name="type">Packet type this callback is registered with</param> /// <param name="callback">Callback to stop firing events for</param> public void UnregisterCallback(PacketType type, EventHandler<PacketReceivedEventArgs> callback) { PacketEvents.UnregisterEvent(type, callback); } /// <summary> /// Register a CAPS event handler. This is a low level event interface /// and should only be used if you are doing something not supported in /// the library /// </summary> /// <param name="capsEvent">Name of the CAPS event to register a handler for</param> /// <param name="callback">Callback to fire when a CAPS event is received</param> public void RegisterEventCallback(string capsEvent, Caps.EventQueueCallback callback) { CapsEvents.RegisterEvent(capsEvent, callback); } /// <summary> /// Unregister a CAPS event handler. This is a low level event interface /// and should only be used if you are doing something not supported in /// the library /// </summary> /// <param name="capsEvent">Name of the CAPS event this callback is /// registered with</param> /// <param name="callback">Callback to stop firing events for</param> public void UnregisterEventCallback(string capsEvent, Caps.EventQueueCallback callback) { CapsEvents.UnregisterEvent(capsEvent, callback); } /// <summary> /// Send a packet to the simulator the avatar is currently occupying /// </summary> /// <param name="packet">Packet to send</param> public void SendPacket(Packet packet) { // try CurrentSim, however directly after login this will // be null, so if it is, we'll try to find the first simulator // we're connected to in order to send the packet. Simulator simulator = CurrentSim; if (simulator == null && Client.Network.Simulators.Count >= 1) { Logger.DebugLog("CurrentSim object was null, using first found connected simulator", Client); simulator = Client.Network.Simulators[0]; } if (simulator != null && simulator.Connected) { simulator.SendPacket(packet); } else { //throw new NotConnectedException("Packet received before simulator packet processing threads running, make certain you are completely logged in"); Logger.Log("Packet received before simulator packet processing threads running, make certain you are completely logged in.", Helpers.LogLevel.Error); } } /// <summary> /// Send a packet to a specified simulator /// </summary> /// <param name="packet">Packet to send</param> /// <param name="simulator">Simulator to send the packet to</param> public void SendPacket(Packet packet, Simulator simulator) { if (simulator != null) { simulator.SendPacket(packet); } else { Logger.Log("Packet received before simulator packet processing threads running, make certain you are completely logged in", Helpers.LogLevel.Error); } } /// <summary> /// Connect to a simulator /// </summary> /// <param name="ip">IP address to connect to</param> /// <param name="port">Port to connect to</param> /// <param name="handle">Handle for this simulator, to identify its /// location in the grid</param> /// <param name="setDefault">Whether to set CurrentSim to this new /// connection, use this if the avatar is moving in to this simulator</param> /// <param name="seedcaps">URL of the capabilities server to use for /// this sim connection</param> /// <returns>A Simulator object on success, otherwise null</returns> public Simulator Connect(IPAddress ip, ushort port, ulong handle, bool setDefault, string seedcaps) { IPEndPoint endPoint = new IPEndPoint(ip, (int)port); return Connect(endPoint, handle, setDefault, seedcaps); } /// <summary> /// Connect to a simulator /// </summary> /// <param name="endPoint">IP address and port to connect to</param> /// <param name="handle">Handle for this simulator, to identify its /// location in the grid</param> /// <param name="setDefault">Whether to set CurrentSim to this new /// connection, use this if the avatar is moving in to this simulator</param> /// <param name="seedcaps">URL of the capabilities server to use for /// this sim connection</param> /// <returns>A Simulator object on success, otherwise null</returns> public Simulator Connect(IPEndPoint endPoint, ulong handle, bool setDefault, string seedcaps) { Simulator simulator = FindSimulator(endPoint); if (simulator == null) { // We're not tracking this sim, create a new Simulator object simulator = new Simulator(Client, endPoint, handle); // Immediately add this simulator to the list of current sims. It will be removed if the // connection fails lock (Simulators) Simulators.Add(simulator); } if (!simulator.Connected) { if (!connected) { // Mark that we are connecting/connected to the grid // connected = true; // Open the queues in case this is a reconnect and they were shut down PacketInbox.Open(); PacketOutbox.Open(); // Start the packet decoding thread Thread decodeThread = new Thread(new ThreadStart(IncomingPacketHandler)); decodeThread.Name = "Incoming UDP packet dispatcher"; decodeThread.Start(); // Start the packet sending thread Thread sendThread = new Thread(new ThreadStart(OutgoingPacketHandler)); sendThread.Name = "Outgoing UDP packet dispatcher"; sendThread.Start(); } // raise the SimConnecting event and allow any event // subscribers to cancel the connection if (m_SimConnecting != null) { SimConnectingEventArgs args = new SimConnectingEventArgs(simulator); OnSimConnecting(args); if (args.Cancel) { // Callback is requesting that we abort this connection lock (Simulators) { Simulators.Remove(simulator); } return null; } } // Attempt to establish a connection to the simulator if (simulator.Connect(setDefault)) { if (DisconnectTimer == null) { // Start a timer that checks if we've been disconnected DisconnectTimer = new Timer(new TimerCallback(DisconnectTimer_Elapsed), null, Client.Settings.SIMULATOR_TIMEOUT, Client.Settings.SIMULATOR_TIMEOUT); } if (setDefault) { SetCurrentSim(simulator, seedcaps); } // Raise the SimConnected event if (m_SimConnected != null) { OnSimConnected(new SimConnectedEventArgs(simulator)); } // If enabled, send an AgentThrottle packet to the server to increase our bandwidth if (Client.Settings.SEND_AGENT_THROTTLE) { Client.Throttle.Set(simulator); } return simulator; } else { // Connection failed, remove this simulator from our list and destroy it lock (Simulators) { Simulators.Remove(simulator); } return null; } } else if (setDefault) { // Move in to this simulator simulator.handshakeComplete = false; simulator.UseCircuitCode(true); Client.Self.CompleteAgentMovement(simulator); // We're already connected to this server, but need to set it to the default SetCurrentSim(simulator, seedcaps); // Send an initial AgentUpdate to complete our movement in to the sim if (Client.Settings.SEND_AGENT_UPDATES) { Client.Self.Movement.SendUpdate(true, simulator); } return simulator; } else { // Already connected to this simulator and wasn't asked to set it as the default, // just return a reference to the existing object return simulator; } } /// <summary> /// Initiate a blocking logout request. This will return when the logout /// handshake has completed or when <code>Settings.LOGOUT_TIMEOUT</code> /// has expired and the network layer is manually shut down /// </summary> public void Logout() { AutoResetEvent logoutEvent = new AutoResetEvent(false); EventHandler<LoggedOutEventArgs> callback = delegate(object sender, LoggedOutEventArgs e) { logoutEvent.Set(); }; LoggedOut += callback; // Send the packet requesting a clean logout RequestLogout(); // Wait for a logout response. If the response is received, shutdown // will be fired in the callback. Otherwise we fire it manually with // a NetworkTimeout type if (!logoutEvent.WaitOne(Client.Settings.LOGOUT_TIMEOUT, false)) Shutdown(DisconnectType.NetworkTimeout); LoggedOut -= callback; } /// <summary> /// Initiate the logout process. Check if logout succeeded with the /// <code>OnLogoutReply</code> event, and if this does not fire the /// <code>Shutdown()</code> function needs to be manually called /// </summary> public void RequestLogout() { // No need to run the disconnect timer any more if (DisconnectTimer != null) { DisconnectTimer.Dispose(); DisconnectTimer = null; } // This will catch a Logout when the client is not logged in if (CurrentSim == null || !connected) { Logger.Log("Ignoring RequestLogout(), client is already logged out", Helpers.LogLevel.Warning, Client); return; } Logger.Log("Logging out", Helpers.LogLevel.Info, Client); // Send a logout request to the current sim LogoutRequestPacket logout = new LogoutRequestPacket(); logout.AgentData.AgentID = Client.Self.AgentID; logout.AgentData.SessionID = Client.Self.SessionID; SendPacket(logout); } /// <summary> /// Close a connection to the given simulator /// </summary> /// <param name="simulator"></param> /// <param name="sendCloseCircuit"></param> public void DisconnectSim(Simulator simulator, bool sendCloseCircuit) { if (simulator != null) { simulator.Disconnect(sendCloseCircuit); // Fire the SimDisconnected event if a handler is registered if (m_SimDisconnected != null) { OnSimDisconnected(new SimDisconnectedEventArgs(simulator, DisconnectType.NetworkTimeout)); } lock (Simulators) Simulators.Remove(simulator); if (Simulators.Count == 0) Shutdown(DisconnectType.SimShutdown); } else { Logger.Log("DisconnectSim() called with a null Simulator reference", Helpers.LogLevel.Warning, Client); } } /// <summary> /// Shutdown will disconnect all the sims except for the current sim /// first, and then kill the connection to CurrentSim. This should only /// be called if the logout process times out on <code>RequestLogout</code> /// </summary> /// <param name="type">Type of shutdown</param> public void Shutdown(DisconnectType type) { Shutdown(type, type.ToString()); } /// <summary> /// Shutdown will disconnect all the sims except for the current sim /// first, and then kill the connection to CurrentSim. This should only /// be called if the logout process times out on <code>RequestLogout</code> /// </summary> /// <param name="type">Type of shutdown</param> /// <param name="message">Shutdown message</param> public void Shutdown(DisconnectType type, string message) { Logger.Log("NetworkManager shutdown initiated", Helpers.LogLevel.Info, Client); // Send a CloseCircuit packet to simulators if we are initiating the disconnect bool sendCloseCircuit = (type == DisconnectType.ClientInitiated || type == DisconnectType.NetworkTimeout); lock (Simulators) { // Disconnect all simulators except the current one for (int i = 0; i < Simulators.Count; i++) { if (Simulators[i] != null && Simulators[i] != CurrentSim) { Simulators[i].Disconnect(sendCloseCircuit); // Fire the SimDisconnected event if a handler is registered if (m_SimDisconnected != null) { OnSimDisconnected(new SimDisconnectedEventArgs(Simulators[i], type)); } } } Simulators.Clear(); } if (CurrentSim != null) { // Kill the connection to the curent simulator CurrentSim.Disconnect(sendCloseCircuit); // Fire the SimDisconnected event if a handler is registered if (m_SimDisconnected != null) { OnSimDisconnected(new SimDisconnectedEventArgs(CurrentSim, type)); } } // Clear out all of the packets that never had time to process PacketInbox.Close(); PacketOutbox.Close(); connected = false; // Fire the disconnected callback if (m_Disconnected != null) { OnDisconnected(new DisconnectedEventArgs(type, message)); } } /// <summary> /// Searches through the list of currently connected simulators to find /// one attached to the given IPEndPoint /// </summary> /// <param name="endPoint">IPEndPoint of the Simulator to search for</param> /// <returns>A Simulator reference on success, otherwise null</returns> public Simulator FindSimulator(IPEndPoint endPoint) { lock (Simulators) { for (int i = 0; i < Simulators.Count; i++) { if (Simulators[i].IPEndPoint.Equals(endPoint)) return Simulators[i]; } } return null; } internal void RaisePacketSentEvent(byte[] data, int bytesSent, Simulator simulator) { if (m_PacketSent != null) { OnPacketSent(new PacketSentEventArgs(data, bytesSent, simulator)); } } /// <summary> /// Fire an event when an event queue connects for capabilities /// </summary> /// <param name="simulator">Simulator the event queue is attached to</param> internal void RaiseConnectedEvent(Simulator simulator) { if (m_EventQueueRunning != null) { OnEventQueueRunning(new EventQueueRunningEventArgs(simulator)); } } private void OutgoingPacketHandler() { OutgoingPacket outgoingPacket = null; Simulator simulator; // FIXME: This is kind of ridiculous. Port the HTB code from Simian over ASAP! System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); while (connected) { if (PacketOutbox.Dequeue(100, ref outgoingPacket)) { simulator = outgoingPacket.Simulator; // Very primitive rate limiting, keeps a fixed buffer of time between each packet stopwatch.Stop(); if (stopwatch.ElapsedMilliseconds < 10) { //Logger.DebugLog(String.Format("Rate limiting, last packet was {0}ms ago", ms)); Thread.Sleep(10 - (int)stopwatch.ElapsedMilliseconds); } simulator.SendPacketFinal(outgoingPacket); stopwatch.Start(); } } } private void IncomingPacketHandler() { IncomingPacket incomingPacket = new IncomingPacket(); Packet packet = null; Simulator simulator = null; while (connected) { // Reset packet to null for the check below packet = null; if (PacketInbox.Dequeue(100, ref incomingPacket)) { packet = incomingPacket.Packet; simulator = incomingPacket.Simulator; if (packet != null) { // Skip blacklisted packets if (UDPBlacklist.Contains(packet.Type.ToString())) { Logger.Log(String.Format("Discarding Blacklisted packet {0} from {1}", packet.Type, simulator.IPEndPoint), Helpers.LogLevel.Warning); return; } // Fire the callback(s), if any PacketEvents.RaiseEvent(packet.Type, packet, simulator); } } } } private void SetCurrentSim(Simulator simulator, string seedcaps) { if (simulator != CurrentSim) { Simulator oldSim = CurrentSim; lock (Simulators) CurrentSim = simulator; // CurrentSim is synchronized against Simulators simulator.SetSeedCaps(seedcaps); // If the current simulator changed fire the callback if (m_SimChanged != null && simulator != oldSim) { OnSimChanged(new SimChangedEventArgs(oldSim)); } } } #region Timers private void DisconnectTimer_Elapsed(object obj) { if (!connected || CurrentSim == null) { if (DisconnectTimer != null) { DisconnectTimer.Dispose(); DisconnectTimer = null; } connected = false; } else if (CurrentSim.DisconnectCandidate) { // The currently occupied simulator hasn't sent us any traffic in a while, shutdown Logger.Log("Network timeout for the current simulator (" + CurrentSim.ToString() + "), logging out", Helpers.LogLevel.Warning, Client); if (DisconnectTimer != null) { DisconnectTimer.Dispose(); DisconnectTimer = null; } connected = false; // Shutdown the network layer Shutdown(DisconnectType.NetworkTimeout); } else { // Mark the current simulator as potentially disconnected each time this timer fires. // If the timer is fired again before any packets are received, an actual disconnect // sequence will be triggered CurrentSim.DisconnectCandidate = true; } } #endregion Timers #region Packet Callbacks /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void LogoutReplyHandler(object sender, PacketReceivedEventArgs e) { LogoutReplyPacket logout = (LogoutReplyPacket)e.Packet; if ((logout.AgentData.SessionID == Client.Self.SessionID) && (logout.AgentData.AgentID == Client.Self.AgentID)) { Logger.DebugLog("Logout reply received", Client); // Deal with callbacks, if any if (m_LoggedOut != null) { List<UUID> itemIDs = new List<UUID>(); foreach (LogoutReplyPacket.InventoryDataBlock InventoryData in logout.InventoryData) { itemIDs.Add(InventoryData.ItemID); } OnLoggedOut(new LoggedOutEventArgs(itemIDs)); } // If we are receiving a LogoutReply packet assume this is a client initiated shutdown Shutdown(DisconnectType.ClientInitiated); } else { Logger.Log("Invalid Session or Agent ID received in Logout Reply... ignoring", Helpers.LogLevel.Warning, Client); } } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void StartPingCheckHandler(object sender, PacketReceivedEventArgs e) { StartPingCheckPacket incomingPing = (StartPingCheckPacket)e.Packet; CompletePingCheckPacket ping = new CompletePingCheckPacket(); ping.PingID.PingID = incomingPing.PingID.PingID; ping.Header.Reliable = false; // TODO: We can use OldestUnacked to correct transmission errors // I don't think that's right. As far as I can tell, the Viewer // only uses this to prune its duplicate-checking buffer. -bushing SendPacket(ping, e.Simulator); } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void CompletePingCheckHandler(object sender, PacketReceivedEventArgs e) { CompletePingCheckPacket pong = (CompletePingCheckPacket)e.Packet; //String retval = "Pong2: " + (Environment.TickCount - e.Simulator.Stats.LastPingSent); //if ((pong.PingID.PingID - e.Simulator.Stats.LastPingID + 1) != 0) // retval += " (gap of " + (pong.PingID.PingID - e.Simulator.Stats.LastPingID + 1) + ")"; e.Simulator.Stats.LastLag = Environment.TickCount - e.Simulator.Stats.LastPingSent; e.Simulator.Stats.ReceivedPongs++; // Client.Log(retval, Helpers.LogLevel.Info); } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void SimStatsHandler(object sender, PacketReceivedEventArgs e) { if (!Client.Settings.ENABLE_SIMSTATS) { return; } SimStatsPacket stats = (SimStatsPacket)e.Packet; for (int i = 0; i < stats.Stat.Length; i++) { SimStatsPacket.StatBlock s = stats.Stat[i]; switch (s.StatID) { case 0: e.Simulator.Stats.Dilation = s.StatValue; break; case 1: e.Simulator.Stats.FPS = Convert.ToInt32(s.StatValue); break; case 2: e.Simulator.Stats.PhysicsFPS = s.StatValue; break; case 3: e.Simulator.Stats.AgentUpdates = s.StatValue; break; case 4: e.Simulator.Stats.FrameTime = s.StatValue; break; case 5: e.Simulator.Stats.NetTime = s.StatValue; break; case 6: e.Simulator.Stats.OtherTime = s.StatValue; break; case 7: e.Simulator.Stats.PhysicsTime = s.StatValue; break; case 8: e.Simulator.Stats.AgentTime = s.StatValue; break; case 9: e.Simulator.Stats.ImageTime = s.StatValue; break; case 10: e.Simulator.Stats.ScriptTime = s.StatValue; break; case 11: e.Simulator.Stats.Objects = Convert.ToInt32(s.StatValue); break; case 12: e.Simulator.Stats.ScriptedObjects = Convert.ToInt32(s.StatValue); break; case 13: e.Simulator.Stats.Agents = Convert.ToInt32(s.StatValue); break; case 14: e.Simulator.Stats.ChildAgents = Convert.ToInt32(s.StatValue); break; case 15: e.Simulator.Stats.ActiveScripts = Convert.ToInt32(s.StatValue); break; case 16: e.Simulator.Stats.LSLIPS = Convert.ToInt32(s.StatValue); break; case 17: e.Simulator.Stats.INPPS = Convert.ToInt32(s.StatValue); break; case 18: e.Simulator.Stats.OUTPPS = Convert.ToInt32(s.StatValue); break; case 19: e.Simulator.Stats.PendingDownloads = Convert.ToInt32(s.StatValue); break; case 20: e.Simulator.Stats.PendingUploads = Convert.ToInt32(s.StatValue); break; case 21: e.Simulator.Stats.VirtualSize = Convert.ToInt32(s.StatValue); break; case 22: e.Simulator.Stats.ResidentSize = Convert.ToInt32(s.StatValue); break; case 23: e.Simulator.Stats.PendingLocalUploads = Convert.ToInt32(s.StatValue); break; case 24: e.Simulator.Stats.UnackedBytes = Convert.ToInt32(s.StatValue); break; } } } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void RegionHandshakeHandler(object sender, PacketReceivedEventArgs e) { RegionHandshakePacket handshake = (RegionHandshakePacket)e.Packet; Simulator simulator = e.Simulator; e.Simulator.ID = handshake.RegionInfo.CacheID; simulator.IsEstateManager = handshake.RegionInfo.IsEstateManager; simulator.Name = Utils.BytesToString(handshake.RegionInfo.SimName); simulator.SimOwner = handshake.RegionInfo.SimOwner; simulator.TerrainBase0 = handshake.RegionInfo.TerrainBase0; simulator.TerrainBase1 = handshake.RegionInfo.TerrainBase1; simulator.TerrainBase2 = handshake.RegionInfo.TerrainBase2; simulator.TerrainBase3 = handshake.RegionInfo.TerrainBase3; simulator.TerrainDetail0 = handshake.RegionInfo.TerrainDetail0; simulator.TerrainDetail1 = handshake.RegionInfo.TerrainDetail1; simulator.TerrainDetail2 = handshake.RegionInfo.TerrainDetail2; simulator.TerrainDetail3 = handshake.RegionInfo.TerrainDetail3; simulator.TerrainHeightRange00 = handshake.RegionInfo.TerrainHeightRange00; simulator.TerrainHeightRange01 = handshake.RegionInfo.TerrainHeightRange01; simulator.TerrainHeightRange10 = handshake.RegionInfo.TerrainHeightRange10; simulator.TerrainHeightRange11 = handshake.RegionInfo.TerrainHeightRange11; simulator.TerrainStartHeight00 = handshake.RegionInfo.TerrainStartHeight00; simulator.TerrainStartHeight01 = handshake.RegionInfo.TerrainStartHeight01; simulator.TerrainStartHeight10 = handshake.RegionInfo.TerrainStartHeight10; simulator.TerrainStartHeight11 = handshake.RegionInfo.TerrainStartHeight11; simulator.WaterHeight = handshake.RegionInfo.WaterHeight; simulator.Flags = (RegionFlags)handshake.RegionInfo.RegionFlags; simulator.BillableFactor = handshake.RegionInfo.BillableFactor; simulator.Access = (SimAccess)handshake.RegionInfo.SimAccess; simulator.RegionID = handshake.RegionInfo2.RegionID; simulator.ColoLocation = Utils.BytesToString(handshake.RegionInfo3.ColoName); simulator.CPUClass = handshake.RegionInfo3.CPUClassID; simulator.CPURatio = handshake.RegionInfo3.CPURatio; simulator.ProductName = Utils.BytesToString(handshake.RegionInfo3.ProductName); simulator.ProductSku = Utils.BytesToString(handshake.RegionInfo3.ProductSKU); // Send a RegionHandshakeReply RegionHandshakeReplyPacket reply = new RegionHandshakeReplyPacket(); reply.AgentData.AgentID = Client.Self.AgentID; reply.AgentData.SessionID = Client.Self.SessionID; reply.RegionInfo.Flags = 0; SendPacket(reply, simulator); // We're officially connected to this sim simulator.connected = true; simulator.handshakeComplete = true; simulator.ConnectedEvent.Set(); } protected void EnableSimulatorHandler(string capsKey, IMessage message, Simulator simulator) { if (!Client.Settings.MULTIPLE_SIMS) return; EnableSimulatorMessage msg = (EnableSimulatorMessage)message; for (int i = 0; i < msg.Simulators.Length; i++) { IPAddress ip = msg.Simulators[i].IP; ushort port = (ushort)msg.Simulators[i].Port; ulong handle = msg.Simulators[i].RegionHandle; IPEndPoint endPoint = new IPEndPoint(ip, port); if (FindSimulator(endPoint) != null) return; if (Connect(ip, port, handle, false, null) == null) { Logger.Log("Unabled to connect to new sim " + ip + ":" + port, Helpers.LogLevel.Error, Client); } } } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void DisableSimulatorHandler(object sender, PacketReceivedEventArgs e) { DisconnectSim(e.Simulator, false); } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void KickUserHandler(object sender, PacketReceivedEventArgs e) { string message = Utils.BytesToString(((KickUserPacket)e.Packet).UserInfo.Reason); // Shutdown the network layer Shutdown(DisconnectType.ServerInitiated, message); } #endregion Packet Callbacks } #region EventArgs public class PacketReceivedEventArgs : EventArgs { private readonly Packet m_Packet; private readonly Simulator m_Simulator; public Packet Packet { get { return m_Packet; } } public Simulator Simulator { get { return m_Simulator; } } public PacketReceivedEventArgs(Packet packet, Simulator simulator) { this.m_Packet = packet; this.m_Simulator = simulator; } } public class LoggedOutEventArgs : EventArgs { private readonly List<UUID> m_InventoryItems; public List<UUID> InventoryItems; public LoggedOutEventArgs(List<UUID> inventoryItems) { this.m_InventoryItems = inventoryItems; } } public class PacketSentEventArgs : EventArgs { private readonly byte[] m_Data; private readonly int m_SentBytes; private readonly Simulator m_Simulator; public byte[] Data { get { return m_Data; } } public int SentBytes { get { return m_SentBytes; } } public Simulator Simulator { get { return m_Simulator; } } public PacketSentEventArgs(byte[] data, int bytesSent, Simulator simulator) { this.m_Data = data; this.m_SentBytes = bytesSent; this.m_Simulator = simulator; } } public class SimConnectingEventArgs : EventArgs { private readonly Simulator m_Simulator; private bool m_Cancel; public Simulator Simulator { get { return m_Simulator; } } public bool Cancel { get { return m_Cancel; } set { m_Cancel = value; } } public SimConnectingEventArgs(Simulator simulator) { this.m_Simulator = simulator; this.m_Cancel = false; } } public class SimConnectedEventArgs : EventArgs { private readonly Simulator m_Simulator; public Simulator Simulator { get { return m_Simulator; } } public SimConnectedEventArgs(Simulator simulator) { this.m_Simulator = simulator; } } public class SimDisconnectedEventArgs : EventArgs { private readonly Simulator m_Simulator; private readonly NetworkManager.DisconnectType m_Reason; public Simulator Simulator { get { return m_Simulator; } } public NetworkManager.DisconnectType Reason { get { return m_Reason; } } public SimDisconnectedEventArgs(Simulator simulator, NetworkManager.DisconnectType reason) { this.m_Simulator = simulator; this.m_Reason = reason; } } public class DisconnectedEventArgs : EventArgs { private readonly NetworkManager.DisconnectType m_Reason; private readonly String m_Message; public NetworkManager.DisconnectType Reason { get { return m_Reason; } } public String Message { get { return m_Message; } } public DisconnectedEventArgs(NetworkManager.DisconnectType reason, String message) { this.m_Reason = reason; this.m_Message = message; } } public class SimChangedEventArgs : EventArgs { private readonly Simulator m_PreviousSimulator; public Simulator PreviousSimulator { get { return m_PreviousSimulator; } } public SimChangedEventArgs(Simulator previousSimulator) { this.m_PreviousSimulator = previousSimulator; } } public class EventQueueRunningEventArgs : EventArgs { private readonly Simulator m_Simulator; public Simulator Simulator { get { return m_Simulator; } } public EventQueueRunningEventArgs(Simulator simulator) { this.m_Simulator = simulator; } } #endregion }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal abstract partial class AbstractEditorInlineRenameService : IEditorInlineRenameService { private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices; protected AbstractEditorInlineRenameService(IEnumerable<IRefactorNotifyService> refactorNotifyServices) { _refactorNotifyServices = refactorNotifyServices; } public Task<IInlineRenameInfo> GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken) { // This is unpleasant, but we do everything synchronously. That's because we end up // needing to make calls on the UI thread to determine if the locations of the symbol // are in readonly buffer sections or not. If we go pure async we have the following // problem: // 1) if we call ConfigureAwait(false), then we might call into the text buffer on // the wrong thread. // 2) if we try to call those pieces of code on the UI thread, then we will deadlock // as our caller often is doing a 'Wait' on us, and our UI calling code won't run. var info = this.GetRenameInfo(document, position, cancellationToken); return Task.FromResult(info); } private IInlineRenameInfo GetRenameInfo(Document document, int position, CancellationToken cancellationToken) { var triggerToken = GetTriggerToken(document, position, cancellationToken); if (triggerToken == default(SyntaxToken)) { return new FailureInlineRenameInfo(EditorFeaturesResources.You_must_rename_an_identifier); } return GetRenameInfo(_refactorNotifyServices, document, triggerToken, cancellationToken); } internal static IInlineRenameInfo GetRenameInfo( IEnumerable<IRefactorNotifyService> refactorNotifyServices, Document document, SyntaxToken triggerToken, CancellationToken cancellationToken) { var syntaxFactsService = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); if (syntaxFactsService.IsKeyword(triggerToken)) { return new FailureInlineRenameInfo(EditorFeaturesResources.You_must_rename_an_identifier); } var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); var semanticFacts = document.GetLanguageService<ISemanticFactsService>(); var tokenRenameInfo = RenameUtilities.GetTokenRenameInfo(semanticFacts, semanticModel, triggerToken, cancellationToken); // Rename was invoked on a member group reference in a nameof expression. // Trigger the rename on any of the candidate symbols but force the // RenameOverloads option to be on. var triggerSymbol = tokenRenameInfo.HasSymbols ? tokenRenameInfo.Symbols.First() : null; if (triggerSymbol == null) { return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element); } // see https://github.com/dotnet/roslyn/issues/10898 // we are disabling rename for tuple fields for now // 1) compiler does not return correct location information in these symbols // 2) renaming tuple fields seems a complex enough thing to require some design if (triggerSymbol.ContainingType?.IsTupleType == true) { return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element); } // If rename is invoked on a member group reference in a nameof expression, then the // RenameOverloads option should be forced on. var forceRenameOverloads = tokenRenameInfo.IsMemberGroup; if (syntaxFactsService.IsTypeNamedVarInVariableOrFieldDeclaration(triggerToken, triggerToken.Parent)) { // To check if var in this context is a real type, or the keyword, we need to // speculatively bind the identifier "var". If it returns a symbol, it's a real type, // if not, it's the keyword. // see bugs 659683 (compiler API) and 659705 (rename/workspace api) for examples var symbolForVar = semanticModel.GetSpeculativeSymbolInfo( triggerToken.SpanStart, triggerToken.Parent, SpeculativeBindingOption.BindAsTypeOrNamespace).Symbol; if (symbolForVar == null) { return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element); } } var symbolAndProjectId = RenameLocations.ReferenceProcessing.GetRenamableSymbolAsync(document, triggerToken.SpanStart, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); var symbol = symbolAndProjectId.Symbol; if (symbol == null) { return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element); } if (symbol.Kind == SymbolKind.Alias && symbol.IsExtern) { return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element); } // Cannot rename constructors in VB. TODO: this logic should be in the VB subclass of this type. var workspace = document.Project.Solution.Workspace; if (symbol != null && symbol.Kind == SymbolKind.NamedType && symbol.Language == LanguageNames.VisualBasic && triggerToken.ToString().Equals("New", StringComparison.OrdinalIgnoreCase)) { var originalSymbol = SymbolFinder.FindSymbolAtPositionAsync(semanticModel, triggerToken.SpanStart, workspace, cancellationToken: cancellationToken) .WaitAndGetResult(cancellationToken); if (originalSymbol != null && originalSymbol.IsConstructor()) { return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element); } } if (syntaxFactsService.IsTypeNamedDynamic(triggerToken, triggerToken.Parent)) { if (symbol.Kind == SymbolKind.DynamicType) { return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element); } } // we allow implicit locals and parameters of Event handlers if (symbol.IsImplicitlyDeclared && symbol.Kind != SymbolKind.Local && !(symbol.Kind == SymbolKind.Parameter && symbol.ContainingSymbol.Kind == SymbolKind.Method && symbol.ContainingType != null && symbol.ContainingType.IsDelegateType() && symbol.ContainingType.AssociatedSymbol != null)) { // We enable the parameter in RaiseEvent, if the Event is declared with a signature. If the Event is declared as a // delegate type, we do not have a connection between the delegate type and the event. // this prevents a rename in this case :(. return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element); } if (symbol.Kind == SymbolKind.Property && symbol.ContainingType.IsAnonymousType) { return new FailureInlineRenameInfo(EditorFeaturesResources.Renaming_anonymous_type_members_is_not_yet_supported); } if (symbol.IsErrorType()) { return new FailureInlineRenameInfo(EditorFeaturesResources.Please_resolve_errors_in_your_code_before_renaming_this_element); } if (symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).MethodKind == MethodKind.UserDefinedOperator) { return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_operators); } var symbolLocations = symbol.Locations; // Does our symbol exist in an unchangeable location? var navigationService = workspace.Services.GetService<IDocumentNavigationService>(); foreach (var location in symbolLocations) { if (location.IsInMetadata) { return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_elements_that_are_defined_in_metadata); } else if (location.IsInSource) { if (document.Project.IsSubmission) { var solution = document.Project.Solution; var projectIdOfLocation = solution.GetDocument(location.SourceTree).Project.Id; if (solution.Projects.Any(p => p.IsSubmission && p.ProjectReferences.Any(r => r.ProjectId == projectIdOfLocation))) { return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_elements_from_previous_submissions); } } else { var sourceText = location.SourceTree.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); var textSnapshot = sourceText.FindCorrespondingEditorTextSnapshot(); if (textSnapshot != null) { var buffer = textSnapshot.TextBuffer; var originalSpan = location.SourceSpan.ToSnapshotSpan(textSnapshot).TranslateTo(buffer.CurrentSnapshot, SpanTrackingMode.EdgeInclusive); if (buffer.IsReadOnly(originalSpan) || !navigationService.CanNavigateToSpan(workspace, document.Id, location.SourceSpan)) { return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element); } } } } else { return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element); } } return new SymbolInlineRenameInfo( refactorNotifyServices, document, triggerToken.Span, symbolAndProjectId, forceRenameOverloads, cancellationToken); } private SyntaxToken GetTriggerToken(Document document, int position, CancellationToken cancellationToken) { var syntaxTree = document.GetSyntaxTreeSynchronously(cancellationToken); var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var token = syntaxTree.GetTouchingWordAsync(position, syntaxFacts, cancellationToken, findInsideTrivia: true).WaitAndGetResult(cancellationToken); return token; } } }
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using WriterException = com.google.zxing.WriterException; using EncodeHintType = com.google.zxing.EncodeHintType; using ByteArray = com.google.zxing.common.ByteArray; using ByteMatrix = com.google.zxing.common.ByteMatrix; using CharacterSetECI = com.google.zxing.common.CharacterSetECI; using GF256 = com.google.zxing.common.reedsolomon.GF256; using ReedSolomonEncoder = com.google.zxing.common.reedsolomon.ReedSolomonEncoder; using ErrorCorrectionLevel = com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; using Mode = com.google.zxing.qrcode.decoder.Mode; using Version = com.google.zxing.qrcode.decoder.Version; using System.Collections.Generic; namespace com.google.zxing.qrcode.encoder { /// <author> satorux@google.com (Satoru Takabayashi) - creator /// </author> /// <author> dswitkin@google.com (Daniel Switkin) - ported from C++ /// </author> /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source /// </author> public sealed class Encoder { // The original table is defined in the table 5 of JISX0510:2004 (p.19). //UPGRADE_NOTE: Final was removed from the declaration of 'ALPHANUMERIC_TABLE'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private static readonly int[] ALPHANUMERIC_TABLE = new int[]{- 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, 36, - 1, - 1, - 1, 37, 38, - 1, - 1, - 1, - 1, 39, 40, - 1, 41, 42, 43, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, - 1, - 1, - 1, - 1, - 1, - 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, - 1, - 1, - 1, - 1, - 1}; internal const System.String DEFAULT_BYTE_MODE_ENCODING = "ISO-8859-1"; private Encoder() { } // The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details. // Basically it applies four rules and summate all penalties. private static int calculateMaskPenalty(ByteMatrix matrix) { int penalty = 0; penalty += MaskUtil.applyMaskPenaltyRule1(matrix); penalty += MaskUtil.applyMaskPenaltyRule2(matrix); penalty += MaskUtil.applyMaskPenaltyRule3(matrix); penalty += MaskUtil.applyMaskPenaltyRule4(matrix); return penalty; } /// <summary> Encode "bytes" with the error correction level "ecLevel". The encoding mode will be chosen /// internally by chooseMode(). On success, store the result in "qrCode". /// /// We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for /// "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very /// strong error correction for this purpose. /// /// Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode() /// with which clients can specify the encoding mode. For now, we don't need the functionality. /// </summary> public static void encode(System.String content, ErrorCorrectionLevel ecLevel, QRCode qrCode) { encode(content, ecLevel, null, qrCode); } public static void encode(System.String content, ErrorCorrectionLevel ecLevel, Dictionary<object, object> hints, QRCode qrCode) { System.String encoding = hints == null?null:(System.String) hints[EncodeHintType.CHARACTER_SET]; if (encoding == null) { encoding = DEFAULT_BYTE_MODE_ENCODING; } // Step 1: Choose the mode (encoding). Mode mode = chooseMode(content, encoding); // Step 2: Append "bytes" into "dataBits" in appropriate encoding. BitVector dataBits = new BitVector(); appendBytes(content, mode, dataBits, encoding); // Step 3: Initialize QR code that can contain "dataBits". int numInputBytes = dataBits.sizeInBytes(); initQRCode(numInputBytes, ecLevel, mode, qrCode); // Step 4: Build another bit vector that contains header and data. BitVector headerAndDataBits = new BitVector(); // Step 4.5: Append ECI message if applicable if (mode == Mode.BYTE && !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding)) { CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding); if (eci != null) { appendECI(eci, headerAndDataBits); } } appendModeInfo(mode, headerAndDataBits); int numLetters = mode.Equals(Mode.BYTE)?dataBits.sizeInBytes():content.Length; appendLengthInfo(numLetters, qrCode.Version, mode, headerAndDataBits); headerAndDataBits.appendBitVector(dataBits); // Step 5: Terminate the bits properly. terminateBits(qrCode.NumDataBytes, headerAndDataBits); // Step 6: Interleave data bits with error correction code. BitVector finalBits = new BitVector(); interleaveWithECBytes(headerAndDataBits, qrCode.NumTotalBytes, qrCode.NumDataBytes, qrCode.NumRSBlocks, finalBits); // Step 7: Choose the mask pattern and set to "qrCode". ByteMatrix matrix = new ByteMatrix(qrCode.MatrixWidth, qrCode.MatrixWidth); qrCode.MaskPattern = chooseMaskPattern(finalBits, qrCode.ECLevel, qrCode.Version, matrix); // Step 8. Build the matrix and set it to "qrCode". MatrixUtil.buildMatrix(finalBits, qrCode.ECLevel, qrCode.Version, qrCode.MaskPattern, matrix); qrCode.Matrix = matrix; // Step 9. Make sure we have a valid QR Code. if (!qrCode.Valid) { throw new WriterException("Invalid QR code: " + qrCode.ToString()); } } /// <returns> the code point of the table used in alphanumeric mode or /// -1 if there is no corresponding code in the table. /// </returns> internal static int getAlphanumericCode(int code) { if (code < ALPHANUMERIC_TABLE.Length) { return ALPHANUMERIC_TABLE[code]; } return - 1; } public static Mode chooseMode(System.String content) { return chooseMode(content, null); } /// <summary> Choose the best mode by examining the content. Note that 'encoding' is used as a hint; /// if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}. /// </summary> public static Mode chooseMode(System.String content, System.String encoding) { if ("Shift_JIS".Equals(encoding)) { // Choose Kanji mode if all input are double-byte characters return isOnlyDoubleByteKanji(content)?Mode.KANJI:Mode.BYTE; } bool hasNumeric = false; bool hasAlphanumeric = false; for (int i = 0; i < content.Length; ++i) { char c = content[i]; if (c >= '0' && c <= '9') { hasNumeric = true; } else if (getAlphanumericCode(c) != - 1) { hasAlphanumeric = true; } else { return Mode.BYTE; } } if (hasAlphanumeric) { return Mode.ALPHANUMERIC; } else if (hasNumeric) { return Mode.NUMERIC; } return Mode.BYTE; } private static bool isOnlyDoubleByteKanji(System.String content) { sbyte[] bytes; try { //UPGRADE_TODO: Method 'java.lang.String.getBytes' was converted to 'System.Text.Encoding.GetEncoding(string).GetBytes(string)' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javalangStringgetBytes_javalangString'" bytes = SupportClass.ToSByteArray(System.Text.Encoding.GetEncoding("Shift_JIS").GetBytes(content)); } catch (System.IO.IOException) { return false; } int length = bytes.Length; if (length % 2 != 0) { return false; } for (int i = 0; i < length; i += 2) { int byte1 = bytes[i] & 0xFF; if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB)) { return false; } } return true; } private static int chooseMaskPattern(BitVector bits, ErrorCorrectionLevel ecLevel, int version, ByteMatrix matrix) { int minPenalty = System.Int32.MaxValue; // Lower penalty is better. int bestMaskPattern = - 1; // We try all mask patterns to choose the best one. for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) { MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix); int penalty = calculateMaskPenalty(matrix); if (penalty < minPenalty) { minPenalty = penalty; bestMaskPattern = maskPattern; } } return bestMaskPattern; } /// <summary> Initialize "qrCode" according to "numInputBytes", "ecLevel", and "mode". On success, /// modify "qrCode". /// </summary> private static void initQRCode(int numInputBytes, ErrorCorrectionLevel ecLevel, Mode mode, QRCode qrCode) { qrCode.ECLevel = ecLevel; qrCode.Mode = mode; // In the following comments, we use numbers of Version 7-H. for (int versionNum = 1; versionNum <= 40; versionNum++) { Version version = Version.getVersionForNumber(versionNum); // numBytes = 196 int numBytes = version.TotalCodewords; // getNumECBytes = 130 Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); int numEcBytes = ecBlocks.TotalECCodewords; // getNumRSBlocks = 5 int numRSBlocks = ecBlocks.NumBlocks; // getNumDataBytes = 196 - 130 = 66 int numDataBytes = numBytes - numEcBytes; // We want to choose the smallest version which can contain data of "numInputBytes" + some // extra bits for the header (mode info and length info). The header can be three bytes // (precisely 4 + 16 bits) at most. Hence we do +3 here. if (numDataBytes >= numInputBytes + 3) { // Yay, we found the proper rs block info! qrCode.Version = versionNum; qrCode.NumTotalBytes = numBytes; qrCode.NumDataBytes = numDataBytes; qrCode.NumRSBlocks = numRSBlocks; // getNumECBytes = 196 - 66 = 130 qrCode.NumECBytes = numEcBytes; // matrix width = 21 + 6 * 4 = 45 qrCode.MatrixWidth = version.DimensionForVersion; return ; } } throw new WriterException("Cannot find proper rs block info (input data too big?)"); } /// <summary> Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).</summary> internal static void terminateBits(int numDataBytes, BitVector bits) { int capacity = numDataBytes << 3; if (bits.size() > capacity) { throw new WriterException("data bits cannot fit in the QR Code" + bits.size() + " > " + capacity); } // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details. // TODO: srowen says we can remove this for loop, since the 4 terminator bits are optional if // the last byte has less than 4 bits left. So it amounts to padding the last byte with zeroes // either way. for (int i = 0; i < 4 && bits.size() < capacity; ++i) { bits.appendBit(0); } int numBitsInLastByte = bits.size() % 8; // If the last byte isn't 8-bit aligned, we'll add padding bits. if (numBitsInLastByte > 0) { int numPaddingBits = 8 - numBitsInLastByte; for (int i = 0; i < numPaddingBits; ++i) { bits.appendBit(0); } } // Should be 8-bit aligned here. if (bits.size() % 8 != 0) { throw new WriterException("Number of bits is not a multiple of 8"); } // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24). int numPaddingBytes = numDataBytes - bits.sizeInBytes(); for (int i = 0; i < numPaddingBytes; ++i) { if (i % 2 == 0) { bits.appendBits(0xec, 8); } else { bits.appendBits(0x11, 8); } } if (bits.size() != capacity) { throw new WriterException("Bits size does not equal capacity"); } } /// <summary> Get number of data bytes and number of error correction bytes for block id "blockID". Store /// the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of /// JISX0510:2004 (p.30) /// </summary> internal static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes, int numRSBlocks, int blockID, int[] numDataBytesInBlock, int[] numECBytesInBlock) { if (blockID >= numRSBlocks) { throw new WriterException("Block ID too large"); } // numRsBlocksInGroup2 = 196 % 5 = 1 int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks; // numRsBlocksInGroup1 = 5 - 1 = 4 int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2; // numTotalBytesInGroup1 = 196 / 5 = 39 int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks; // numTotalBytesInGroup2 = 39 + 1 = 40 int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1; // numDataBytesInGroup1 = 66 / 5 = 13 int numDataBytesInGroup1 = numDataBytes / numRSBlocks; // numDataBytesInGroup2 = 13 + 1 = 14 int numDataBytesInGroup2 = numDataBytesInGroup1 + 1; // numEcBytesInGroup1 = 39 - 13 = 26 int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1; // numEcBytesInGroup2 = 40 - 14 = 26 int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2; // Sanity checks. // 26 = 26 if (numEcBytesInGroup1 != numEcBytesInGroup2) { throw new WriterException("EC bytes mismatch"); } // 5 = 4 + 1. if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) { throw new WriterException("RS blocks mismatch"); } // 196 = (13 + 26) * 4 + (14 + 26) * 1 if (numTotalBytes != ((numDataBytesInGroup1 + numEcBytesInGroup1) * numRsBlocksInGroup1) + ((numDataBytesInGroup2 + numEcBytesInGroup2) * numRsBlocksInGroup2)) { throw new WriterException("Total bytes mismatch"); } if (blockID < numRsBlocksInGroup1) { numDataBytesInBlock[0] = numDataBytesInGroup1; numECBytesInBlock[0] = numEcBytesInGroup1; } else { numDataBytesInBlock[0] = numDataBytesInGroup2; numECBytesInBlock[0] = numEcBytesInGroup2; } } /// <summary> Interleave "bits" with corresponding error correction bytes. On success, store the result in /// "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details. /// </summary> internal static void interleaveWithECBytes(BitVector bits, int numTotalBytes, int numDataBytes, int numRSBlocks, BitVector result) { // "bits" must have "getNumDataBytes" bytes of data. if (bits.sizeInBytes() != numDataBytes) { throw new WriterException("Number of bits and data bytes does not match"); } // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll // store the divided data bytes blocks and error correction bytes blocks into "blocks". int dataBytesOffset = 0; int maxNumDataBytes = 0; int maxNumEcBytes = 0; // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number. List<object> blocks = new List<object>(); for (int i = 0; i < numRSBlocks; ++i) { int[] numDataBytesInBlock = new int[1]; int[] numEcBytesInBlock = new int[1]; getNumDataBytesAndNumECBytesForBlockID(numTotalBytes, numDataBytes, numRSBlocks, i, numDataBytesInBlock, numEcBytesInBlock); ByteArray dataBytes = new ByteArray(); dataBytes.set_Renamed(bits.Array, dataBytesOffset, numDataBytesInBlock[0]); ByteArray ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]); blocks.Add(new BlockPair(dataBytes, ecBytes)); maxNumDataBytes = System.Math.Max(maxNumDataBytes, dataBytes.size()); maxNumEcBytes = System.Math.Max(maxNumEcBytes, ecBytes.size()); dataBytesOffset += numDataBytesInBlock[0]; } if (numDataBytes != dataBytesOffset) { throw new WriterException("Data bytes does not match offset"); } // First, place data blocks. for (int i = 0; i < maxNumDataBytes; ++i) { for (int j = 0; j < blocks.Count; ++j) { ByteArray dataBytes = ((BlockPair) blocks[j]).DataBytes; if (i < dataBytes.size()) { result.appendBits(dataBytes.at(i), 8); } } } // Then, place error correction blocks. for (int i = 0; i < maxNumEcBytes; ++i) { for (int j = 0; j < blocks.Count; ++j) { ByteArray ecBytes = ((BlockPair) blocks[j]).ErrorCorrectionBytes; if (i < ecBytes.size()) { result.appendBits(ecBytes.at(i), 8); } } } if (numTotalBytes != result.sizeInBytes()) { // Should be same. throw new WriterException("Interleaving error: " + numTotalBytes + " and " + result.sizeInBytes() + " differ."); } } internal static ByteArray generateECBytes(ByteArray dataBytes, int numEcBytesInBlock) { int numDataBytes = dataBytes.size(); int[] toEncode = new int[numDataBytes + numEcBytesInBlock]; for (int i = 0; i < numDataBytes; i++) { toEncode[i] = dataBytes.at(i); } new ReedSolomonEncoder(GF256.QR_CODE_FIELD).encode(toEncode, numEcBytesInBlock); ByteArray ecBytes = new ByteArray(numEcBytesInBlock); for (int i = 0; i < numEcBytesInBlock; i++) { ecBytes.set_Renamed(i, toEncode[numDataBytes + i]); } return ecBytes; } /// <summary> Append mode info. On success, store the result in "bits".</summary> internal static void appendModeInfo(Mode mode, BitVector bits) { bits.appendBits(mode.Bits, 4); } /// <summary> Append length info. On success, store the result in "bits".</summary> internal static void appendLengthInfo(int numLetters, int version, Mode mode, BitVector bits) { int numBits = mode.getCharacterCountBits(Version.getVersionForNumber(version)); if (numLetters > ((1 << numBits) - 1)) { throw new WriterException(numLetters + "is bigger than" + ((1 << numBits) - 1)); } bits.appendBits(numLetters, numBits); } /// <summary> Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits".</summary> internal static void appendBytes(System.String content, Mode mode, BitVector bits, System.String encoding) { if (mode.Equals(Mode.NUMERIC)) { appendNumericBytes(content, bits); } else if (mode.Equals(Mode.ALPHANUMERIC)) { appendAlphanumericBytes(content, bits); } else if (mode.Equals(Mode.BYTE)) { append8BitBytes(content, bits, encoding); } else if (mode.Equals(Mode.KANJI)) { appendKanjiBytes(content, bits); } else { throw new WriterException("Invalid mode: " + mode); } } internal static void appendNumericBytes(System.String content, BitVector bits) { int length = content.Length; int i = 0; while (i < length) { int num1 = content[i] - '0'; if (i + 2 < length) { // Encode three numeric letters in ten bits. int num2 = content[i + 1] - '0'; int num3 = content[i + 2] - '0'; bits.appendBits(num1 * 100 + num2 * 10 + num3, 10); i += 3; } else if (i + 1 < length) { // Encode two numeric letters in seven bits. int num2 = content[i + 1] - '0'; bits.appendBits(num1 * 10 + num2, 7); i += 2; } else { // Encode one numeric letter in four bits. bits.appendBits(num1, 4); i++; } } } internal static void appendAlphanumericBytes(System.String content, BitVector bits) { int length = content.Length; int i = 0; while (i < length) { int code1 = getAlphanumericCode(content[i]); if (code1 == - 1) { throw new WriterException(); } if (i + 1 < length) { int code2 = getAlphanumericCode(content[i + 1]); if (code2 == - 1) { throw new WriterException(); } // Encode two alphanumeric letters in 11 bits. bits.appendBits(code1 * 45 + code2, 11); i += 2; } else { // Encode one alphanumeric letter in six bits. bits.appendBits(code1, 6); i++; } } } internal static void append8BitBytes(System.String content, BitVector bits, System.String encoding) { sbyte[] bytes; try { //UPGRADE_TODO: Method 'java.lang.String.getBytes' was converted to 'System.Text.Encoding.GetEncoding(string).GetBytes(string)' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javalangStringgetBytes_javalangString'" bytes = SupportClass.ToSByteArray(System.Text.Encoding.GetEncoding(encoding).GetBytes(content)); } catch (System.IO.IOException uee) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" throw new WriterException(uee.ToString()); } for (int i = 0; i < bytes.Length; ++i) { bits.appendBits(bytes[i], 8); } } internal static void appendKanjiBytes(System.String content, BitVector bits) { sbyte[] bytes; try { //UPGRADE_TODO: Method 'java.lang.String.getBytes' was converted to 'System.Text.Encoding.GetEncoding(string).GetBytes(string)' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javalangStringgetBytes_javalangString'" bytes = SupportClass.ToSByteArray(System.Text.Encoding.GetEncoding("Shift_JIS").GetBytes(content)); } catch (System.IO.IOException uee) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" throw new WriterException(uee.ToString()); } int length = bytes.Length; for (int i = 0; i < length; i += 2) { int byte1 = bytes[i] & 0xFF; int byte2 = bytes[i + 1] & 0xFF; int code = (byte1 << 8) | byte2; int subtracted = - 1; if (code >= 0x8140 && code <= 0x9ffc) { subtracted = code - 0x8140; } else if (code >= 0xe040 && code <= 0xebbf) { subtracted = code - 0xc140; } if (subtracted == - 1) { throw new WriterException("Invalid byte sequence"); } int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff); bits.appendBits(encoded, 13); } } private static void appendECI(CharacterSetECI eci, BitVector bits) { bits.appendBits(Mode.ECI.Bits, 4); // This is correct for values up to 127, which is all we need now. bits.appendBits(eci.Value, 8); } } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Collections.Generic; using System.Globalization; using NLog.Config; using NLog.Targets; using NLog.UnitTests.Common; namespace NLog.UnitTests.Fluent { using System; using System.IO; using Xunit; using NLog.Fluent; public class LogBuilderTests : NLogTestBase { private static readonly ILogger _logger = LogManager.GetLogger("logger1"); public LogBuilderTests() { var configuration = new LoggingConfiguration(); var t1 = new LastLogEventListTarget { Name = "t1" }; var t2 = new DebugTarget { Name = "t2", Layout = "${message}" }; configuration.AddTarget(t1); configuration.AddTarget(t2); configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, t1)); configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, t2)); LogManager.Configuration = configuration; } [Fact] public void TraceWrite() { TraceWrite_internal(() => _logger.Trace()); } #if NET4_5 [Fact] public void TraceWrite_static_builder() { TraceWrite_internal(() => Log.Trace(), true); } #endif ///<remarks> /// func because 1 logbuilder creates 1 message /// /// Caution: don't use overloading, that will break xUnit: /// CATASTROPHIC ERROR OCCURRED: /// System.ArgumentException: Ambiguous method named TraceWrite in type NLog.UnitTests.Fluent.LogBuilderTests /// </remarks> private void TraceWrite_internal(Func<LogBuilder> logBuilder, bool isStatic = false) { logBuilder() .Message("This is a test fluent message.") .Property("Test", "TraceWrite") .Write(); var loggerName = isStatic ? "LogBuilderTests" : "logger1"; { var expectedEvent = new LogEventInfo(LogLevel.Trace, loggerName, "This is a test fluent message."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); } var ticks = DateTime.Now.Ticks; logBuilder() .Message("This is a test fluent message '{0}'.", ticks) .Property("Test", "TraceWrite") .Write(); { var rendered = string.Format("This is a test fluent message '{0}'.", ticks); var expectedEvent = new LogEventInfo(LogLevel.Trace, loggerName, "This is a test fluent message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessage("t2", rendered); } } [Fact] public void TraceWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; _logger.Trace() .Message("This is a test fluent message.") .Properties(props).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } [Fact] public void WarnWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; _logger.Warn() .Message("This is a test fluent message.") .Properties(props).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Warn, "logger1", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } [Fact] public void LogWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; _logger.Log(LogLevel.Fatal) .Message("This is a test fluent message.") .Properties(props).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Fatal, "logger1", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } [Fact] public void LogOffWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; var props2 = new Dictionary<string, object> { {"prop1", "4"}, {"prop2", "5"}, }; _logger.Log(LogLevel.Fatal) .Message("This is a test fluent message.") .Properties(props).Write(); _logger.Log(LogLevel.Off) .Message("dont log this.") .Properties(props2).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Fatal, "logger1", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } #if NET4_5 [Fact] public void LevelWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; Log.Level(LogLevel.Fatal) .Message("This is a test fluent message.") .Properties(props).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Fatal, "LogBuilderTests", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } #endif [Fact] public void TraceIfWrite() { _logger.Trace() .Message("This is a test fluent message.1") .Property("Test", "TraceWrite") .Write(); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent message.1"); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); } int v = 1; _logger.Trace() .Message("This is a test fluent WriteIf message '{0}'.", DateTime.Now.Ticks) .Property("Test", "TraceWrite") .WriteIf(() => v == 1); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent WriteIf message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent WriteIf message "); } _logger.Trace() .Message("dont write this! '{0}'.", DateTime.Now.Ticks) .Property("Test", "TraceWrite") .WriteIf(() => { return false; }); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent WriteIf message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent WriteIf message "); } _logger.Trace() .Message("This is a test fluent WriteIf message '{0}'.", DateTime.Now.Ticks) .Property("Test", "TraceWrite") .WriteIf(v == 1); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent WriteIf message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent WriteIf message "); } _logger.Trace() .Message("Should Not WriteIf message '{0}'.", DateTime.Now.Ticks) .Property("Test", "TraceWrite") .WriteIf(v > 1); { //previous var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent WriteIf message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent WriteIf message "); } } [Fact] public void InfoWrite() { InfoWrite_internal(() => _logger.Info()); } #if NET4_5 [Fact] public void InfoWrite_static_builder() { InfoWrite_internal(() => Log.Info(), true); } #endif ///<remarks> /// func because 1 logbuilder creates 1 message /// /// Caution: don't use overloading, that will break xUnit: /// CATASTROPHIC ERROR OCCURRED: /// System.ArgumentException: Ambiguous method named TraceWrite in type NLog.UnitTests.Fluent.LogBuilderTests /// </remarks> private void InfoWrite_internal(Func<LogBuilder> logBuilder, bool isStatic = false) { logBuilder() .Message("This is a test fluent message.") .Property("Test", "InfoWrite") .Write(); var loggerName = isStatic ? "LogBuilderTests" : "logger1"; { //previous var expectedEvent = new LogEventInfo(LogLevel.Info, loggerName, "This is a test fluent message."); expectedEvent.Properties["Test"] = "InfoWrite"; AssertLastLogEventTarget(expectedEvent); } logBuilder() .Message("This is a test fluent message '{0}'.", DateTime.Now.Ticks) .Property("Test", "InfoWrite") .Write(); { //previous var expectedEvent = new LogEventInfo(LogLevel.Info, loggerName, "This is a test fluent message '{0}'."); expectedEvent.Properties["Test"] = "InfoWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent message '"); } } [Fact] public void DebugWrite() { ErrorWrite_internal(() => _logger.Debug(), LogLevel.Debug); } #if NET4_5 [Fact] public void DebugWrite_static_builder() { ErrorWrite_internal(() => Log.Debug(), LogLevel.Debug, true); } #endif [Fact] public void FatalWrite() { ErrorWrite_internal(() => _logger.Fatal(), LogLevel.Fatal); } #if NET4_5 [Fact] public void FatalWrite_static_builder() { ErrorWrite_internal(() => Log.Fatal(), LogLevel.Fatal, true); } #endif [Fact] public void ErrorWrite() { ErrorWrite_internal(() => _logger.Error(), LogLevel.Error); } #if NET4_5 [Fact] public void ErrorWrite_static_builder() { ErrorWrite_internal(() => Log.Error(), LogLevel.Error, true); } #endif [Fact] public void LogBuilder_null_lead_to_ArgumentNullException() { var logger = LogManager.GetLogger("a"); Assert.Throws<ArgumentNullException>(() => new LogBuilder(null, LogLevel.Debug)); Assert.Throws<ArgumentNullException>(() => new LogBuilder(null)); Assert.Throws<ArgumentNullException>(() => new LogBuilder(logger, null)); var logBuilder = new LogBuilder(logger); Assert.Throws<ArgumentNullException>(() => logBuilder.Properties(null)); Assert.Throws<ArgumentNullException>(() => logBuilder.Property(null, "b")); } [Fact] public void LogBuilder_nLogEventInfo() { var d = new DateTime(2015, 01, 30, 14, 30, 5); var logEventInfo = new LogBuilder(LogManager.GetLogger("a")).LoggerName("b").Level(LogLevel.Fatal).TimeStamp(d).LogEventInfo; Assert.Equal("b", logEventInfo.LoggerName); Assert.Equal(LogLevel.Fatal, logEventInfo.Level); Assert.Equal(d, logEventInfo.TimeStamp); } [Fact] public void LogBuilder_exception_only() { var ex = new Exception("Exception message1"); _logger.Error() .Exception(ex) .Write(); var expectedEvent = new LogEventInfo(LogLevel.Error, "logger1", null) { Exception = ex }; AssertLastLogEventTarget(expectedEvent); } [Fact] public void LogBuilder_null_logLevel() { Assert.Throws<ArgumentNullException>(() => _logger.Error().Level(null)); } [Fact] public void LogBuilder_message_overloadsTest() { LogManager.ThrowExceptions = true; _logger.Debug() .Message("Message with {0} arg", 1) .Write(); AssertDebugLastMessage("t2", "Message with 1 arg"); _logger.Debug() .Message("Message with {0} args. {1}", 2, "YES") .Write(); AssertDebugLastMessage("t2", "Message with 2 args. YES"); _logger.Debug() .Message("Message with {0} args. {1} {2}", 3, ":) ", 2) .Write(); AssertDebugLastMessage("t2", "Message with 3 args. :) 2"); _logger.Debug() .Message("Message with {0} args. {1} {2}{3}", "more", ":) ", 2, "b") .Write(); AssertDebugLastMessage("t2", "Message with more args. :) 2b"); } [Fact] public void LogBuilder_message_cultureTest() { LogManager.Configuration.DefaultCultureInfo = GetCultureInfo("en-US"); _logger.Debug() .Message("Message with {0} {1} {2} {3}", 4.1, 4.001, new DateTime(2016, 12, 31), true) .Write(); AssertDebugLastMessage("t2", "Message with 4.1 4.001 12/31/2016 12:00:00 AM True"); _logger.Debug() .Message(GetCultureInfo("nl-nl"), "Message with {0} {1} {2} {3}", 4.1, 4.001, new DateTime(2016, 12, 31), true) .Write(); AssertDebugLastMessage("t2", "Message with 4,1 4,001 31-12-2016 00:00:00 True"); } ///<remarks> /// func because 1 logbuilder creates 1 message /// /// Caution: don't use overloading, that will break xUnit: /// CATASTROPHIC ERROR OCCURRED: /// System.ArgumentException: Ambiguous method named TraceWrite in type NLog.UnitTests.Fluent.LogBuilderTests /// </remarks> private void ErrorWrite_internal(Func<LogBuilder> logBuilder, LogLevel logLevel, bool isStatic = false) { Exception catchedException = null; string path = "blah.txt"; try { string text = File.ReadAllText(path); } catch (Exception ex) { catchedException = ex; logBuilder() .Message("Error reading file '{0}'.", path) .Exception(ex) .Property("Test", "ErrorWrite") .Write(); } var loggerName = isStatic ? "LogBuilderTests" : "logger1"; { var expectedEvent = new LogEventInfo(logLevel, loggerName, "Error reading file '{0}'."); expectedEvent.Properties["Test"] = "ErrorWrite"; expectedEvent.Exception = catchedException; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "Error reading file '"); } logBuilder() .Message("This is a test fluent message.") .Property("Test", "ErrorWrite") .Write(); { var expectedEvent = new LogEventInfo(logLevel, loggerName, "This is a test fluent message."); expectedEvent.Properties["Test"] = "ErrorWrite"; AssertLastLogEventTarget(expectedEvent); } logBuilder() .Message("This is a test fluent message '{0}'.", DateTime.Now.Ticks) .Property("Test", "ErrorWrite") .Write(); { var expectedEvent = new LogEventInfo(logLevel, loggerName, "This is a test fluent message '{0}'."); expectedEvent.Properties["Test"] = "ErrorWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent message '"); } } /// <summary> /// Test the written logevent /// </summary> /// <param name="expected">exptected event to be logged.</param> static void AssertLastLogEventTarget(LogEventInfo expected) { var target = LogManager.Configuration.FindTargetByName<LastLogEventListTarget>("t1"); Assert.NotNull(target); var lastLogEvent = target.LastLogEvent; Assert.NotNull(lastLogEvent); Assert.Equal(expected.Message, lastLogEvent.Message); Assert.NotNull(lastLogEvent.Properties); //remove caller as they are also removed from the alleventrenders. lastLogEvent.Properties.Remove("CallerMemberName"); lastLogEvent.Properties.Remove("CallerLineNumber"); lastLogEvent.Properties.Remove("CallerFilePath"); Assert.Equal(expected.Properties, lastLogEvent.Properties); Assert.Equal(expected.LoggerName, lastLogEvent.LoggerName); Assert.Equal(expected.Level, lastLogEvent.Level); Assert.Equal(expected.Exception, lastLogEvent.Exception); Assert.Equal(expected.FormatProvider, lastLogEvent.FormatProvider); } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoad.Business.ERLevel { /// <summary> /// C07_Country_Child (editable child object).<br/> /// This is a generated base class of <see cref="C07_Country_Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="C06_Country"/> collection. /// </remarks> [Serializable] public partial class C07_Country_Child : BusinessBase<C07_Country_Child> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Country_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Country_Child_NameProperty = RegisterProperty<string>(p => p.Country_Child_Name, "Regions Child Name"); /// <summary> /// Gets or sets the Regions Child Name. /// </summary> /// <value>The Regions Child Name.</value> public string Country_Child_Name { get { return GetProperty(Country_Child_NameProperty); } set { SetProperty(Country_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="C07_Country_Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="C07_Country_Child"/> object.</returns> internal static C07_Country_Child NewC07_Country_Child() { return DataPortal.CreateChild<C07_Country_Child>(); } /// <summary> /// Factory method. Loads a <see cref="C07_Country_Child"/> object, based on given parameters. /// </summary> /// <param name="country_ID1">The Country_ID1 parameter of the C07_Country_Child to fetch.</param> /// <returns>A reference to the fetched <see cref="C07_Country_Child"/> object.</returns> internal static C07_Country_Child GetC07_Country_Child(int country_ID1) { return DataPortal.FetchChild<C07_Country_Child>(country_ID1); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="C07_Country_Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public C07_Country_Child() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="C07_Country_Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="C07_Country_Child"/> object from the database, based on given criteria. /// </summary> /// <param name="country_ID1">The Country ID1.</param> protected void Child_Fetch(int country_ID1) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetC07_Country_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Country_ID1", country_ID1).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, country_ID1); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="C07_Country_Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Country_Child_NameProperty, dr.GetString("Country_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="C07_Country_Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(C06_Country parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddC07_Country_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Country_ID1", parent.Country_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Country_Child_Name", ReadProperty(Country_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="C07_Country_Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(C06_Country parent) { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateC07_Country_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Country_ID1", parent.Country_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Country_Child_Name", ReadProperty(Country_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="C07_Country_Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(C06_Country parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteC07_Country_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Country_ID1", parent.Country_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; using System.Collections.Generic; using System.Linq; using NMahjong.Aux; using NMahjong.Base; using TA = NMahjong.Japanese.TileAnnotations; namespace NMahjong.Japanese.Engine { internal class GameStateImpl : IGameState { private readonly Quad<PlayerStateImpl> mPlayerImpls; private readonly Quad<IPlayerState> mPlayers; private HandStartingEventArgs mHand; private List<Dora> mDora; private PlayerId mTurn; internal GameStateImpl(Quad<String> names, Quad<Int32> scores) { HandState = HandState.NotStarted; var players = new PlayerStateImpl[4]; for (int i = 0; i < 4; i++) { players[i] = new PlayerStateImpl(names[i], scores[i]); } mPlayerImpls = Quad.Of(players); mPlayers = Quad.Of<IPlayerState>(players); } [VisibleForTesting] internal Quad<PlayerStateImpl> PlayerImpls { get { return mPlayerImpls; } } public Quad<IPlayerState> Players { get { return mPlayers; } } public HandState HandState { get; private set; } public PlayerId Turn { get { EnsureStarted(); return mTurn; } } public IWall Wall { get { EnsureStarted(); return mHand.Wall; } } public PlayerId Dealer { get { EnsureStarted(); return mHand.Dealer; } } public Wind PrevailingWind { get { EnsureStarted(); return mHand.PrevailingWind; } } public int HandNumber { get { EnsureStarted(); return mHand.HandNumber; } } public int Counters { get; private set; } public int RiichiSticks { get; private set; } public ReadOnlyListView<Dora> Dora { get { EnsureStarted(); return mDora.AsReadOnlyView(); } } internal void RegisterHandlers(IEventHandlerRegisterer registerer) { registerer.AddOnHandStarting(OnHandStarting); registerer.AddOnHandStarted(OnHandStarted); registerer.AddOnHandEnded(OnHandEnded); registerer.AddOnDoraAdded(OnDoraAdded); registerer.AddOnMeldExtended(OnMeldExtended); registerer.AddOnMeldRevealed(OnMeldRevealed); registerer.AddOnPlayerHandUpdated(OnPlayerHandUpdated); registerer.AddOnScoreUpdated(OnScoreUpdated); registerer.AddOnSticksUpdated(OnSticksUpdated); registerer.AddOnTileDiscarded(OnTileDiscarded); registerer.AddOnTileDrawn(OnTileDrawn); } [VisibleForTesting] internal void SetHandStateForTest(HandState handState) { HandState = handState; } private void OnHandStarting(object sender, HandStartingEventArgs e) { EnsureHandState(HandState.NotStarted, HandState.Ended); CheckArg.Expect(e.Wall is WallImpl, "e.Wall", "Object must be created through {0}.", typeof(Wall)); mDora = new List<Dora>(); mTurn = e.Dealer; mHand = e; for (int i = 0; i < 4; i++) { mPlayerImpls[i].StartHand((Wind) ((i - e.Dealer.Id + 4) % 4)); } HandState = HandState.Starting; } private void OnHandStarted(object sender, EventArgs e) { EnsureHandState(HandState.Starting); for (int i = 0; i < 4; i++) { CheckState.IsSet(mPlayerImpls[i].Tiles, "Players[" + i + "].Tiles"); } HandState = HandState.Playing; } private void OnHandEnded(object sender, EventArgs e) { EnsureHandState(HandState.Playing); HandState = HandState.Ended; } private void OnDoraAdded(object sender, DoraAddedEventArgs e) { EnsureHandState(HandState.Starting, HandState.Playing); mDora.Add(e.Dora); (mHand.Wall as WallImpl).OnDoraAdded(e.Dora); } private void OnMeldExtended(object sender, MeldExtendedEventArgs e) { EnsureHandState(HandState.Playing); mTurn = e.Player; mPlayerImpls[e.Player].ExtendMeld(e.Extender); } private void OnMeldRevealed(object sender, MeldRevealedEventArgs e) { EnsureHandState(HandState.Playing); mTurn = e.Player; if (e.Meld.IsOpen()) { mPlayerImpls[e.Meld.Feeder].AnnotateLastDiscard(TA.Claimed); } mPlayerImpls[e.Player].RevealMeld(e.Meld); } private void OnPlayerHandUpdated(object sender, PlayerHandUpdatedEventArgs e) { EnsureHandState(HandState.Starting, HandState.Playing); CheckArg.Expect(e.Tiles is IPlayerHandInternal, "e.Tiles", "Object must be created through {0}.", typeof(PlayerHand)); mPlayerImpls[e.Player].SetTiles(e.Tiles as IPlayerHandInternal); } private void OnScoreUpdated(object sender, ScoreUpdatedEventArgs e) { EnsureHandState(HandState.Starting, HandState.Playing); mPlayerImpls[e.Player].Score = e.Score; } private void OnSticksUpdated(object sender, SticksUpdatedEventArgs e) { EnsureHandState(HandState.Starting, HandState.Playing); Counters = e.Counters; RiichiSticks = e.RiichiSticks; } private void OnTileDiscarded(object sender, TileDiscardedEventArgs e) { EnsureHandState(HandState.Playing); mTurn = e.Player; mPlayerImpls[e.Player].Discard(e.Discard); } private void OnTileDrawn(object sender, TileDrawnEventArgs e) { EnsureHandState(HandState.Playing); mTurn = e.Player; (mHand.Wall as WallImpl).OnTileDrawn(e.Tile); mPlayerImpls[e.Player].Draw(e.Tile); } private void EnsureStarted() { CheckState.Expect(HandState != HandState.NotStarted, "No hands have been started yet."); } private void EnsureHandState(params HandState[] allowedStates) { CheckState.Expect(allowedStates.Contains(HandState), "Event is inconsistent with HandState."); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Streams.Core; namespace Orleans.Streams { [Serializable] internal class PubSubGrainState { public HashSet<PubSubPublisherState> Producers { get; set; } = new HashSet<PubSubPublisherState>(); public HashSet<PubSubSubscriptionState> Consumers { get; set; } = new HashSet<PubSubSubscriptionState>(); } [Orleans.Providers.StorageProvider(ProviderName = "PubSubStore")] internal class PubSubRendezvousGrain : Grain<PubSubGrainState>, IPubSubRendezvousGrain { private Logger logger; private const bool DEBUG_PUB_SUB = false; private static readonly CounterStatistic counterProducersAdded; private static readonly CounterStatistic counterProducersRemoved; private static readonly CounterStatistic counterProducersTotal; private static readonly CounterStatistic counterConsumersAdded; private static readonly CounterStatistic counterConsumersRemoved; private static readonly CounterStatistic counterConsumersTotal; private readonly ISiloStatusOracle siloStatusOracle; static PubSubRendezvousGrain() { counterProducersAdded = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_ADDED); counterProducersRemoved = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_REMOVED); counterProducersTotal = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_TOTAL); counterConsumersAdded = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_ADDED); counterConsumersRemoved = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_REMOVED); counterConsumersTotal = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_TOTAL); } public PubSubRendezvousGrain(ISiloStatusOracle siloStatusOracle) { this.siloStatusOracle = siloStatusOracle; } public override async Task OnActivateAsync() { logger = GetLogger(GetType().Name + "-" + RuntimeIdentity + "-" + IdentityString); LogPubSubCounts("OnActivateAsync"); int numRemoved = RemoveDeadProducers(); if (numRemoved > 0) { if (State.Producers.Count > 0 || State.Consumers.Count > 0) await WriteStateAsync(); else await ClearStateAsync(); //State contains no producers or consumers, remove it from storage } logger.Verbose("OnActivateAsync-Done"); } public override Task OnDeactivateAsync() { LogPubSubCounts("OnDeactivateAsync"); return Task.CompletedTask; } private int RemoveDeadProducers() { // Remove only those we know for sure are Dead. int numRemoved = 0; if (State.Producers != null && State.Producers.Count > 0) numRemoved = State.Producers.RemoveWhere(producerState => IsDeadProducer(producerState.Producer)); if (numRemoved > 0) { LogPubSubCounts("RemoveDeadProducers: removed {0} outdated producers", numRemoved); } return numRemoved; } /// accept and notify only Active producers. private bool IsActiveProducer(IStreamProducerExtension producer) { var grainRef = producer as GrainReference; if (grainRef !=null && grainRef.GrainId.IsSystemTarget && grainRef.IsInitializedSystemTarget) return siloStatusOracle.GetApproximateSiloStatus(grainRef.SystemTargetSilo) == SiloStatus.Active; return true; } private bool IsDeadProducer(IStreamProducerExtension producer) { var grainRef = producer as GrainReference; if (grainRef != null && grainRef.GrainId.IsSystemTarget && grainRef.IsInitializedSystemTarget) return siloStatusOracle.GetApproximateSiloStatus(grainRef.SystemTargetSilo) == SiloStatus.Dead; return false; } public async Task<ISet<PubSubSubscriptionState>> RegisterProducer(StreamId streamId, IStreamProducerExtension streamProducer) { counterProducersAdded.Increment(); if (!IsActiveProducer(streamProducer)) throw new ArgumentException($"Trying to register non active IStreamProducerExtension: {streamProducer}", "streamProducer"); try { int producersRemoved = RemoveDeadProducers(); var publisherState = new PubSubPublisherState(streamId, streamProducer); State.Producers.Add(publisherState); LogPubSubCounts("RegisterProducer {0}", streamProducer); await WriteStateAsync(); counterProducersTotal.DecrementBy(producersRemoved); counterProducersTotal.Increment(); } catch (Exception exc) { logger.Error(ErrorCode.Stream_RegisterProducerFailed, $"Failed to register a stream producer. Stream: {streamId}, Producer: {streamProducer}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } return State.Consumers.Where(c => !c.IsFaulted).ToSet(); } public async Task UnregisterProducer(StreamId streamId, IStreamProducerExtension streamProducer) { counterProducersRemoved.Increment(); try { int numRemoved = State.Producers.RemoveWhere(s => s.Equals(streamId, streamProducer)); LogPubSubCounts("UnregisterProducer {0} NumRemoved={1}", streamProducer, numRemoved); if (numRemoved > 0) { Task updateStorageTask = State.Producers.Count == 0 && State.Consumers.Count == 0 ? ClearStateAsync() //State contains no producers or consumers, remove it from storage : WriteStateAsync(); await updateStorageTask; } counterProducersTotal.DecrementBy(numRemoved); } catch (Exception exc) { logger.Error(ErrorCode.Stream_UnegisterProducerFailed, $"Failed to unregister a stream producer. Stream: {streamId}, Producer: {streamProducer}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } if (State.Producers.Count == 0 && State.Consumers.Count == 0) { DeactivateOnIdle(); // No producers or consumers left now, so flag ourselves to expedite Deactivation } } public async Task RegisterConsumer( GuidId subscriptionId, StreamId streamId, IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter) { counterConsumersAdded.Increment(); PubSubSubscriptionState pubSubState = State.Consumers.FirstOrDefault(s => s.Equals(subscriptionId)); if (pubSubState != null && pubSubState.IsFaulted) throw new FaultedSubscriptionException(subscriptionId, streamId); try { if (pubSubState == null) { pubSubState = new PubSubSubscriptionState(subscriptionId, streamId, streamConsumer); State.Consumers.Add(pubSubState); } if (filter != null) pubSubState.AddFilter(filter); LogPubSubCounts("RegisterConsumer {0}", streamConsumer); await WriteStateAsync(); counterConsumersTotal.Increment(); } catch (Exception exc) { logger.Error(ErrorCode.Stream_RegisterConsumerFailed, $"Failed to register a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}, Consumer: {streamConsumer}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } int numProducers = State.Producers.Count; if (numProducers <= 0) return; if (logger.IsVerbose) logger.Info("Notifying {0} existing producer(s) about new consumer {1}. Producers={2}", numProducers, streamConsumer, Utils.EnumerableToString(State.Producers)); // Notify producers about a new streamConsumer. var tasks = new List<Task>(); var producers = State.Producers.ToList(); int initialProducerCount = producers.Count; try { foreach (var producerState in producers) { PubSubPublisherState producer = producerState; // Capture loop variable if (!IsActiveProducer(producer.Producer)) { // Producer is not active (could be stopping / shutting down) so skip if (logger.IsVerbose) logger.Verbose("Producer {0} on stream {1} is not active - skipping.", producer, streamId); continue; } tasks.Add(NotifyProducerOfNewSubscriber(producer, subscriptionId, streamId, streamConsumer, filter)); } Exception exception = null; try { await Task.WhenAll(tasks); } catch (Exception exc) { exception = exc; } // if the number of producers has been changed, resave state. if (State.Producers.Count != initialProducerCount) { await WriteStateAsync(); counterConsumersTotal.DecrementBy(initialProducerCount - State.Producers.Count); } if (exception != null) { throw exception; } } catch (Exception exc) { logger.Error(ErrorCode.Stream_RegisterConsumerFailed, $"Failed to update producers while register a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}, Consumer: {streamConsumer}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } } private async Task NotifyProducerOfNewSubscriber(PubSubPublisherState producer, GuidId subscriptionId, StreamId streamId, IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter) { try { await producer.Producer.AddSubscriber(subscriptionId, streamId, streamConsumer, filter); } catch (GrainExtensionNotInstalledException) { RemoveProducer(producer); } catch (ClientNotAvailableException) { RemoveProducer(producer); } } private void RemoveProducer(PubSubPublisherState producer) { logger.Warn(ErrorCode.Stream_ProducerIsDead, "Producer {0} on stream {1} is no longer active - permanently removing producer.", producer, producer.Stream); State.Producers.Remove(producer); } public async Task UnregisterConsumer(GuidId subscriptionId, StreamId streamId) { counterConsumersRemoved.Increment(); try { int numRemoved = State.Consumers.RemoveWhere(c => c.Equals(subscriptionId)); LogPubSubCounts("UnregisterSubscription {0} NumRemoved={1}", subscriptionId, numRemoved); if (await TryClearState()) { // If state was cleared expedite Deactivation DeactivateOnIdle(); } else { if (numRemoved != 0) { await WriteStateAsync(); } await NotifyProducersOfRemovedSubscription(subscriptionId, streamId); } counterConsumersTotal.DecrementBy(numRemoved); } catch (Exception exc) { logger.Error(ErrorCode.Stream_UnregisterConsumerFailed, $"Failed to unregister a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } } public Task<int> ProducerCount(StreamId streamId) { return Task.FromResult(State.Producers.Count); } public Task<int> ConsumerCount(StreamId streamId) { return Task.FromResult(GetConsumersForStream(streamId).Length); } public Task<PubSubSubscriptionState[]> DiagGetConsumers(StreamId streamId) { return Task.FromResult(GetConsumersForStream(streamId)); } private PubSubSubscriptionState[] GetConsumersForStream(StreamId streamId) { return State.Consumers.Where(c => !c.IsFaulted && c.Stream.Equals(streamId)).ToArray(); } private void LogPubSubCounts(string fmt, params object[] args) { if (logger.IsVerbose || DEBUG_PUB_SUB) { int numProducers = 0; int numConsumers = 0; if (State?.Producers != null) numProducers = State.Producers.Count; if (State?.Consumers != null) numConsumers = State.Consumers.Count; string when = args != null && args.Length != 0 ? String.Format(fmt, args) : fmt; logger.Info("{0}. Now have total of {1} producers and {2} consumers. All Consumers = {3}, All Producers = {4}", when, numProducers, numConsumers, Utils.EnumerableToString(State.Consumers), Utils.EnumerableToString(State.Producers)); } } // Check that what we have cached locally matches what is in the persistent table. public async Task Validate() { var captureProducers = State.Producers; var captureConsumers = State.Consumers; await ReadStateAsync(); if (captureProducers.Count != State.Producers.Count) { throw new OrleansException( $"State mismatch between PubSubRendezvousGrain and its persistent state. captureProducers.Count={captureProducers.Count}, State.Producers.Count={State.Producers.Count}"); } if (captureProducers.Any(producer => !State.Producers.Contains(producer))) { throw new OrleansException( $"State mismatch between PubSubRendezvousGrain and its persistent state. captureProducers={Utils.EnumerableToString(captureProducers)}, State.Producers={Utils.EnumerableToString(State.Producers)}"); } if (captureConsumers.Count != State.Consumers.Count) { LogPubSubCounts("Validate: Consumer count mismatch"); throw new OrleansException( $"State mismatch between PubSubRendezvousGrain and its persistent state. captureConsumers.Count={captureConsumers.Count}, State.Consumers.Count={State.Consumers.Count}"); } if (captureConsumers.Any(consumer => !State.Consumers.Contains(consumer))) { throw new OrleansException( $"State mismatch between PubSubRendezvousGrain and its persistent state. captureConsumers={Utils.EnumerableToString(captureConsumers)}, State.Consumers={Utils.EnumerableToString(State.Consumers)}"); } } public Task<List<StreamSubscription>> GetAllSubscriptions(StreamId streamId, IStreamConsumerExtension streamConsumer) { if (streamConsumer != null) { var grainRef = streamConsumer as GrainReference; List<StreamSubscription> subscriptions = State.Consumers.Where(c => !c.IsFaulted && c.Consumer.Equals(streamConsumer)) .Select( c => new StreamSubscription(c.SubscriptionId.Guid, streamId.ProviderName, streamId, grainRef.GrainId)).ToList(); return Task.FromResult(subscriptions); } else { List<StreamSubscription> subscriptions = State.Consumers.Where(c => !c.IsFaulted) .Select( c => new StreamSubscription(c.SubscriptionId.Guid, streamId.ProviderName, streamId, c.consumerReference.GrainId)).ToList(); return Task.FromResult(subscriptions); } } public async Task FaultSubscription(GuidId subscriptionId) { PubSubSubscriptionState pubSubState = State.Consumers.FirstOrDefault(s => s.Equals(subscriptionId)); if (pubSubState == null) { return; } try { pubSubState.Fault(); if (logger.IsVerbose) logger.Verbose("Setting subscription {0} to a faulted state.", subscriptionId.Guid); await WriteStateAsync(); await NotifyProducersOfRemovedSubscription(pubSubState.SubscriptionId, pubSubState.Stream); } catch (Exception exc) { logger.Error(ErrorCode.Stream_SetSubscriptionToFaultedFailed, $"Failed to set subscription state to faulted. SubscriptionId {subscriptionId}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } } private async Task NotifyProducersOfRemovedSubscription(GuidId subscriptionId, StreamId streamId) { int numProducersBeforeNotify = State.Producers.Count; if (numProducersBeforeNotify > 0) { if (logger.IsVerbose) logger.Verbose("Notifying {0} existing producers about unregistered consumer.", numProducersBeforeNotify); // Notify producers about unregistered consumer. List<Task> tasks = State.Producers.Where(producerState => IsActiveProducer(producerState.Producer)) .Select(producerState => NotifyProducerOfRemovedSubscriber(producerState, subscriptionId, streamId)) .ToList(); await Task.WhenAll(tasks); //if producers got removed if (State.Producers.Count < numProducersBeforeNotify) await this.WriteStateAsync(); } } private async Task NotifyProducerOfRemovedSubscriber(PubSubPublisherState producer, GuidId subscriptionId, StreamId streamId) { try { await producer.Producer.RemoveSubscriber(subscriptionId, streamId); } catch (GrainExtensionNotInstalledException) { RemoveProducer(producer); } catch (ClientNotAvailableException) { RemoveProducer(producer); } } /// <summary> /// Try clear state will only clear the state if there are no producers or consumers. /// </summary> /// <returns></returns> private async Task<bool> TryClearState() { if (State.Producers.Count == 0 && State.Consumers.Count == 0) // + we already know that numProducers == 0 from previous if-clause { await ClearStateAsync(); //State contains no producers or consumers, remove it from storage return true; } return false; } } }
/* * 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.IO.Compression; using System.Reflection; using System.Threading; using System.Text; using System.Xml; using System.Xml.Linq; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Region.CoreModules.World.Archiver; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { public class InventoryArchiveReadRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The maximum major version of archive that we can read. Minor versions shouldn't need a max number since version /// bumps here should be compatible. /// </summary> public static int MAX_MAJOR_VERSION = 1; protected TarArchiveReader archive; private UserAccount m_userInfo; private string m_invPath; /// <value> /// ID of this request /// </value> protected UUID m_id; /// <summary> /// Do we want to merge this load with existing inventory? /// </summary> protected bool m_merge; protected IInventoryService m_InventoryService; protected IAssetService m_AssetService; protected IUserAccountService m_UserAccountService; private InventoryArchiverModule m_module; /// <value> /// The stream from which the inventory archive will be loaded. /// </value> private Stream m_loadStream; /// <summary> /// Has the control file been loaded for this archive? /// </summary> public bool ControlFileLoaded { get; private set; } /// <summary> /// Do we want to enforce the check. IAR versions before 0.2 and 1.1 do not guarantee this order, so we can't /// enforce. /// </summary> public bool EnforceControlFileCheck { get; private set; } protected bool m_assetsLoaded; protected bool m_inventoryNodesLoaded; protected int m_successfulAssetRestores; protected int m_failedAssetRestores; protected int m_successfulItemRestores; /// <summary> /// Root destination folder for the IAR load. /// </summary> protected InventoryFolderBase m_rootDestinationFolder; /// <summary> /// Inventory nodes loaded from the iar. /// </summary> protected HashSet<InventoryNodeBase> m_loadedNodes = new HashSet<InventoryNodeBase>(); /// <summary> /// In order to load identically named folders, we need to keep track of the folders that we have already /// resolved. /// </summary> Dictionary <string, InventoryFolderBase> m_resolvedFolders = new Dictionary<string, InventoryFolderBase>(); /// <summary> /// Record the creator id that should be associated with an asset. This is used to adjust asset creator ids /// after OSP resolution (since OSP creators are only stored in the item /// </summary> protected Dictionary<UUID, UUID> m_creatorIdForAssetId = new Dictionary<UUID, UUID>(); public InventoryArchiveReadRequest( IInventoryService inv, IAssetService assets, IUserAccountService uacc, UserAccount userInfo, string invPath, string loadPath, bool merge) : this(UUID.Zero, null, inv, assets, uacc, userInfo, invPath, loadPath, merge) { } public InventoryArchiveReadRequest( UUID id, InventoryArchiverModule module, IInventoryService inv, IAssetService assets, IUserAccountService uacc, UserAccount userInfo, string invPath, string loadPath, bool merge) : this( id, module, inv, assets, uacc, userInfo, invPath, new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress), merge) { } public InventoryArchiveReadRequest( UUID id, InventoryArchiverModule module, IInventoryService inv, IAssetService assets, IUserAccountService uacc, UserAccount userInfo, string invPath, Stream loadStream, bool merge) { m_id = id; m_InventoryService = inv; m_AssetService = assets; m_UserAccountService = uacc; m_merge = merge; m_userInfo = userInfo; m_invPath = invPath; m_loadStream = loadStream; m_module = module; // FIXME: Do not perform this check since older versions of OpenSim do save the control file after other things // (I thought they weren't). We will need to bump the version number and perform this check on all // subsequent IAR versions only ControlFileLoaded = true; } /// <summary> /// Execute the request /// </summary> /// <remarks> /// Only call this once. To load another IAR, construct another request object. /// </remarks> /// <returns> /// A list of the inventory nodes loaded. If folders were loaded then only the root folders are /// returned /// </returns> /// <exception cref="System.Exception">Thrown if load fails.</exception> public HashSet<InventoryNodeBase> Execute() { try { Exception reportedException = null; string filePath = "ERROR"; List<InventoryFolderBase> folderCandidates = InventoryArchiveUtils.FindFoldersByPath( m_InventoryService, m_userInfo.PrincipalID, m_invPath); if (folderCandidates.Count == 0) { // Possibly provide an option later on to automatically create this folder if it does not exist m_log.ErrorFormat("[INVENTORY ARCHIVER]: Inventory path {0} does not exist", m_invPath); return m_loadedNodes; } m_rootDestinationFolder = folderCandidates[0]; archive = new TarArchiveReader(m_loadStream); byte[] data; TarArchiveReader.TarEntryType entryType; while ((data = archive.ReadEntry(out filePath, out entryType)) != null) { if (filePath == ArchiveConstants.CONTROL_FILE_PATH) { LoadControlFile(filePath, data); } else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) { LoadAssetFile(filePath, data); } else if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH)) { LoadInventoryFile(filePath, entryType, data); } } archive.Close(); m_log.DebugFormat( "[INVENTORY ARCHIVER]: Successfully loaded {0} assets with {1} failures", m_successfulAssetRestores, m_failedAssetRestores); //Alicia: When this is called by LibraryModule or Tests, m_module will be null as event is not required if(m_module != null) m_module.TriggerInventoryArchiveLoaded(m_id, true, m_userInfo, m_invPath, m_loadStream, reportedException, m_successfulItemRestores); return m_loadedNodes; } catch(Exception Ex) { // Trigger saved event with failed result and exception data if (m_module != null) m_module.TriggerInventoryArchiveLoaded(m_id, false, m_userInfo, m_invPath, m_loadStream, Ex, 0); return m_loadedNodes; } finally { m_loadStream.Close(); } } public void Close() { if (m_loadStream != null) m_loadStream.Close(); } /// <summary> /// Replicate the inventory paths in the archive to the user's inventory as necessary. /// </summary> /// <param name="iarPath">The item archive path to replicate</param> /// <param name="rootDestinationFolder">The root folder for the inventory load</param> /// <param name="resolvedFolders"> /// The folders that we have resolved so far for a given archive path. /// This method will add more folders if necessary /// </param> /// <param name="loadedNodes"> /// Track the inventory nodes created. /// </param> /// <returns>The last user inventory folder created or found for the archive path</returns> public InventoryFolderBase ReplicateArchivePathToUserInventory( string iarPath, InventoryFolderBase rootDestFolder, Dictionary <string, InventoryFolderBase> resolvedFolders, HashSet<InventoryNodeBase> loadedNodes) { string iarPathExisting = iarPath; // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Loading folder {0} {1}", rootDestFolder.Name, rootDestFolder.ID); InventoryFolderBase destFolder = ResolveDestinationFolder(rootDestFolder, ref iarPathExisting, resolvedFolders); // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: originalArchivePath [{0}], section already loaded [{1}]", // iarPath, iarPathExisting); string iarPathToCreate = iarPath.Substring(iarPathExisting.Length); CreateFoldersForPath(destFolder, iarPathExisting, iarPathToCreate, resolvedFolders, loadedNodes); return destFolder; } /// <summary> /// Resolve a destination folder /// </summary> /// /// We require here a root destination folder (usually the root of the user's inventory) and the archive /// path. We also pass in a list of previously resolved folders in case we've found this one previously. /// /// <param name="archivePath"> /// The item archive path to resolve. The portion of the path passed back is that /// which corresponds to the resolved desintation folder. /// <param name="rootDestinationFolder"> /// The root folder for the inventory load /// </param> /// <param name="resolvedFolders"> /// The folders that we have resolved so far for a given archive path. /// </param> /// <returns> /// The folder in the user's inventory that matches best the archive path given. If no such folder was found /// then the passed in root destination folder is returned. /// </returns> protected InventoryFolderBase ResolveDestinationFolder( InventoryFolderBase rootDestFolder, ref string archivePath, Dictionary <string, InventoryFolderBase> resolvedFolders) { // string originalArchivePath = archivePath; while (archivePath.Length > 0) { // m_log.DebugFormat("[INVENTORY ARCHIVER]: Trying to resolve destination folder {0}", archivePath); if (resolvedFolders.ContainsKey(archivePath)) { // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Found previously created folder from archive path {0}", archivePath); return resolvedFolders[archivePath]; } else { if (m_merge) { // TODO: Using m_invPath is totally wrong - what we need to do is strip the uuid from the // iar name and try to find that instead. string plainPath = ArchiveConstants.ExtractPlainPathFromIarPath(archivePath); List<InventoryFolderBase> folderCandidates = InventoryArchiveUtils.FindFoldersByPath( m_InventoryService, m_userInfo.PrincipalID, plainPath); if (folderCandidates.Count != 0) { InventoryFolderBase destFolder = folderCandidates[0]; resolvedFolders[archivePath] = destFolder; return destFolder; } } // Don't include the last slash so find the penultimate one int penultimateSlashIndex = archivePath.LastIndexOf("/", archivePath.Length - 2); if (penultimateSlashIndex >= 0) { // Remove the last section of path so that we can see if we've already resolved the parent archivePath = archivePath.Remove(penultimateSlashIndex + 1); } else { // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Found no previously created folder for archive path {0}", // originalArchivePath); archivePath = string.Empty; return rootDestFolder; } } } return rootDestFolder; } /// <summary> /// Create a set of folders for the given path. /// </summary> /// <param name="destFolder"> /// The root folder from which the creation will take place. /// </param> /// <param name="iarPathExisting"> /// the part of the iar path that already exists /// </param> /// <param name="iarPathToReplicate"> /// The path to replicate in the user's inventory from iar /// </param> /// <param name="resolvedFolders"> /// The folders that we have resolved so far for a given archive path. /// </param> /// <param name="loadedNodes"> /// Track the inventory nodes created. /// </param> protected void CreateFoldersForPath( InventoryFolderBase destFolder, string iarPathExisting, string iarPathToReplicate, Dictionary <string, InventoryFolderBase> resolvedFolders, HashSet<InventoryNodeBase> loadedNodes) { string[] rawDirsToCreate = iarPathToReplicate.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < rawDirsToCreate.Length; i++) { // m_log.DebugFormat("[INVENTORY ARCHIVER]: Creating folder {0} from IAR", rawDirsToCreate[i]); if (!rawDirsToCreate[i].Contains(ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR)) continue; int identicalNameIdentifierIndex = rawDirsToCreate[i].LastIndexOf( ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR); string newFolderName = rawDirsToCreate[i].Remove(identicalNameIdentifierIndex); newFolderName = InventoryArchiveUtils.UnescapeArchivePath(newFolderName); UUID newFolderId = UUID.Random(); // Asset type has to be Unknown here rather than Folder, otherwise the created folder can't be // deleted once the client has relogged. // The root folder appears to be labelled AssetType.Folder (shows up as "Category" in the client) // even though there is a AssetType.RootCategory destFolder = new InventoryFolderBase( newFolderId, newFolderName, m_userInfo.PrincipalID, (short)AssetType.Unknown, destFolder.ID, 1); m_InventoryService.AddFolder(destFolder); // Record that we have now created this folder iarPathExisting += rawDirsToCreate[i] + "/"; m_log.DebugFormat("[INVENTORY ARCHIVER]: Created folder {0} from IAR", iarPathExisting); resolvedFolders[iarPathExisting] = destFolder; if (0 == i) loadedNodes.Add(destFolder); } } /// <summary> /// Load an item from the archive /// </summary> /// <param name="filePath">The archive path for the item</param> /// <param name="data">The raw item data</param> /// <param name="rootDestinationFolder">The root destination folder for loaded items</param> /// <param name="nodesLoaded">All the inventory nodes (items and folders) loaded so far</param> protected InventoryItemBase LoadItem(byte[] data, InventoryFolderBase loadFolder) { InventoryItemBase item = UserInventoryItemSerializer.Deserialize(data); // Don't use the item ID that's in the file item.ID = UUID.Random(); UUID ospResolvedId = OspResolver.ResolveOspa(item.CreatorId, m_UserAccountService); if (UUID.Zero != ospResolvedId) // The user exists in this grid { // m_log.DebugFormat("[INVENTORY ARCHIVER]: Found creator {0} via OSPA resolution", ospResolvedId); // item.CreatorIdAsUuid = ospResolvedId; // Don't preserve the OSPA in the creator id (which actually gets persisted to the // database). Instead, replace with the UUID that we found. item.CreatorId = ospResolvedId.ToString(); item.CreatorData = string.Empty; } else if (string.IsNullOrEmpty(item.CreatorData)) { item.CreatorId = m_userInfo.PrincipalID.ToString(); // item.CreatorIdAsUuid = new UUID(item.CreatorId); } item.Owner = m_userInfo.PrincipalID; // Reset folder ID to the one in which we want to load it item.Folder = loadFolder.ID; // Record the creator id for the item's asset so that we can use it later, if necessary, when the asset // is loaded. // FIXME: This relies on the items coming before the assets in the TAR file. Need to create stronger // checks for this, and maybe even an external tool for creating OARs which enforces this, rather than // relying on native tar tools. m_creatorIdForAssetId[item.AssetID] = item.CreatorIdAsUuid; if (!m_InventoryService.AddItem(item)) m_log.WarnFormat("[INVENTORY ARCHIVER]: Unable to save item {0} in folder {1}", item.Name, item.Folder); return item; } /// <summary> /// Load an asset /// </summary> /// <param name="assetFilename"></param> /// <param name="data"></param> /// <returns>true if asset was successfully loaded, false otherwise</returns> private bool LoadAsset(string assetPath, byte[] data) { //IRegionSerialiser serialiser = scene.RequestModuleInterface<IRegionSerialiser>(); // Right now we're nastily obtaining the UUID from the filename string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length); int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR); if (i == -1) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping", assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR); return false; } string extension = filename.Substring(i); string rawUuid = filename.Remove(filename.Length - extension.Length); UUID assetId = new UUID(rawUuid); if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension)) { sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension]; if (assetType == (sbyte)AssetType.Unknown) { m_log.WarnFormat("[INVENTORY ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, assetId); } else if (assetType == (sbyte)AssetType.Object) { if (m_creatorIdForAssetId.ContainsKey(assetId)) { data = SceneObjectSerializer.ModifySerializedObject(assetId, data, sog => { bool modified = false; foreach (SceneObjectPart sop in sog.Parts) { if (string.IsNullOrEmpty(sop.CreatorData)) { sop.CreatorID = m_creatorIdForAssetId[assetId]; modified = true; } } return modified; }); if (data == null) return false; } } //m_log.DebugFormat("[INVENTORY ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType); AssetBase asset = new AssetBase(assetId, "From IAR", assetType, UUID.Zero.ToString()); asset.Data = data; m_AssetService.Store(asset); return true; } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}", assetPath, extension); return false; } } /// <summary> /// Load control file /// </summary> /// <param name="path"></param> /// <param name="data"></param> public void LoadControlFile(string path, byte[] data) { XDocument doc = XDocument.Parse(Encoding.ASCII.GetString(data)); XElement archiveElement = doc.Element("archive"); int majorVersion = int.Parse(archiveElement.Attribute("major_version").Value); int minorVersion = int.Parse(archiveElement.Attribute("minor_version").Value); string version = string.Format("{0}.{1}", majorVersion, minorVersion); if (majorVersion > MAX_MAJOR_VERSION) { throw new Exception( string.Format( "The IAR you are trying to load has major version number of {0} but this version of OpenSim can only load IARs with major version number {1} and below", majorVersion, MAX_MAJOR_VERSION)); } ControlFileLoaded = true; m_log.InfoFormat("[INVENTORY ARCHIVER]: Loading IAR with version {0}", version); } /// <summary> /// Load inventory file /// </summary> /// <param name="path"></param> /// <param name="entryType"></param> /// <param name="data"></param> protected void LoadInventoryFile(string path, TarArchiveReader.TarEntryType entryType, byte[] data) { if (!ControlFileLoaded) throw new Exception( string.Format( "The IAR you are trying to load does not list {0} before {1}. Aborting load", ArchiveConstants.CONTROL_FILE_PATH, ArchiveConstants.INVENTORY_PATH)); if (m_assetsLoaded) throw new Exception( string.Format( "The IAR you are trying to load does not list all {0} before {1}. Aborting load", ArchiveConstants.INVENTORY_PATH, ArchiveConstants.ASSETS_PATH)); path = path.Substring(ArchiveConstants.INVENTORY_PATH.Length); // Trim off the file portion if we aren't already dealing with a directory path if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType) path = path.Remove(path.LastIndexOf("/") + 1); InventoryFolderBase foundFolder = ReplicateArchivePathToUserInventory( path, m_rootDestinationFolder, m_resolvedFolders, m_loadedNodes); if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType) { InventoryItemBase item = LoadItem(data, foundFolder); if (item != null) { m_successfulItemRestores++; // If we aren't loading the folder containing the item then well need to update the // viewer separately for that item. if (!m_loadedNodes.Contains(foundFolder)) m_loadedNodes.Add(item); } } m_inventoryNodesLoaded = true; } /// <summary> /// Load asset file /// </summary> /// <param name="path"></param> /// <param name="data"></param> protected void LoadAssetFile(string path, byte[] data) { if (!ControlFileLoaded) throw new Exception( string.Format( "The IAR you are trying to load does not list {0} before {1}. Aborting load", ArchiveConstants.CONTROL_FILE_PATH, ArchiveConstants.ASSETS_PATH)); if (!m_inventoryNodesLoaded) throw new Exception( string.Format( "The IAR you are trying to load does not list all {0} before {1}. Aborting load", ArchiveConstants.INVENTORY_PATH, ArchiveConstants.ASSETS_PATH)); if (LoadAsset(path, data)) m_successfulAssetRestores++; else m_failedAssetRestores++; if ((m_successfulAssetRestores) % 50 == 0) m_log.DebugFormat( "[INVENTORY ARCHIVER]: Loaded {0} assets...", m_successfulAssetRestores); m_assetsLoaded = true; } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim 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.Linq; using System.Net; using System.Reflection; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenMetaverse; using OpenMetaverse.StructuredData; using Nini.Config; namespace Aurora.Modules.EntityTransfer { public class EntityTransferModule : ISharedRegionModule, IEntityTransferModule { #region Declares protected bool m_Enabled = false; protected List<IScene> m_scenes = new List<IScene> (); private readonly Dictionary<IScene, Dictionary<UUID, AgentData>> m_incomingChildAgentData = new Dictionary<IScene, Dictionary<UUID, AgentData>> (); #endregion #region ISharedRegionModule public Type ReplaceableInterface { get { return null; } } public virtual string Name { get { return "BasicEntityTransferModule"; } } public virtual void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("EntityTransferModule", ""); if (name == Name) { m_Enabled = true; //MainConsole.Instance.InfoFormat("[ENTITY TRANSFER MODULE]: {0} enabled.", Name); } } } public virtual void PostInitialise() { } public virtual void AddRegion (IScene scene) { if (!m_Enabled) return; m_scenes.Add(scene); scene.RegisterModuleInterface<IEntityTransferModule>(this); scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnNewPresence += EventManager_OnNewPresence; scene.EventManager.OnClosingClient += OnClosingClient; } void EventManager_OnNewPresence (IScenePresence sp) { lock (m_incomingChildAgentData) { Dictionary<UUID, AgentData> childAgentUpdates; if (m_incomingChildAgentData.TryGetValue (sp.Scene, out childAgentUpdates)) { if (childAgentUpdates.ContainsKey (sp.UUID)) { //Found info, update the agent then remove it sp.ChildAgentDataUpdate (childAgentUpdates[sp.UUID]); childAgentUpdates.Remove (sp.UUID); m_incomingChildAgentData[sp.Scene] = childAgentUpdates; } } } } public virtual void Close() { } public virtual void RemoveRegion (IScene scene) { if (!m_Enabled) return; m_scenes.Remove(scene); scene.UnregisterModuleInterface<IEntityTransferModule>(this); scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnNewPresence -= EventManager_OnNewPresence; scene.EventManager.OnClosingClient -= OnClosingClient; } public virtual void RegionLoaded (IScene scene) { } #endregion #region Agent Teleports public virtual void Teleport(IScenePresence sp, ulong regionHandle, Vector3 position, Vector3 lookAt, uint teleportFlags) { int x = 0, y = 0; Util.UlongToInts(regionHandle, out x, out y); GridRegion reg = sp.Scene.GridService.GetRegionByPosition (sp.Scene.RegionInfo.ScopeID, x, y); if (reg == null) { List<GridRegion> regions = sp.Scene.GridService.GetRegionRange(sp.Scene.RegionInfo.ScopeID, x - (sp.Scene.GridService.GetRegionViewSize() * sp.Scene.RegionInfo.RegionSizeX), x + (sp.Scene.GridService.GetRegionViewSize() * sp.Scene.RegionInfo.RegionSizeX), y - (sp.Scene.GridService.GetRegionViewSize() * sp.Scene.RegionInfo.RegionSizeY), y + (sp.Scene.GridService.GetRegionViewSize() * sp.Scene.RegionInfo.RegionSizeY)); foreach (GridRegion r in regions) { if (r.RegionLocX <= x && r.RegionLocX + r.RegionSizeX > x && r.RegionLocY <= y && r.RegionLocY + r.RegionSizeY > y) { reg = r; position.X += x - reg.RegionLocX; position.Y += y - reg.RegionLocY; break; } } if (reg == null) { // TP to a place that doesn't exist (anymore) // Inform the viewer about that sp.ControllingClient.SendTeleportFailed ("The region you tried to teleport to doesn't exist anymore"); // and set the map-tile to '(Offline)' int regX, regY; Util.UlongToInts (regionHandle, out regX, out regY); MapBlockData block = new MapBlockData { X = (ushort) (regX/Constants.RegionSize), Y = (ushort) (regY/Constants.RegionSize), Access = 254 }; // == not there List<MapBlockData> blocks = new List<MapBlockData> {block}; sp.ControllingClient.SendMapBlock (blocks, 0); return; } } Teleport(sp, reg, position, lookAt, teleportFlags); } public virtual void Teleport(IScenePresence sp, GridRegion finalDestination, Vector3 position, Vector3 lookAt, uint teleportFlags) { sp.ControllingClient.SendTeleportStart(teleportFlags); sp.ControllingClient.SendTeleportProgress(teleportFlags, "requesting"); // Reset animations; the viewer does that in teleports. if(sp.Animator != null) sp.Animator.ResetAnimations(); try { string reason = ""; if (finalDestination.RegionHandle == sp.Scene.RegionInfo.RegionHandle) { //First check whether the user is allowed to move at all if (!sp.Scene.Permissions.AllowedOutgoingLocalTeleport(sp.UUID, out reason)) { sp.ControllingClient.SendTeleportFailed(reason); return; } //Now respect things like parcel bans with this if (!sp.Scene.Permissions.AllowedIncomingTeleport(sp.UUID, position, teleportFlags, out position, out reason)) { sp.ControllingClient.SendTeleportFailed(reason); return; } MainConsole.Instance.DebugFormat( "[ENTITY TRANSFER MODULE]: RequestTeleportToLocation {0} within {1}", position, sp.Scene.RegionInfo.RegionName); sp.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags); sp.Teleport(position); } else // Another region possibly in another simulator { // Make sure the user is allowed to leave this region if (!sp.Scene.Permissions.AllowedOutgoingRemoteTeleport(sp.UUID, out reason)) { sp.ControllingClient.SendTeleportFailed(reason); return; } //MainConsole.Instance.DebugFormat("[ENTITY TRANSFER MODULE]: Final destination is x={0} y={1} uuid={2}", // finalDestination.RegionLocX / Constants.RegionSize, finalDestination.RegionLocY / Constants.RegionSize, finalDestination.RegionID); // Check that these are not the same coordinates if (finalDestination.RegionLocX == sp.Scene.RegionInfo.RegionLocX && finalDestination.RegionLocY == sp.Scene.RegionInfo.RegionLocY) { // Can't do. Viewer crashes sp.ControllingClient.SendTeleportFailed("Space warp! You would crash. Move to a different region and try again."); return; } // // This is it // DoTeleport(sp, finalDestination, position, lookAt, teleportFlags); // // // } } catch (Exception e) { MainConsole.Instance.ErrorFormat("[ENTITY TRANSFER MODULE]: Exception on teleport: {0}\n{1}", e.Message, e.StackTrace); sp.ControllingClient.SendTeleportFailed("Internal error"); } } public virtual void DoTeleport(IScenePresence sp, GridRegion finalDestination, Vector3 position, Vector3 lookAt, uint teleportFlags) { sp.ControllingClient.SendTeleportProgress(teleportFlags, "sending_dest"); if (finalDestination == null) { sp.ControllingClient.SendTeleportFailed("Unable to locate destination"); return; } MainConsole.Instance.DebugFormat( "[ENTITY TRANSFER MODULE]: Request Teleport to {0}:{1}/{2}", finalDestination.ServerURI, finalDestination.RegionName, position); sp.ControllingClient.SendTeleportProgress(teleportFlags, "arriving"); sp.SetAgentLeaving(finalDestination); // Fixing a bug where teleporting while sitting results in the avatar ending up removed from // both regions if (sp.ParentID != UUID.Zero) sp.StandUp(); AgentCircuitData agentCircuit = BuildCircuitDataForPresence(sp, position); AgentData agent = new AgentData(); sp.CopyTo(agent); //Fix the position agent.Position = position; IEventQueueService eq = sp.Scene.RequestModuleInterface<IEventQueueService>(); if (eq != null) { ISyncMessagePosterService syncPoster = sp.Scene.RequestModuleInterface<ISyncMessagePosterService>(); if (syncPoster != null) { //This does CreateAgent and sends the EnableSimulator/EstablishAgentCommunication/TeleportFinish // messages if they need to be called and deals with the callback OSDMap map = syncPoster.Get(SyncMessageHelper.TeleportAgent((int)sp.DrawDistance, agentCircuit, agent, teleportFlags, finalDestination, sp.Scene.RegionInfo.RegionHandle), sp.UUID, sp.Scene.RegionInfo.RegionHandle); bool result = false; if(map != null) result = map["Success"].AsBoolean(); if (!result) { // Fix the agent status sp.IsChildAgent = false; //Tell modules about it sp.AgentFailedToLeave(); sp.ControllingClient.SendTeleportFailed(map != null ? map["Reason"].AsString() : "Teleport Failed"); return; } //Get the new destintation, it may have changed if(map.ContainsKey("Destination")) { finalDestination = new GridRegion(); finalDestination.FromOSD((OSDMap)map["Destination"]); } } } MakeChildAgent(sp, finalDestination, false); } private AgentCircuitData BuildCircuitDataForPresence(IScenePresence sp, Vector3 position) { AgentCircuitData agentCircuit = sp.ControllingClient.RequestClientInfo(); agentCircuit.startpos = position; //The agent will be a root agent agentCircuit.child = false; //Make sure the appearnace is right IAvatarAppearanceModule appearance = sp.RequestModuleInterface<IAvatarAppearanceModule>(); if (appearance != null && appearance.Appearance != null) agentCircuit.Appearance = appearance.Appearance; else MainConsole.Instance.Error("[EntityTransferModule]: No appearance is being packed as we could not find the appearance ? " + appearance == null); AgentCircuitData oldCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.UUID); agentCircuit.ServiceURLs = oldCircuit.ServiceURLs; agentCircuit.firstname = oldCircuit.firstname; agentCircuit.lastname = oldCircuit.lastname; agentCircuit.ServiceSessionID = oldCircuit.ServiceSessionID; return agentCircuit; } public void MakeChildAgent (IScenePresence sp, GridRegion finalDestination, bool markAgentAsLeaving) { if(sp == null) return; if(markAgentAsLeaving) sp.SetAgentLeaving(null); sp.Scene.AuroraEventManager.FireGenericEventHandler("SendingAttachments", new object[] { finalDestination, sp }); //Kill the groups here, otherwise they will become ghost attachments // and stay in the sim, they'll get readded below into the new sim //KillAttachments(sp); // Well, this is it. The agent is over there. KillEntity(sp.Scene, sp); //Make it a child agent for now... the grid will kill us later if we need to close sp.MakeChildAgent(finalDestination); } protected void KillEntity (IScene scene, IEntity entity) { scene.ForEachClient(delegate(IClientAPI client) { if(client.AgentId != entity.UUID) client.SendKillObject (scene.RegionInfo.RegionHandle, new[] { entity }); }); } protected void KillEntities (IScenePresence sp, IEntity[] grp) { sp.Scene.ForEachClient(delegate(IClientAPI client) { if(sp.UUID != client.AgentId)//Don't send kill requests to us, it'll just look jerky client.SendKillObject(sp.Scene.RegionInfo.RegionHandle, grp); }); } #endregion #region Client Events protected virtual void OnNewClient(IClientAPI client) { client.OnTeleportHomeRequest += ClientTeleportHome; client.OnTeleportCancel += RequestTeleportCancel; client.OnTeleportLocationRequest += RequestTeleportLocation; client.OnTeleportLandmarkRequest += RequestTeleportLandmark; } protected virtual void OnClosingClient(IClientAPI client) { client.OnTeleportHomeRequest -= ClientTeleportHome; client.OnTeleportCancel -= RequestTeleportCancel; client.OnTeleportLocationRequest -= RequestTeleportLocation; client.OnTeleportLandmarkRequest -= RequestTeleportLandmark; } public void RequestTeleportCancel(IClientAPI client) { CancelTeleport(client.AgentId, client.Scene.RegionInfo.RegionHandle); } /// <summary> /// Tries to teleport agent to other region. /// </summary> /// <param name="remoteClient"></param> /// <param name="regionName"></param> /// <param name="position"></param> /// <param name="lookat"></param> /// <param name="teleportFlags"></param> public void RequestTeleportLocation(IClientAPI remoteClient, string regionName, Vector3 position, Vector3 lookat, uint teleportFlags) { GridRegion regionInfo = remoteClient.Scene.RequestModuleInterface<IGridService>().GetRegionByName(UUID.Zero, regionName); if (regionInfo == null) { // can't find the region: Tell viewer and abort remoteClient.SendTeleportFailed("The region '" + regionName + "' could not be found."); return; } RequestTeleportLocation(remoteClient, regionInfo, position, lookat, teleportFlags); } /// <summary> /// Tries to teleport agent to other region. /// </summary> /// <param name="remoteClient"></param> /// <param name="regionHandle"></param> /// <param name="position"></param> /// <param name="lookAt"></param> /// <param name="teleportFlags"></param> public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint teleportFlags) { IScenePresence sp = remoteClient.Scene.GetScenePresence(remoteClient.AgentId); if (sp != null) { Teleport(sp, regionHandle, position, lookAt, teleportFlags); } } /// <summary> /// Tries to teleport agent to other region. /// </summary> /// <param name="remoteClient"></param> /// <param name="reg"></param> /// <param name="position"></param> /// <param name="lookAt"></param> /// <param name="teleportFlags"></param> public void RequestTeleportLocation(IClientAPI remoteClient, GridRegion reg, Vector3 position, Vector3 lookAt, uint teleportFlags) { IScenePresence sp = remoteClient.Scene.GetScenePresence(remoteClient.AgentId); if (sp != null) { Teleport(sp, reg, position, lookAt, teleportFlags); } } /// <summary> /// Tries to teleport agent to landmark. /// </summary> /// <param name="remoteClient"></param> /// <param name="gatekeeperURL"></param> /// <param name="position"></param> /// <param name="regionID"></param> public void RequestTeleportLandmark (IClientAPI remoteClient, UUID regionID, string gatekeeperURL, Vector3 position) { GridRegion info = null; try { info = remoteClient.Scene.RequestModuleInterface<IGridService>().GetRegionByUUID(UUID.Zero, regionID); } catch( Exception ex) { MainConsole.Instance.Warn("[EntityTransferModule]: Error finding landmark's region for user " + remoteClient.Name + ", " + ex); } if (info == null) { if (!string.IsNullOrEmpty(gatekeeperURL)) { info = new GridRegion { ServerURI = gatekeeperURL, RegionID = regionID, Flags = (int) (Aurora.Framework.RegionFlags.Foreign | Aurora.Framework.RegionFlags.Hyperlink) }; } else { // can't find the region: Tell viewer and abort remoteClient.SendTeleportFailed ("The teleport destination could not be found."); return; } } RequestTeleportLocation(remoteClient, info, position, Vector3.Zero, (uint)(TeleportFlags.SetLastToTarget | TeleportFlags.ViaLandmark)); } #endregion #region Teleport Home public void ClientTeleportHome (UUID id, IClientAPI client) { TeleportHome(id, client); } public virtual bool TeleportHome(UUID id, IClientAPI client) { //MainConsole.Instance.DebugFormat("[ENTITY TRANSFER MODULE]: Request to teleport {0} {1} home", client.FirstName, client.LastName); //OpenSim.Services.Interfaces.PresenceInfo pinfo = m_aScene.PresenceService.GetAgent(client.SessionId); UserInfo uinfo = client.Scene.RequestModuleInterface<IAgentInfoService>().GetUserInfo(client.AgentId.ToString()); IUserAgentService uas = client.Scene.RequestModuleInterface<IUserAgentService> (); if (uinfo != null) { GridRegion regionInfo = client.Scene.GridService.GetRegionByUUID(UUID.Zero, uinfo.HomeRegionID); if (regionInfo == null) { Vector3 position = Vector3.Zero, lookAt = Vector3.Zero; if (uas != null) regionInfo = uas.GetHomeRegion(client.Scene.AuthenticateHandler.GetAgentCircuitData(client.AgentId), out position, out lookAt); if (regionInfo == null) { //can't find the Home region: Tell viewer and abort client.SendTeleportFailed ("Your home region could not be found."); return false; } } MainConsole.Instance.DebugFormat("[ENTITY TRANSFER MODULE]: User's home region is {0} {1} ({2}-{3})", regionInfo.RegionName, regionInfo.RegionID, regionInfo.RegionLocX / Constants.RegionSize, regionInfo.RegionLocY / Constants.RegionSize); RequestTeleportLocation( client, regionInfo, uinfo.HomePosition, uinfo.HomeLookAt, (uint)(TeleportFlags.SetLastToTarget | TeleportFlags.ViaHome)); } else { //Default region time... List<GridRegion> Regions = client.Scene.GridService.GetDefaultRegions(UUID.Zero); if(Regions.Count != 0) { MainConsole.Instance.DebugFormat("[ENTITY TRANSFER MODULE]: User's home region was not found, using {0} {1} ({2}-{3})", Regions[0].RegionName, Regions[0].RegionID, Regions[0].RegionLocX / Constants.RegionSize, Regions[0].RegionLocY / Constants.RegionSize); RequestTeleportLocation( client, Regions[0], new Vector3(128, 128, 25), new Vector3(128, 128, 128), (uint)(TeleportFlags.SetLastToTarget | TeleportFlags.ViaHome)); } else return false; } return true; } #endregion #region Agent Crossings public virtual void Cross(IScenePresence agent, bool isFlying, GridRegion crossingRegion) { if(agent.PhysicsActor != null) agent.PhysicsActor.IsPhysical = false; CrossAgentToNewRegionAsyncUtil (agent, isFlying, crossingRegion); } private void CrossAgentToNewRegionAsyncUtil (IScenePresence agent, bool isFlying, GridRegion crossingRegion) { Vector3 newposition = new Vector3 (agent.AbsolutePosition.X, agent.AbsolutePosition.Y, agent.AbsolutePosition.Z); #if (!ISWIN) Util.FireAndForget(delegate(object o) { CrossAgentToNewRegionAsync(agent, newposition, crossingRegion, isFlying, false); }); #else Util.FireAndForget (o => CrossAgentToNewRegionAsync(agent, newposition, crossingRegion, isFlying, false)); #endif } /// <summary> /// This Closes child agents on neighboring regions /// Calls an asynchronous method to do so.. so it doesn't lag the sim. /// </summary> protected IScenePresence CrossAgentToNewRegionAsync(IScenePresence agent, Vector3 pos, GridRegion crossingRegion, bool isFlying, bool positionIsAlreadyFixed) { MainConsole.Instance.DebugFormat("[EntityTransferModule]: Crossing agent {0} to region {1}", agent.Name, crossingRegion.RegionName); IScene m_scene = agent.Scene; try { if (!positionIsAlreadyFixed) { pos.X = (m_scene.RegionInfo.RegionLocX + pos.X) - crossingRegion.RegionLocX; pos.Y = (m_scene.RegionInfo.RegionLocY + pos.Y) - crossingRegion.RegionLocY; //Make sure that they are within bounds (velocity can push it out of bounds) if (pos.X < 0) pos.X = 1; if (pos.Y < 0) pos.Y = 1; if (pos.X > crossingRegion.RegionSizeX) pos.X = crossingRegion.RegionSizeX - 1; if (pos.Y > crossingRegion.RegionSizeY) pos.Y = crossingRegion.RegionSizeY - 1; } agent.SetAgentLeaving(crossingRegion); AgentData cAgent = new AgentData(); agent.CopyTo(cAgent); cAgent.Position = pos; if (isFlying) cAgent.ControlFlags |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY; AgentCircuitData agentCircuit = BuildCircuitDataForPresence(agent, pos); agentCircuit.teleportFlags = (uint)TeleportFlags.ViaRegionID; IEventQueueService eq = agent.Scene.RequestModuleInterface<IEventQueueService>(); if (eq != null) { //This does UpdateAgent and closing of child agents // messages if they need to be called ISyncMessagePosterService syncPoster = agent.Scene.RequestModuleInterface<ISyncMessagePosterService>(); if (syncPoster != null) { OSDMap map = syncPoster.Get(SyncMessageHelper.CrossAgent(crossingRegion, pos, agent.Velocity, agentCircuit, cAgent, agent.Scene.RegionInfo.RegionHandle), agent.UUID, agent.Scene.RegionInfo.RegionHandle); bool result = false; if (map != null) result = map["Success"].AsBoolean(); if (!result) { //Tell modules that we have failed agent.AgentFailedToLeave(); if (map != null) { if (map.ContainsKey("Note") && !map["Note"].AsBoolean()) return agent; agent.ControllingClient.SendTeleportFailed(map["Reason"].AsString()); } else agent.ControllingClient.SendTeleportFailed("TP Failed"); if (agent.PhysicsActor != null) agent.PhysicsActor.IsPhysical = true; //Fix the setting that we set earlier // In any case agent.FailedCrossingTransit(crossingRegion); return agent; } } } //We're killing the animator and the physics actor, so we don't need to worry about agent.PhysicsActor.IsPhysical agent.MakeChildAgent(crossingRegion); //Revolution- We already were in this region... we don't need updates about the avatars we already know about, right? // OLD: now we have a child agent in this region. Request and send all interesting data about (root) agents in the sim //agent.SendOtherAgentsAvatarDataToMe(); //agent.SendOtherAgentsAppearanceToMe(); //Kill the groups here, otherwise they will become ghost attachments // and stay in the sim, they'll get readded below into the new sim //KillAttachments(agent); } catch(Exception ex) { MainConsole.Instance.Warn("[EntityTransferModule]: Exception in crossing: " + ex); } // In any case agent.SuccessfulCrossingTransit(crossingRegion); return agent; } private void KillAttachments(IScenePresence agent) { IAttachmentsModule attModule = agent.Scene.RequestModuleInterface<IAttachmentsModule>(); if (attModule != null) { ISceneEntity[] attachments = attModule.GetAttachmentsForAvatar (agent.UUID); foreach (ISceneEntity grp in attachments) { //Kill in all clients as it will be readded in the other region KillEntities(agent, grp.ChildrenEntities().ToArray()); //Now remove it from the Scene so that it will not come back agent.Scene.SceneGraph.DeleteEntity(grp); } } } #endregion #region Object Transfers /// <summary> /// Move the given scene object into a new region depending on which region its absolute position has moved /// into. /// /// This method locates the new region handle and offsets the prim position for the new region /// </summary> /// <param name="attemptedPosition">the attempted out of region position of the scene object</param> /// <param name="grp">the scene object that we're crossing</param> ///<param name="destination"></param> public bool CrossGroupToNewRegion(SceneObjectGroup grp, Vector3 attemptedPosition, GridRegion destination) { if (grp == null) return false; if (grp.IsDeleted) return false; if (grp.Scene == null) return false; if (grp.RootPart.DIE_AT_EDGE) { // We remove the object here try { IBackupModule backup = grp.Scene.RequestModuleInterface<IBackupModule>(); if (backup != null) return backup.DeleteSceneObjects(new[] { grp }, true, true); } catch (Exception) { MainConsole.Instance.Warn("[DATABASE]: exception when trying to remove the prim that crossed the border."); } return false; } if (grp.RootPart.RETURN_AT_EDGE) { // We remove the object here try { List<ISceneEntity> objects = new List<ISceneEntity> { grp }; ILLClientInventory inventoryModule = grp.Scene.RequestModuleInterface<ILLClientInventory>(); if (inventoryModule != null) return inventoryModule.ReturnObjects(objects.ToArray(), UUID.Zero); } catch (Exception) { MainConsole.Instance.Warn("[SCENE]: exception when trying to return the prim that crossed the border."); } return false; } Vector3 oldGroupPosition = grp.RootPart.GroupPosition; // If we fail to cross the border, then reset the position of the scene object on that border. if (destination != null && !CrossPrimGroupIntoNewRegion(destination, grp, attemptedPosition)) { grp.OffsetForNewRegion(oldGroupPosition); grp.ScheduleGroupUpdate (PrimUpdateFlags.ForcedFullUpdate); return false; } return true; } /// <summary> /// Move the given scene object into a new region /// </summary> /// <param name="destination"></param> /// <param name="grp">Scene Object Group that we're crossing</param> /// <param name="attemptedPos"></param> /// <returns> /// true if the crossing itself was successful, false on failure /// </returns> protected bool CrossPrimGroupIntoNewRegion(GridRegion destination, SceneObjectGroup grp, Vector3 attemptedPos) { bool successYN = false; if (destination != null) { if(grp.SitTargetAvatar.Count != 0) { bool success = false; lock(grp.SitTargetAvatar) { foreach(UUID avID in grp.SitTargetAvatar) { IScenePresence SP = grp.Scene.GetScenePresence(avID); SP.Velocity = grp.RootChild.PhysActor.Velocity; SP = CrossAgentToNewRegionAsync(SP, attemptedPos, destination, false, true); success = SP.IsChildAgent; } } if(success) { foreach(ISceneChildEntity part in grp.ChildrenEntities()) part.SitTargetAvatar.Clear(); grp.SitTargetAvatar.Clear(); IBackupModule backup = grp.Scene.RequestModuleInterface<IBackupModule>(); if(backup != null) return backup.DeleteSceneObjects(new[] { grp }, false, false); return true;//They do all the work adding the prim in the other region } return false; } SceneObjectGroup copiedGroup = (SceneObjectGroup)grp.Copy(false); copiedGroup.SetAbsolutePosition(true, attemptedPos); if (grp.Scene != null && grp.Scene.SimulationService != null) successYN = grp.Scene.SimulationService.CreateObject(destination, copiedGroup); if (successYN) { // We remove the object here try { foreach (ISceneChildEntity part in grp.ChildrenEntities()) part.SitTargetAvatar.Clear(); grp.SitTargetAvatar.Clear(); IBackupModule backup = grp.Scene.RequestModuleInterface<IBackupModule>(); if (backup != null) return backup.DeleteSceneObjects(new[] { grp }, false, true); } catch (Exception e) { MainConsole.Instance.ErrorFormat( "[ENTITY TRANSFER MODULE]: Exception deleting the old object left behind on a border crossing for {0}, {1}", grp, e); } } else { if (!grp.IsDeleted) { if (grp.RootPart.PhysActor != null) { grp.RootPart.PhysActor.CrossingFailure(); } } MainConsole.Instance.ErrorFormat("[ENTITY TRANSFER MODULE]: Prim crossing failed for {0}", grp); } } else { MainConsole.Instance.Error("[ENTITY TRANSFER MODULE]: destination was unexpectedly null in Scene.CrossPrimGroupIntoNewRegion()"); } return successYN; } #endregion #region Incoming Object Transfers /// <summary> /// Attachment rezzing /// </summary> /// <param name="regionID"></param> /// <param name="userID">Agent Unique ID</param> /// <param name="itemID">Inventory Item ID to rez</param> /// <returns>False</returns> public virtual bool IncomingCreateObject(UUID regionID, UUID userID, UUID itemID) { /*//MainConsole.Instance.DebugFormat(" >>> IncomingCreateObject(userID, itemID) <<< {0} {1}", userID, itemID); Scene scene = GetScene(regionID); if (scene == null) return false; ScenePresence sp = scene.GetScenePresence(userID); IAttachmentsModule attachMod = scene.RequestModuleInterface<IAttachmentsModule>(); if (sp != null && attachMod != null) { MainConsole.Instance.DebugFormat( "[EntityTransferModule]: Received attachment via new attachment method {0} for agent {1}", itemID, sp.Name); int attPt = sp.Appearance.GetAttachpoint(itemID); attachMod.RezSingleAttachmentFromInventory(sp.ControllingClient, itemID, attPt, true); return true; }*/ return false; } /// <summary> /// Called when objects or attachments cross the border, or teleport, between regions. /// </summary> /// <param name="regionID"></param> /// <param name="sog"></param> /// <returns></returns> public virtual bool IncomingCreateObject(UUID regionID, ISceneObject sog) { IScene scene = GetScene(regionID); if (scene == null) return false; //MainConsole.Instance.Debug(" >>> IncomingCreateObject(sog) <<< " + ((SceneObjectGroup)sog).AbsolutePosition + " deleted? " + ((SceneObjectGroup)sog).IsDeleted); SceneObjectGroup newObject; try { newObject = (SceneObjectGroup)sog; } catch (Exception e) { MainConsole.Instance.WarnFormat("[EntityTransferModule]: Problem casting object: {0}", e.Message); return false; } if (!AddSceneObject(scene, newObject)) { MainConsole.Instance.WarnFormat("[EntityTransferModule]: Problem adding scene object {0} in {1} ", sog.UUID, scene.RegionInfo.RegionName); return false; } newObject.RootPart.ParentGroup.CreateScriptInstances(0, false, StateSource.PrimCrossing, UUID.Zero); return true; } /// <summary> /// Adds a Scene Object group to the Scene. /// Verifies that the creator of the object is not banned from the simulator. /// Checks if the item is an Attachment /// </summary> /// <param name="scene"></param> /// <param name="sceneObject"></param> /// <returns>True if the SceneObjectGroup was added, False if it was not</returns> public bool AddSceneObject(IScene scene, SceneObjectGroup sceneObject) { // If the user is banned, we won't let any of their objects // enter. Period. // if (scene.RegionInfo.EstateSettings.IsBanned(sceneObject.OwnerID)) { MainConsole.Instance.Info("[EntityTransferModule]: Denied prim crossing for banned avatar"); return false; } if (!sceneObject.IsAttachmentCheckFull()) // Not Attachment { if (!scene.Permissions.CanObjectEntry(sceneObject.UUID, true, sceneObject.AbsolutePosition, sceneObject.OwnerID)) { // Deny non attachments based on parcel settings // MainConsole.Instance.Info("[EntityTransferModule]: Denied prim crossing " + "because of parcel settings"); IBackupModule backup = scene.RequestModuleInterface<IBackupModule>(); if (backup != null) backup.DeleteSceneObjects(new[] { sceneObject }, true, true); return false; } if (scene.SceneGraph.AddPrimToScene(sceneObject)) { if(sceneObject.RootPart.IsSelected) sceneObject.RootPart.CreateSelected = true; sceneObject.ScheduleGroupUpdate (PrimUpdateFlags.ForcedFullUpdate); return true; } } return false; } #endregion #region Misc public void CancelTeleport(UUID AgentID, ulong RegionHandle) { ISyncMessagePosterService syncPoster = m_scenes[0].RequestModuleInterface<ISyncMessagePosterService>(); if (syncPoster != null) { syncPoster.Post(SyncMessageHelper.CancelTeleport(AgentID, RegionHandle), RegionHandle); } } /// <summary> /// This 'can' return null, so be careful /// </summary> /// <param name="RegionID"></param> /// <returns></returns> public IScene GetScene(UUID RegionID) { #if (!ISWIN) foreach (IScene scene in m_scenes) { if (scene.RegionInfo.RegionID == RegionID) return scene; } return null; #else return m_scenes.FirstOrDefault(scene => scene.RegionInfo.RegionID == RegionID); #endif } #endregion #region RegionComms /// <summary> /// Do the work necessary to initiate a new user connection for a particular scene. /// At the moment, this consists of setting up the caps infrastructure /// The return bool should allow for connections to be refused, but as not all calling paths /// take proper notice of it let, we allowed banned users in still. /// </summary> /// <param name="scene"></param> /// <param name="agent">CircuitData of the agent who is connecting</param> /// <param name="UDPPort"></param> /// <param name="reason">Outputs the reason for the false response on this string, /// If the agent was accepted, this will be the Caps SEED for the region</param> /// <param name="teleportFlags"></param> /// <returns>True if the region accepts this agent. False if it does not. False will /// also return a reason.</returns> public bool NewUserConnection (IScene scene, AgentCircuitData agent, uint teleportFlags, out int UDPPort, out string reason) { reason = String.Empty; UDPPort = GetUDPPort(scene); IScenePresence sp = scene.GetScenePresence(agent.AgentID); // Don't disable this log message - it's too helpful MainConsole.Instance.TraceFormat ( "[ConnectionBegin]: Region {0} told of incoming {1} agent {2} (circuit code {3}, teleportflags {4})", scene.RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.AgentID, agent.circuitcode, teleportFlags); if (!AuthorizeUser (scene, agent, out reason)) { OSDMap map = new OSDMap (); map["Reason"] = reason; map["Success"] = false; reason = OSDParser.SerializeJsonString (map); return false; } CacheUserInfo(scene, agent.OtherInformation); if (sp != null && !sp.IsChildAgent) { // We have a zombie from a crashed session. // Or the same user is trying to be root twice here, won't work. // Kill it. MainConsole.Instance.InfoFormat ("[Scene]: Zombie scene presence detected for {0} in {1}", agent.AgentID, scene.RegionInfo.RegionName); //Tell everyone about it scene.AuroraEventManager.FireGenericEventHandler ("AgentIsAZombie", sp.UUID); //Send the killing message (DisableSimulator) scene.RemoveAgent (sp, true); sp = null; } OSDMap responseMap = new OSDMap (); responseMap["CapsUrls"] = scene.EventManager.TriggerOnRegisterCaps (agent.AgentID); responseMap["OurIPForClient"] = NetworkUtils.ResolveAddressForClient(NetworkUtils.GetHostFromDNS(MainServer.Instance.HostName), new IPEndPoint(IPAddress.Parse(agent.IPAddress), 0)).ToString(); // In all cases, add or update the circuit data with the new agent circuit data and teleport flags agent.teleportFlags = teleportFlags; responseMap["Agent"] = agent.PackAgentCircuitData (); object[] obj = new object[2]; obj[0] = responseMap; obj[1] = agent; scene.AuroraEventManager.FireGenericEventHandler ("NewUserConnection", obj); //Add the circuit at the end scene.AuthenticateHandler.AddNewCircuit (agent.circuitcode, agent); MainConsole.Instance.InfoFormat ( "[ConnectionBegin]: Region {0} authenticated and authorized incoming {1} agent {2} (circuit code {3})", scene.RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.AgentID, agent.circuitcode); responseMap["Success"] = true; reason = OSDParser.SerializeJsonString (responseMap); return true; } private void CacheUserInfo(IScene scene, OSDMap map) { if(map.ContainsKey("CachedUserInfo")) { //OpenSim does not contain this, only check if it is there // We do this caching so that we don't pull down all of this info as the user is trying to login, which causes major lag, and slows down the sim for people already in the sim CachedUserInfo cache = new CachedUserInfo(); cache.FromOSD((OSDMap)map["CachedUserInfo"]); IAgentConnector conn = Aurora.DataManager.DataManager.RequestPlugin<IAgentConnector>(); if (conn != null) conn.CacheAgent(cache.AgentInfo); scene.UserAccountService.CacheAccount(cache.UserAccount); IGroupsModule groupsMod = scene.RequestModuleInterface<IGroupsModule>(); if (groupsMod != null) groupsMod.UpdateCachedData(cache.UserAccount.PrincipalID, cache); } } private readonly Dictionary<IScene, int> m_lastUsedPort = new Dictionary<IScene, int> (); /// <summary> /// This method provides ports for the region to accept requests from clients on as given by the region info /// and goes through them one by one /// </summary> /// <param name="scene"></param> /// <returns></returns> private int GetUDPPort (IScene scene) { if (scene.RegionInfo.UDPPorts.Count == 0) return scene.RegionInfo.InternalEndPoint.Port; lock (m_lastUsedPort) { if (!m_lastUsedPort.ContainsKey (scene)) m_lastUsedPort.Add (scene, 0); int port = scene.RegionInfo.UDPPorts[m_lastUsedPort[scene]]; m_lastUsedPort[scene]++; if (m_lastUsedPort[scene] == scene.RegionInfo.UDPPorts.Count) m_lastUsedPort[scene] = 0; return port; } } /// <summary> /// Verify if the user can connect to this region. Checks the banlist and ensures that the region is set for public access /// </summary> /// <param name="scene"></param> /// <param name="agent">The circuit data for the agent</param> /// <param name="reason">outputs the reason to this string</param> /// <returns>True if the region accepts this agent. False if it does not. False will /// also return a reason.</returns> protected bool AuthorizeUser (IScene scene, AgentCircuitData agent, out string reason) { reason = String.Empty; IAuthorizationService AuthorizationService = scene.RequestModuleInterface<IAuthorizationService> (); if (AuthorizationService != null) { GridRegion ourRegion = new GridRegion (scene.RegionInfo); if (!AuthorizationService.IsAuthorizedForRegion (ourRegion, agent, !agent.child, out reason)) { MainConsole.Instance.WarnFormat ("[ConnectionBegin]: Denied access to {0} at {1} because the user does not have access to the region, reason: {2}", agent.AgentID, scene.RegionInfo.RegionName, reason); reason = String.Format ("You do not have access to the region {0}, reason: {1}", scene.RegionInfo.RegionName, reason); return false; } } return true; } /// <summary> /// We've got an update about an agent that sees into this region, /// send it to ScenePresence for processing It's the full data. /// </summary> /// <param name="scene"></param> /// <param name="cAgentData">Agent that contains all of the relevant things about an agent. /// Appearance, animations, position, etc.</param> /// <returns>true if we handled it.</returns> public virtual bool IncomingChildAgentDataUpdate (IScene scene, AgentData cAgentData) { MainConsole.Instance.DebugFormat( "[SCENE]: Incoming child agent update for {0} in {1}", cAgentData.AgentID, scene.RegionInfo.RegionName); //No null updates! if (cAgentData == null) return false; // We have to wait until the viewer contacts this region after receiving EAC. // That calls AddNewClient, which finally creates the ScenePresence and then this gets set up // So if the client isn't here yet, save the update for them when they get into the region fully IScenePresence SP = scene.GetScenePresence (cAgentData.AgentID); if (SP != null) SP.ChildAgentDataUpdate (cAgentData); else lock (m_incomingChildAgentData) { if (!m_incomingChildAgentData.ContainsKey (scene)) m_incomingChildAgentData.Add (scene, new Dictionary<UUID, AgentData> ()); m_incomingChildAgentData[scene][cAgentData.AgentID] = cAgentData; return false;//The agent doesn't exist } return true; } /// <summary> /// We've got an update about an agent that sees into this region, /// send it to ScenePresence for processing It's only positional data /// </summary> /// <param name="scene"></param> /// <param name="cAgentData">AgentPosition that contains agent positional data so we can know what to send</param> /// <returns>true if we handled it.</returns> public virtual bool IncomingChildAgentDataUpdate (IScene scene, AgentPosition cAgentData) { //MainConsole.Instance.Debug(" XXX Scene IncomingChildAgentDataUpdate POSITION in " + RegionInfo.RegionName); IScenePresence presence = scene.GetScenePresence (cAgentData.AgentID); if (presence != null) { // I can't imagine *yet* why we would get an update if the agent is a root agent.. // however to avoid a race condition crossing borders.. if (presence.IsChildAgent) { uint rRegionX = 0; uint rRegionY = 0; //In meters Utils.LongToUInts (cAgentData.RegionHandle, out rRegionX, out rRegionY); //In meters int tRegionX = scene.RegionInfo.RegionLocX; int tRegionY = scene.RegionInfo.RegionLocY; //Send Data to ScenePresence presence.ChildAgentDataUpdate (cAgentData, tRegionX, tRegionY, (int)rRegionX, (int)rRegionY); } return true; } return false; } public virtual bool IncomingRetrieveRootAgent(IScene scene, UUID id, bool agentIsLeaving, out AgentData agent, out AgentCircuitData circuitData) { agent = null; circuitData = null; IScenePresence sp = scene.GetScenePresence (id); if ((sp != null) && (!sp.IsChildAgent)) { AgentData data = new AgentData (); sp.CopyTo (data); agent = data; circuitData = BuildCircuitDataForPresence(sp, sp.AbsolutePosition); //if (agentIsLeaving) // sp.SetAgentLeaving(null);//We arn't sure where they are going return true; } return false; } /// <summary> /// Tell a single agent to disconnect from the region. /// </summary> /// <param name="scene"></param> /// <param name="agentID"></param> public bool IncomingCloseAgent (IScene scene, UUID agentID) { //MainConsole.Instance.DebugFormat("[SCENE]: Processing incoming close agent for {0}", agentID); IScenePresence presence = scene.GetScenePresence (agentID); if (presence != null) { bool RetVal = scene.RemoveAgent (presence, true); ISyncMessagePosterService syncPoster = scene.RequestModuleInterface<ISyncMessagePosterService> (); if (syncPoster != null) { //Tell the grid that we are logged out syncPoster.Post (SyncMessageHelper.DisableSimulator (presence.UUID, scene.RegionInfo.RegionHandle), scene.RegionInfo.RegionHandle); } return RetVal; } return false; } #endregion } }
// // SupportingClasses.cs // // using System; using System.Windows; using System.Windows.Navigation; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Windows.Ink; using System.Windows.Controls; using System.Collections.Generic; using System.Windows.Input; using System.Windows.Data; using System.Windows.Markup; namespace Microsoft.Samples.CustomControls { #region SpectrumSlider public class SpectrumSlider : Slider { static SpectrumSlider() { DefaultStyleKeyProperty.OverrideMetadata(typeof(SpectrumSlider), new FrameworkPropertyMetadata(typeof(SpectrumSlider))); } #region Public Properties public Color SelectedColor { get { return (Color)GetValue(SelectedColorProperty); } set { SetValue(SelectedColorProperty, value); } } #endregion #region Dependency Property Fields public static readonly DependencyProperty SelectedColorProperty = DependencyProperty.Register ("SelectedColor", typeof(Color), typeof(SpectrumSlider), new PropertyMetadata(System.Windows.Media.Colors.Transparent)); #endregion #region Public Methods public override void OnApplyTemplate() { base.OnApplyTemplate(); m_spectrumDisplay = GetTemplateChild(SpectrumDisplayName) as Rectangle; updateColorSpectrum(); OnValueChanged(Double.NaN, Value); } #endregion #region Protected Methods protected override void OnValueChanged(double oldValue, double newValue) { base.OnValueChanged(oldValue, newValue); Color theColor = ColorUtilities.ConvertHsvToRgb(360 - newValue, 1, 1); SetValue(SelectedColorProperty, theColor); } #endregion #region Private Methods private void updateColorSpectrum() { if (m_spectrumDisplay != null) { createSpectrum(); } } private void createSpectrum() { pickerBrush = new LinearGradientBrush(); pickerBrush.StartPoint = new Point(0.5, 0); pickerBrush.EndPoint = new Point(0.5, 1); pickerBrush.ColorInterpolationMode = ColorInterpolationMode.SRgbLinearInterpolation; List<Color> colorsList = ColorUtilities.GenerateHsvSpectrum(); double stopIncrement = (double)1 / colorsList.Count; int i; for (i = 0; i < colorsList.Count; i++) { pickerBrush.GradientStops.Add(new GradientStop(colorsList[i], i * stopIncrement)); } pickerBrush.GradientStops[i - 1].Offset = 1.0; m_spectrumDisplay.Fill = pickerBrush; } #endregion #region Private Fields private static string SpectrumDisplayName = "PART_SpectrumDisplay"; private Rectangle m_spectrumDisplay; private LinearGradientBrush pickerBrush; #endregion } #endregion SpectrumSlider #region ColorUtilities static class ColorUtilities { // Converts an RGB color to an HSV color. public static HsvColor ConvertRgbToHsv(int r, int b, int g) { double delta, min; double h = 0, s, v; min = Math.Min(Math.Min(r, g), b); v = Math.Max(Math.Max(r, g), b); delta = v - min; if (v == 0.0) { s = 0; } else s = delta / v; if (s == 0) h = 0.0; else { if (r == v) h = (g - b) / delta; else if (g == v) h = 2 + (b - r) / delta; else if (b == v) h = 4 + (r - g) / delta; h *= 60; if (h < 0.0) h = h + 360; } HsvColor hsvColor = new HsvColor(); hsvColor.H = h; hsvColor.S = s; hsvColor.V = v / 255; return hsvColor; } // Converts an HSV color to an RGB color. public static Color ConvertHsvToRgb(double h, double s, double v) { double r = 0, g = 0, b = 0; if (s == 0) { r = v; g = v; b = v; } else { int i; double f, p, q, t; if (h == 360) h = 0; else h = h / 60; i = (int)Math.Truncate(h); f = h - i; p = v * (1.0 - s); q = v * (1.0 - (s * f)); t = v * (1.0 - (s * (1.0 - f))); switch (i) { case 0: r = v; g = t; b = p; break; case 1: r = q; g = v; b = p; break; case 2: r = p; g = v; b = t; break; case 3: r = p; g = q; b = v; break; case 4: r = t; g = p; b = v; break; default: r = v; g = p; b = q; break; } } return Color.FromArgb(255, (byte)(r * 255), (byte)(g * 255), (byte)(b * 255)); } // Generates a list of colors with hues ranging from 0 360 // and a saturation and value of 1. public static List<Color> GenerateHsvSpectrum() { List<Color> colorsList = new List<Color>(8); for (int i = 0; i < 29; i++) { colorsList.Add( ColorUtilities.ConvertHsvToRgb(i * 12, 1, 1) ); } colorsList.Add(ColorUtilities.ConvertHsvToRgb(0, 1, 1)); return colorsList; } } #endregion ColorUtilities // Describes a color in terms of // Hue, Saturation, and Value (brightness) #region HsvColor struct HsvColor { public double H; public double S; public double V; public HsvColor(double h, double s, double v) { this.H = h; this.S = s; this.V = v; } } #endregion HsvColor #region ColorThumb public class ColorThumb : System.Windows.Controls.Primitives.Thumb { static ColorThumb() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ColorThumb), new FrameworkPropertyMetadata(typeof(ColorThumb))); } public static readonly DependencyProperty ThumbColorProperty = DependencyProperty.Register ("ThumbColor", typeof(Color), typeof(ColorThumb), new FrameworkPropertyMetadata(Colors.Transparent)); public static readonly DependencyProperty PointerOutlineThicknessProperty = DependencyProperty.Register ("PointerOutlineThickness", typeof(double), typeof(ColorThumb), new FrameworkPropertyMetadata(1.0)); public static readonly DependencyProperty PointerOutlineBrushProperty = DependencyProperty.Register ("PointerOutlineBrush", typeof(Brush), typeof(ColorThumb), new FrameworkPropertyMetadata(null)); public Color ThumbColor { get { return (Color)GetValue(ThumbColorProperty); } set { SetValue(ThumbColorProperty, value); } } public double PointerOutlineThickness { get { return (double)GetValue(PointerOutlineThicknessProperty); } set { SetValue(PointerOutlineThicknessProperty, value); } } public Brush PointerOutlineBrush { get { return (Brush)GetValue(PointerOutlineBrushProperty); } set { SetValue(PointerOutlineBrushProperty, value); } } } #endregion ColorThumb }
namespace Gu.Wpf.Geometry { using System; using System.ComponentModel; using System.Diagnostics; using System.Windows; [DebuggerDisplay("{DebuggerDisplay,nq}")] internal struct Line { internal readonly Point StartPoint; internal readonly Point EndPoint; internal Line(Point startPoint, Point endPoint) { this.StartPoint = startPoint; this.EndPoint = endPoint; } internal Point MidPoint { get { var x = (this.StartPoint.X + this.EndPoint.X) / 2; var y = (this.StartPoint.Y + this.EndPoint.Y) / 2; return new Point(x, y); } } internal double Length => (this.EndPoint - this.StartPoint).Length; internal Vector Direction { get { var v = this.EndPoint - this.StartPoint; v.Normalize(); return v; } } internal Vector PerpendicularDirection { get { var direction = this.Direction; return new Vector(direction.Y, -direction.X); } } private string DebuggerDisplay => $"{this.StartPoint.ToString("F1")} -> {this.EndPoint.ToString("F1")} length: {this.Length:F1}"; public override string ToString() => this.ToString(string.Empty); internal static Line Parse(string text) { var strings = text.Split(';'); if (strings.Length != 2) { throw new FormatException("Could not parse a Line from the string."); } var sp = Point.Parse(strings[0]); var ep = Point.Parse(strings[1]); return new Line(sp, ep); } internal string ToString(string format) => $"{this.StartPoint.ToString(format)}; {this.EndPoint.ToString(format)}"; internal Line RotateAroundStartPoint(double angleInDegrees) { var v = this.EndPoint - this.StartPoint; v = v.Rotate(angleInDegrees); var ep = this.StartPoint + v; return new Line(this.StartPoint, ep); } internal Line Flip() { return new Line(this.EndPoint, this.StartPoint); } internal Line Offset(double distance) { var v = this.PerpendicularDirection; var sp = this.StartPoint.WithOffset(v, distance); var ep = this.EndPoint.WithOffset(v, distance); return new Line(sp, ep); } internal bool IsPointOnLine(Point p) { if (this.StartPoint.DistanceTo(p) < Constants.Tolerance) { return true; } var v = p - this.StartPoint; var angleBetween = Vector.AngleBetween(this.Direction, v); if (Math.Abs(angleBetween) > Constants.Tolerance) { return false; } return v.Length <= this.Length + Constants.Tolerance; } internal Point? TrimTo(Point p) { if (this.IsPointOnLine(p)) { return p; } var v = this.StartPoint.VectorTo(p); if (Math.Abs(v.AngleTo(this.Direction) % 180) > Constants.Tolerance) { return null; } var dp = v.DotProdcut(this.Direction); return dp < 0 ? this.StartPoint : this.EndPoint; } internal Point Project(Point p) { var toPoint = this.StartPoint.VectorTo(p); var dotProdcut = toPoint.DotProdcut(this.Direction); var projected = this.StartPoint + (dotProdcut * this.Direction); return projected; } internal Line? TrimOrExtendEndWith(Line other) { if (this.EndPoint.DistanceTo(other.StartPoint) < Constants.Tolerance) { return this; } var ip = IntersectionPoint(this, other, mustBeBetweenStartAndEnd: false); if (ip is null) { return this; } return new Line(this.StartPoint, ip.Value); } internal Line? TrimOrExtendStartWith(Line other) { if (this.StartPoint.DistanceTo(other.EndPoint) < Constants.Tolerance) { return this; } var ip = IntersectionPoint(this, other, mustBeBetweenStartAndEnd: false); if (ip is null) { return null; } return new Line(ip.Value, this.EndPoint); } internal Point? IntersectWith(Line other, bool mustBeBetweenStartAndEnd) { return IntersectionPoint(this, other, mustBeBetweenStartAndEnd); } internal Point? ClosestIntersection(Rect rectangle) { var quadrant = rectangle.Contains(this.StartPoint) ? this.Direction.Quadrant() : this.Direction.Negated().Quadrant(); return quadrant switch { Quadrant.NegativeXPositiveY => IntersectionPoint(rectangle.LeftLine(), this, mustBeBetweenStartAndEnd: true) ?? IntersectionPoint(rectangle.BottomLine(), this, mustBeBetweenStartAndEnd: true), Quadrant.PositiveXPositiveY => IntersectionPoint(rectangle.RightLine(), this, mustBeBetweenStartAndEnd: true) ?? IntersectionPoint(rectangle.BottomLine(), this, mustBeBetweenStartAndEnd: true), Quadrant.PositiveXNegativeY => IntersectionPoint(rectangle.RightLine(), this, mustBeBetweenStartAndEnd: true) ?? IntersectionPoint(rectangle.TopLine(), this, mustBeBetweenStartAndEnd: true), Quadrant.NegativeXNegativeY => IntersectionPoint(rectangle.LeftLine(), this, mustBeBetweenStartAndEnd: true) ?? IntersectionPoint(rectangle.TopLine(), this, mustBeBetweenStartAndEnd: true), _ => throw new InvalidEnumArgumentException("Unhandled Quadrant."), }; } internal double DistanceTo(Point p) { return this.Project(p) .DistanceTo(p); } internal double DistanceToPointOnLine(Point p) { var toPoint = this.StartPoint.VectorTo(p); var dotProduct = toPoint.DotProdcut(this.Direction); var pointOnLine = this.StartPoint + (dotProduct * this.Direction); return pointOnLine.DistanceTo(p); } internal Line? PerpendicularLineTo(Point p) { if (this.IsPointOnLine(p)) { return null; } var startPoint = this.Project(p); return new Line(startPoint, p); } // http://geomalgorithms.com/a05-_intersect-1.html#intersect2D_2Segments() private static Point? IntersectionPoint(Line l1, Line l2, bool mustBeBetweenStartAndEnd) { var u = l1.Direction; var v = l2.Direction; var w = l1.StartPoint - l2.StartPoint; var d = Perp(u, v); if (Math.Abs(d) < Constants.Tolerance) { // parallel lines return null; } var sI = Perp(v, w) / d; var p = l1.StartPoint + (sI * u); if (mustBeBetweenStartAndEnd) { if (l1.IsPointOnLine(p) && l2.IsPointOnLine(p)) { return p; } return null; } return p; } private static double Perp(Vector u, Vector v) { return (u.X * v.Y) - (u.Y * v.X); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Lists; namespace osu.Framework.Tests.Lists { [TestFixture] public class TestWeakList { [Test] public void TestAdd() { var obj = new object(); var list = new WeakList<object> { obj }; Assert.That(list.Count(), Is.EqualTo(1)); Assert.That(list, Does.Contain(obj)); GC.KeepAlive(obj); } [Test] public void TestAddWeakReference() { var obj = new object(); var weakRef = new WeakReference<object>(obj); var list = new WeakList<object> { weakRef }; Assert.That(list.Contains(weakRef), Is.True); GC.KeepAlive(obj); } [Test] public void TestEnumerate() { var obj = new object(); var list = new WeakList<object> { obj }; Assert.That(list.Count(), Is.EqualTo(1)); Assert.That(list, Does.Contain(obj)); GC.KeepAlive(obj); } [Test] public void TestRemove() { var obj = new object(); var list = new WeakList<object> { obj }; list.Remove(obj); Assert.That(list.Count(), Is.Zero); Assert.That(list, Does.Not.Contain(obj)); GC.KeepAlive(obj); } [Test] public void TestRemoveWeakReference() { var obj = new object(); var weakRef = new WeakReference<object>(obj); var list = new WeakList<object> { weakRef }; list.Remove(weakRef); Assert.That(list.Count(), Is.Zero); Assert.That(list.Contains(weakRef), Is.False); GC.KeepAlive(obj); } [Test] public void TestRemoveObjectsAtSides() { var objects = new List<object> { new object(), new object(), new object(), new object(), new object(), new object(), }; var list = new WeakList<object>(); foreach (var o in objects) list.Add(o); list.Remove(objects[0]); list.Remove(objects[1]); list.Remove(objects[4]); list.Remove(objects[5]); Assert.That(list.Count(), Is.EqualTo(2)); Assert.That(list, Does.Contain(objects[2])); Assert.That(list, Does.Contain(objects[3])); } [Test] public void TestRemoveObjectsAtCentre() { var objects = new List<object> { new object(), new object(), new object(), new object(), new object(), new object(), }; var list = new WeakList<object>(); foreach (var o in objects) list.Add(o); list.Remove(objects[2]); list.Remove(objects[3]); Assert.That(list.Count(), Is.EqualTo(4)); Assert.That(list, Does.Contain(objects[0])); Assert.That(list, Does.Contain(objects[1])); Assert.That(list, Does.Contain(objects[4])); Assert.That(list, Does.Contain(objects[5])); } [Test] public void TestAddAfterRemoveFromEnd() { var objects = new List<object> { new object(), new object(), new object(), }; var newLastObject = new object(); var list = new WeakList<object>(); foreach (var o in objects) list.Add(o); list.Remove(objects[2]); list.Add(newLastObject); Assert.That(list.Count(), Is.EqualTo(3)); Assert.That(list, Does.Contain(objects[0])); Assert.That(list, Does.Contain(objects[0])); Assert.That(list, Does.Not.Contain(objects[2])); Assert.That(list, Does.Contain(newLastObject)); } [Test] public void TestRemoveAllUsingRemoveAtFromStart() { var objects = new List<object> { new object(), new object(), new object(), new object(), new object(), new object(), }; var list = new WeakList<object>(); foreach (var o in objects) list.Add(o); for (int i = 0; i < objects.Count; i++) list.RemoveAt(0); Assert.That(list.Count(), Is.Zero); } [Test] public void TestRemoveAllUsingRemoveAtFromEnd() { var objects = new List<object> { new object(), new object(), new object(), new object(), new object(), new object(), }; var list = new WeakList<object>(); foreach (var o in objects) list.Add(o); for (int i = 0; i < objects.Count; i++) list.RemoveAt(list.Count() - 1); Assert.That(list.Count(), Is.Zero); } [Test] public void TestRemoveAllUsingRemoveAtFromBothSides() { var objects = new List<object> { new object(), new object(), new object(), new object(), new object(), new object(), new object(), new object(), new object(), }; var list = new WeakList<object>(); foreach (var o in objects) list.Add(o); for (int i = 0; i < objects.Count; i++) { if (i % 2 == 0) list.RemoveAt(0); else list.RemoveAt(list.Count() - 1); } Assert.That(list.Count(), Is.Zero); } [Test] public void TestCountIsZeroAfterClear() { var obj = new object(); var weakRef = new WeakReference<object>(obj); var list = new WeakList<object> { obj, weakRef }; list.Clear(); Assert.That(list.Count(), Is.Zero); Assert.That(list, Does.Not.Contain(obj)); Assert.That(list.Contains(weakRef), Is.False); GC.KeepAlive(obj); } [Test] public void TestAddAfterClear() { var objects = new List<object> { new object(), new object(), new object(), }; var newObject = new object(); var list = new WeakList<object>(); foreach (var o in objects) list.Add(o); list.Clear(); list.Add(newObject); Assert.That(list.Count(), Is.EqualTo(1)); Assert.That(list, Does.Contain(newObject)); } [Test] public void TestIterateWithRemove() { var obj = new object(); var obj2 = new object(); var obj3 = new object(); var list = new WeakList<object> { obj, obj2, obj3 }; int count = 0; foreach (var item in list) { if (count == 1) list.Remove(item); count++; } Assert.That(count, Is.EqualTo(3)); Assert.That(list, Does.Contain(obj)); Assert.That(list, Does.Not.Contain(obj2)); Assert.That(list, Does.Contain(obj3)); GC.KeepAlive(obj); GC.KeepAlive(obj2); GC.KeepAlive(obj3); } [Test] public void TestIterateWithRemoveSkipsInvalidated() { var obj = new object(); var obj2 = new object(); var obj3 = new object(); var list = new WeakList<object> { obj, obj2, obj3 }; int count = 0; foreach (var item in list) { if (count == 0) list.Remove(obj2); Assert.That(item, Is.Not.EqualTo(obj2)); count++; } Assert.That(count, Is.EqualTo(2)); GC.KeepAlive(obj); GC.KeepAlive(obj2); GC.KeepAlive(obj3); } [Test] public void TestDeadObjectsAreSkippedBeforeEnumeration() { GC.TryStartNoGCRegion(10 * 1000000); // 10MB (should be enough) var (list, aliveObjects) = generateWeakList(); GC.EndNoGCRegion(); GC.Collect(); GC.WaitForPendingFinalizers(); foreach (var obj in list) { if (!aliveObjects.Contains(obj)) Assert.Fail("Dead objects were iterated over."); } } [Test] public void TestDeadObjectsAreSkippedDuringEnumeration() { GC.TryStartNoGCRegion(10 * 1000000); // 10MB (should be enough) var (list, aliveObjects) = generateWeakList(); using (var enumerator = list.GetEnumerator()) { GC.EndNoGCRegion(); GC.Collect(); GC.WaitForPendingFinalizers(); while (enumerator.MoveNext()) { if (!aliveObjects.Contains(enumerator.Current)) Assert.Fail("Dead objects were iterated over."); } } } // This method is required for references to be released in DEBUG builds. private (WeakList<object> list, object[] aliveObjects) generateWeakList() { var objects = new List<object> { new object(), new object(), new object(), new object(), new object(), new object(), }; var list = new WeakList<object>(); foreach (var o in objects) list.Add(o); return (list, new[] { objects[1], objects[2], objects[4] }); } } }
using Signum.Engine; using Signum.Engine.Authorization; using Signum.Entities; using Signum.Entities.Authorization; using Signum.React.Filters; using Signum.Utilities; using System; using System.IO; using System.IO.Compression; using System.Linq; using System.Security.Authentication; using System.Security.Cryptography; using System.Text; using System.Runtime.Serialization.Formatters.Binary; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Authorization; using Signum.Engine.Json; using System.Text.Json; namespace Signum.React.Authorization { public static class AuthTokenServer { public static Func<AuthTokenConfigurationEmbedded> Configuration; public static Action<UserEntity, AuthToken?, AuthToken?> OnAuthToken; public static Func<string, bool> AuthenticateHeader = (authHeader) => true; public static void Start(Func<AuthTokenConfigurationEmbedded> tokenConfig, string hashableEncryptionKey) { Configuration = tokenConfig; CryptoKey = new MD5CryptoServiceProvider().Using(p => p.ComputeHash(Encoding.UTF8.GetBytes(hashableEncryptionKey))); SignumAuthenticationFilter.Authenticators.Add(TokenAuthenticator); SignumAuthenticationFilter.Authenticators.Add(AnonymousUserAuthenticator); SignumAuthenticationFilter.Authenticators.Add(AllowAnonymousAuthenticator); SignumAuthenticationFilter.Authenticators.Add(InvalidAuthenticator); } public static SignumAuthenticationResult? InvalidAuthenticator(FilterContext actionContext) { throw new AuthenticationException("No authentication information found!"); } public static SignumAuthenticationResult? AnonymousUserAuthenticator(FilterContext actionContext) { if (AuthLogic.AnonymousUser != null) return new SignumAuthenticationResult { User = AuthLogic.AnonymousUser }; return null; } public static SignumAuthenticationResult? AllowAnonymousAuthenticator(FilterContext actionContext) { if (actionContext.ActionDescriptor is ControllerActionDescriptor cad && (cad.MethodInfo.HasAttribute<SignumAllowAnonymousAttribute>() || cad.ControllerTypeInfo.HasAttribute<SignumAllowAnonymousAttribute>())) return new SignumAuthenticationResult(); return null; } public static string AuthHeader = "Authorization"; public static void PrepareForWindowsAuthentication() { AuthHeader = "Signum_Authorization"; } public static SignumAuthenticationResult? TokenAuthenticator(FilterContext ctx) { var authHeader = ctx.HttpContext.Request.Headers[AuthHeader].FirstOrDefault(); if (authHeader == null || !AuthenticateHeader(authHeader)) { return null; } var token = DeserializeAuthHeaderToken(authHeader); var c = Configuration(); bool requiresRefresh = token.CreationDate.AddMinutes(c.RefreshTokenEvery) < TimeZoneManager.Now || c.RefreshAnyTokenPreviousTo.HasValue && token.CreationDate < c.RefreshAnyTokenPreviousTo || ctx.HttpContext.Request.Query.ContainsKey("refreshToken"); if (requiresRefresh) { ctx.HttpContext.Response.Headers["New_Token"] = RefreshToken(token, out var newUser); return new SignumAuthenticationResult { User = newUser}; } else { OnAuthToken?.Invoke(token.User, token, null); } return new SignumAuthenticationResult { User = token.User }; } public static string RefreshToken(AuthToken oldToken, out UserEntity newUser) { var user = AuthLogic.Disable().Using(_ => Database.Query<UserEntity>().SingleOrDefaultEx(u => u.Id == oldToken.User.Id)); if (user == null) throw new AuthenticationException(LoginAuthMessage.TheUserIsNotLongerInTheDatabase.NiceToString()); if (user.State == UserState.Deactivated) throw new AuthenticationException(LoginAuthMessage.User0IsDisabled.NiceToString(user)); if (user.UserName != oldToken.User.UserName) throw new AuthenticationException(LoginAuthMessage.InvalidUsername.NiceToString()); if (!user.PasswordHash.EmptyIfNull().SequenceEqual(oldToken.User.PasswordHash.EmptyIfNull())) throw new AuthenticationException(LoginAuthMessage.InvalidPassword.NiceToString()); AuthToken newToken = new AuthToken { User = user, CreationDate = TimeZoneManager.Now, }; OnAuthToken?.Invoke(user, oldToken, newToken); var result = SerializeToken(newToken); newUser = user; return result; } public static Func<string, AuthToken> DeserializeAuthHeaderToken = (string authHeader) => DeserializeToken(authHeader.After("Bearer ")); public static AuthToken DeserializeToken(string token) { try { var array = Convert.FromBase64String(token); array = Decrypt(array); using (var ms = new MemoryStream(array)) using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress)) { var bytes = ds.ReadAllBytes(); return JsonExtensions.FromJsonBytes<AuthToken>(bytes, EntityJsonContext.FullJsonSerializerOptions); } } catch (Exception) { throw new AuthenticationException("Invalid token"); } } public static string CreateToken(UserEntity user) { AuthToken newToken = new AuthToken { User = user, CreationDate = TimeZoneManager.Now, }; OnAuthToken?.Invoke(user, null, newToken); return SerializeToken(newToken); } static string SerializeToken(AuthToken token) { using (HeavyProfiler.LogNoStackTrace("SerializeToken")) { var array = new MemoryStream().Using(ms => { using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress)) { using (Utf8JsonWriter writer = new Utf8JsonWriter(ds)) { JsonSerializer.Serialize(writer, token, EntityJsonContext.FullJsonSerializerOptions); } } return ms.ToArray(); }); //var str = Encoding.UTF8.GetString(array); array = Encrypt(array); return Convert.ToBase64String(array); } } static byte[] CryptoKey; //http://stackoverflow.com/questions/8041451/good-aes-initialization-vector-practice static byte[] Encrypt(byte[] toEncryptBytes) { using (var provider = new AesCryptoServiceProvider()) { provider.Key = CryptoKey; provider.Mode = CipherMode.CBC; provider.Padding = PaddingMode.PKCS7; using (var encryptor = provider.CreateEncryptor(provider.Key, provider.IV)) { using (var ms = new MemoryStream()) { ms.Write(provider.IV, 0, provider.IV.Length); using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { cs.Write(toEncryptBytes, 0, toEncryptBytes.Length); cs.FlushFinalBlock(); } return ms.ToArray(); } } } } static byte[] Decrypt(byte[] encryptedString) { using (var provider = new AesCryptoServiceProvider()) { provider.Key = CryptoKey; using (var ms = new MemoryStream(encryptedString)) { // Read the first 16 bytes which is the IV. byte[] iv = new byte[16]; ms.Read(iv, 0, 16); provider.IV = iv; using (var decryptor = provider.CreateDecryptor()) { using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) { return cs.ReadAllBytes(); } } } } } } [Serializable] public class AuthToken { public UserEntity User { get; set; } public DateTime CreationDate { get; set; } } [Serializable] public class NewTokenRequiredException : Exception { public NewTokenRequiredException(string message) : base(message) { } } }
using System.Linq; using System.Reflection; using System.Web.Mvc; using NGM.Forum.Models; using NGM.Forum.Extensions; using NGM.Forum.Services; using Orchard; using Orchard.ContentManagement; using Orchard.Core.Contents.Controllers; using Orchard.DisplayManagement; using Orchard.Localization; using Orchard.Mvc; using Orchard.Settings; using Orchard.UI.Admin; using Orchard.UI.Navigation; using Orchard.UI.Notify; namespace NGM.Forum.Controllers { [ValidateInput(false), Admin] public class ForumAdminController : Controller, IUpdateModel { private readonly IOrchardServices _orchardServices; private readonly IForumService _forumService; private readonly IThreadService _threadService; private readonly ISiteService _siteService; private readonly IContentManager _contentManager; public ForumAdminController(IOrchardServices orchardServices, IForumService forumService, IThreadService threadService, ISiteService siteService, IContentManager contentManager, IShapeFactory shapeFactory) { _orchardServices = orchardServices; _forumService = forumService; _threadService = threadService; _siteService = siteService; _contentManager = contentManager; T = NullLocalizer.Instance; Shape = shapeFactory; } dynamic Shape { get; set; } public Localizer T { get; set; } public ActionResult Create(string type) { if (!_orchardServices.Authorizer.Authorize(Permissions.ManageForums, T("Not allowed to create forums"))) return new HttpUnauthorizedResult(); if (string.IsNullOrWhiteSpace(type)) { var forumTypes = _forumService.GetForumTypes(); if (forumTypes.Count > 1) return Redirect(Url.ForumSelectTypeForAdmin()); if (forumTypes.Count == 0) { _orchardServices.Notifier.Warning(T("You have no forum types available. Add one to create a forum.")); return Redirect(Url.DashboardForAdmin()); } type = forumTypes.Single().Name; } var forum = _orchardServices.ContentManager.New<ForumPart>(type); if (forum == null) return HttpNotFound(); var model = _orchardServices.ContentManager.BuildEditor(forum); return View((object)model); } public ActionResult SelectType() { if (!_orchardServices.Authorizer.Authorize(Permissions.ManageForums, T("Not allowed to create forums"))) return new HttpUnauthorizedResult(); var forumTypes = _forumService.GetForumTypes(); var model = Shape.ViewModel(ForumTypes: forumTypes); return View(model); } [HttpPost, ActionName("Create")] public ActionResult CreatePOST(string type) { if (!_orchardServices.Authorizer.Authorize(Permissions.ManageForums, T("Not allowed to create forums"))) return new HttpUnauthorizedResult(); if (string.IsNullOrWhiteSpace(type)) { var forumTypes = _forumService.GetForumTypes(); if (forumTypes.Count > 1) return Redirect(Url.ForumSelectTypeForAdmin()); if (forumTypes.Count == 0) { _orchardServices.Notifier.Warning(T("You have no forum types available. Add one to create a forum.")); return Redirect(Url.DashboardForAdmin()); } type = forumTypes.Single().Name; } var forum = _orchardServices.ContentManager.New<ForumPart>(type); _orchardServices.ContentManager.Create(forum, VersionOptions.Draft); var model = _orchardServices.ContentManager.UpdateEditor(forum, this); if (!ModelState.IsValid) { _orchardServices.TransactionManager.Cancel(); return View((object)model); } _orchardServices.ContentManager.Publish(forum.ContentItem); return Redirect(Url.ForumForAdmin(forum)); } public ActionResult Edit(int forumId) { var forum = _forumService.Get(forumId, VersionOptions.Latest); if (forum == null) return HttpNotFound(); if (!_orchardServices.Authorizer.Authorize(Permissions.ManageForums, forum, T("Not allowed to edit forum"))) return new HttpUnauthorizedResult(); dynamic model = _orchardServices.ContentManager.BuildEditor(forum); // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation. return View((object)model); } [HttpPost, ActionName("Edit")] [InternalFormValueRequired("submit.Save")] public ActionResult EditPOST(int forumId) { var forum = _forumService.Get(forumId, VersionOptions.DraftRequired); if (forum == null) return HttpNotFound(); if (!_orchardServices.Authorizer.Authorize(Permissions.ManageForums, forum, T("Not allowed to edit forum"))) return new HttpUnauthorizedResult(); dynamic model = _orchardServices.ContentManager.UpdateEditor(forum, this); if (!ModelState.IsValid) { _orchardServices.TransactionManager.Cancel(); // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation. return View((object)model); } _contentManager.Publish(forum.ContentItem); _orchardServices.Notifier.Information(T("Forum information updated")); return Redirect(Url.ForumsForAdmin()); } [HttpPost, ActionName("Edit")] [InternalFormValueRequired("submit.Delete")] public ActionResult EditDeletePOST(int forumId) { return Remove(forumId); } [HttpPost] public ActionResult Remove(int forumId) { var forum = _forumService.Get(forumId, VersionOptions.Latest); if (forum == null) return HttpNotFound(); if (!_orchardServices.Authorizer.Authorize(Permissions.ManageForums, forum, T("Not allowed to edit forum"))) return new HttpUnauthorizedResult(); _forumService.Delete(forum); _orchardServices.Notifier.Information(T("Forum was successfully deleted")); return Redirect(Url.ForumsForAdmin()); } public ActionResult List() { var list = _orchardServices.New.List(); list.AddRange(_forumService.Get(VersionOptions.Latest) .Select(b => { var forum = _orchardServices.ContentManager.BuildDisplay(b, "SummaryAdmin"); forum.TotalPostCount = _threadService.Get(b, VersionOptions.Latest).Count(); return forum; })); dynamic viewModel = _orchardServices.New.ViewModel() .ContentItems(list); // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation. return View((object)viewModel); } public ActionResult Item(int forumId, PagerParameters pagerParameters) { Pager pager = new Pager(_siteService.GetSiteSettings(), pagerParameters); ForumPart forum = _forumService.Get(forumId, VersionOptions.Latest); if (forum == null) return HttpNotFound(); if (!_orchardServices.Authorizer.Authorize(Permissions.ManageForums, forum, T("Not allowed to view forum"))) return new HttpUnauthorizedResult(); var threads = _threadService.Get(forum, pager.GetStartIndex(), pager.PageSize, VersionOptions.Latest).ToArray(); var threadsShapes = threads.Select(bp => _contentManager.BuildDisplay(bp, "SummaryAdmin")).ToArray(); dynamic forumShape = _orchardServices.ContentManager.BuildDisplay(forum, "DetailAdmin"); var list = Shape.List(); list.AddRange(threadsShapes); forumShape.Content.Add(Shape.Parts_Forums_Thread_ListAdmin(ContentItems: list), "5"); var totalItemCount = _threadService.Count(forum, VersionOptions.Latest); forumShape.Content.Add(Shape.Pager(pager).TotalItemCount(totalItemCount), "Content:after"); // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation. return View((object)forumShape); } bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) { return TryUpdateModel(model, prefix, includeProperties, excludeProperties); } void IUpdateModel.AddModelError(string key, LocalizedString errorMessage) { ModelState.AddModelError(key, errorMessage.ToString()); } } public class InternalFormValueRequiredAttribute : ActionMethodSelectorAttribute { private readonly string _submitButtonName; public InternalFormValueRequiredAttribute(string submitButtonName) { _submitButtonName = submitButtonName; } public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) { var value = controllerContext.HttpContext.Request.Form[_submitButtonName]; return !string.IsNullOrEmpty(value); } } }
#region Apache License // // 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. // #endregion using System; using System.Text; using System.Xml; using log4net.Core; using log4net.Util; namespace log4net.Layout { /// <summary> /// Layout that formats the log events as XML elements. /// </summary> /// <remarks> /// <para> /// The output of the <see cref="XmlLayout" /> consists of a series of /// log4net:event elements. It does not output a complete well-formed XML /// file. The output is designed to be included as an <em>external entity</em> /// in a separate file to form a correct XML file. /// </para> /// <para> /// For example, if <c>abc</c> is the name of the file where /// the <see cref="XmlLayout" /> output goes, then a well-formed XML file would /// be: /// </para> /// <code lang="XML"> /// &lt;?xml version="1.0" ?&gt; /// /// &lt;!DOCTYPE log4net:events SYSTEM "log4net-events.dtd" [&lt;!ENTITY data SYSTEM "abc"&gt;]&gt; /// /// &lt;log4net:events version="1.2" xmlns:log4net="http://logging.apache.org/log4net/schemas/log4net-events-1.2&gt; /// &amp;data; /// &lt;/log4net:events&gt; /// </code> /// <para> /// This approach enforces the independence of the <see cref="XmlLayout" /> /// and the appender where it is embedded. /// </para> /// <para> /// The <c>version</c> attribute helps components to correctly /// interpret output generated by <see cref="XmlLayout" />. The value of /// this attribute should be "1.2" for release 1.2 and later. /// </para> /// <para> /// Alternatively the <c>Header</c> and <c>Footer</c> properties can be /// configured to output the correct XML header, open tag and close tag. /// When setting the <c>Header</c> and <c>Footer</c> properties it is essential /// that the underlying data store not be appendable otherwise the data /// will become invalid XML. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class XmlLayout : XmlLayoutBase { #region Public Instance Constructors /// <summary> /// Constructs an XmlLayout /// </summary> public XmlLayout() : base() { } /// <summary> /// Constructs an XmlLayout. /// </summary> /// <remarks> /// <para> /// The <b>LocationInfo</b> option takes a boolean value. By /// default, it is set to false which means there will be no location /// information output by this layout. If the the option is set to /// true, then the file name and line number of the statement /// at the origin of the log statement will be output. /// </para> /// <para> /// If you are embedding this layout within an SmtpAppender /// then make sure to set the <b>LocationInfo</b> option of that /// appender as well. /// </para> /// </remarks> public XmlLayout(bool locationInfo) : base(locationInfo) { } #endregion Public Instance Constructors #region Public Instance Properties /// <summary> /// The prefix to use for all element names /// </summary> /// <remarks> /// <para> /// The default prefix is <b>log4net</b>. Set this property /// to change the prefix. If the prefix is set to an empty string /// then no prefix will be written. /// </para> /// </remarks> public string Prefix { get { return m_prefix; } set { m_prefix = value; } } /// <summary> /// Set whether or not to base64 encode the message. /// </summary> /// <remarks> /// <para> /// By default the log message will be written as text to the xml /// output. This can cause problems when the message contains binary /// data. By setting this to true the contents of the message will be /// base64 encoded. If this is set then invalid character replacement /// (see <see cref="XmlLayoutBase.InvalidCharReplacement"/>) will not be performed /// on the log message. /// </para> /// </remarks> public bool Base64EncodeMessage { get {return m_base64Message;} set {m_base64Message=value;} } /// <summary> /// Set whether or not to base64 encode the property values. /// </summary> /// <remarks> /// <para> /// By default the properties will be written as text to the xml /// output. This can cause problems when one or more properties contain /// binary data. By setting this to true the values of the properties /// will be base64 encoded. If this is set then invalid character replacement /// (see <see cref="XmlLayoutBase.InvalidCharReplacement"/>) will not be performed /// on the property values. /// </para> /// </remarks> public bool Base64EncodeProperties { get {return m_base64Properties;} set {m_base64Properties=value;} } #endregion Public Instance Properties #region Implementation of IOptionHandler /// <summary> /// Initialize layout options /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// <para> /// Builds a cache of the element names /// </para> /// </remarks> override public void ActivateOptions() { base.ActivateOptions(); // Cache the full element names including the prefix if (m_prefix != null && m_prefix.Length > 0) { m_elmEvent = m_prefix + ":" + ELM_EVENT; m_elmMessage = m_prefix + ":" + ELM_MESSAGE; m_elmProperties = m_prefix + ":" + ELM_PROPERTIES; m_elmData = m_prefix + ":" + ELM_DATA; m_elmException = m_prefix + ":" + ELM_EXCEPTION; m_elmLocation = m_prefix + ":" + ELM_LOCATION; } } #endregion Implementation of IOptionHandler #region Override implementation of XMLLayoutBase /// <summary> /// Does the actual writing of the XML. /// </summary> /// <param name="writer">The writer to use to output the event to.</param> /// <param name="loggingEvent">The event to write.</param> /// <remarks> /// <para> /// Override the base class <see cref="XmlLayoutBase.FormatXml"/> method /// to write the <see cref="LoggingEvent"/> to the <see cref="XmlWriter"/>. /// </para> /// </remarks> override protected void FormatXml(XmlWriter writer, LoggingEvent loggingEvent) { writer.WriteStartElement(m_elmEvent); writer.WriteAttributeString(ATTR_LOGGER, loggingEvent.LoggerName); writer.WriteAttributeString(ATTR_TIMESTAMP, XmlConvert.ToString(loggingEvent.TimeStamp, XmlDateTimeSerializationMode.Local)); writer.WriteAttributeString(ATTR_LEVEL, loggingEvent.Level.DisplayName); writer.WriteAttributeString(ATTR_THREAD, loggingEvent.ThreadName); if (loggingEvent.Domain != null && loggingEvent.Domain.Length > 0) { writer.WriteAttributeString(ATTR_DOMAIN, loggingEvent.Domain); } if (loggingEvent.Identity != null && loggingEvent.Identity.Length > 0) { writer.WriteAttributeString(ATTR_IDENTITY, loggingEvent.Identity); } if (loggingEvent.UserName != null && loggingEvent.UserName.Length > 0) { writer.WriteAttributeString(ATTR_USERNAME, loggingEvent.UserName); } // Append the message text writer.WriteStartElement(m_elmMessage); if (!this.Base64EncodeMessage) { Transform.WriteEscapedXmlString(writer, loggingEvent.RenderedMessage, this.InvalidCharReplacement); } else { byte[] messageBytes = Encoding.UTF8.GetBytes(loggingEvent.RenderedMessage); string base64Message = Convert.ToBase64String(messageBytes, 0, messageBytes.Length); Transform.WriteEscapedXmlString(writer, base64Message,this.InvalidCharReplacement); } writer.WriteEndElement(); PropertiesDictionary properties = loggingEvent.GetProperties(); // Append the properties text if (properties.Count > 0) { writer.WriteStartElement(m_elmProperties); foreach(System.Collections.DictionaryEntry entry in properties) { writer.WriteStartElement(m_elmData); writer.WriteAttributeString(ATTR_NAME, Transform.MaskXmlInvalidCharacters((string)entry.Key,this.InvalidCharReplacement)); // Use an ObjectRenderer to convert the object to a string string valueStr =null; if (!this.Base64EncodeProperties) { valueStr = Transform.MaskXmlInvalidCharacters(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value),this.InvalidCharReplacement); } else { byte[] propertyValueBytes = Encoding.UTF8.GetBytes(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value)); valueStr = Convert.ToBase64String(propertyValueBytes, 0, propertyValueBytes.Length); } writer.WriteAttributeString(ATTR_VALUE, valueStr); writer.WriteEndElement(); } writer.WriteEndElement(); } string exceptionStr = loggingEvent.GetExceptionString(); if (exceptionStr != null && exceptionStr.Length > 0) { // Append the stack trace line writer.WriteStartElement(m_elmException); Transform.WriteEscapedXmlString(writer, exceptionStr,this.InvalidCharReplacement); writer.WriteEndElement(); } if (LocationInfo) { LocationInfo locationInfo = loggingEvent.LocationInformation; writer.WriteStartElement(m_elmLocation); writer.WriteAttributeString(ATTR_CLASS, locationInfo.ClassName); writer.WriteAttributeString(ATTR_METHOD, locationInfo.MethodName); writer.WriteAttributeString(ATTR_FILE, locationInfo.FileName); writer.WriteAttributeString(ATTR_LINE, locationInfo.LineNumber); writer.WriteEndElement(); } writer.WriteEndElement(); } #endregion Override implementation of XMLLayoutBase #region Private Instance Fields /// <summary> /// The prefix to use for all generated element names /// </summary> private string m_prefix = PREFIX; private string m_elmEvent = ELM_EVENT; private string m_elmMessage = ELM_MESSAGE; private string m_elmData = ELM_DATA; private string m_elmProperties = ELM_PROPERTIES; private string m_elmException = ELM_EXCEPTION; private string m_elmLocation = ELM_LOCATION; private bool m_base64Message=false; private bool m_base64Properties=false; #endregion Private Instance Fields #region Private Static Fields private const string PREFIX = "log4net"; private const string ELM_EVENT = "event"; private const string ELM_MESSAGE = "message"; private const string ELM_PROPERTIES = "properties"; private const string ELM_GLOBAL_PROPERTIES = "global-properties"; private const string ELM_DATA = "data"; private const string ELM_EXCEPTION = "exception"; private const string ELM_LOCATION = "locationInfo"; private const string ATTR_LOGGER = "logger"; private const string ATTR_TIMESTAMP = "timestamp"; private const string ATTR_LEVEL = "level"; private const string ATTR_THREAD = "thread"; private const string ATTR_DOMAIN = "domain"; private const string ATTR_IDENTITY = "identity"; private const string ATTR_USERNAME = "username"; private const string ATTR_CLASS = "class"; private const string ATTR_METHOD = "method"; private const string ATTR_FILE = "file"; private const string ATTR_LINE = "line"; private const string ATTR_NAME = "name"; private const string ATTR_VALUE = "value"; #endregion Private Static Fields } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Controls.DataGrid.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Controls { public partial class DataGrid : System.Windows.Controls.Primitives.MultiSelector { #region Methods and constructors public bool BeginEdit() { return default(bool); } public bool BeginEdit(System.Windows.RoutedEventArgs editingEventArgs) { return default(bool); } public bool CancelEdit() { return default(bool); } public bool CancelEdit(DataGridEditingUnit editingUnit) { return default(bool); } protected override void ClearContainerForItemOverride(System.Windows.DependencyObject element, Object item) { } public void ClearDetailsVisibilityForItem(Object item) { } public DataGridColumn ColumnFromDisplayIndex(int displayIndex) { Contract.Requires(this.Columns != null); return default(DataGridColumn); } public bool CommitEdit() { return default(bool); } public bool CommitEdit(DataGridEditingUnit editingUnit, bool exitEditingMode) { return default(bool); } public DataGrid() { } public static System.Collections.ObjectModel.Collection<DataGridColumn> GenerateColumns(System.ComponentModel.IItemProperties itemProperties) { Contract.Ensures(Contract.Result<System.Collections.ObjectModel.Collection<System.Windows.Controls.DataGridColumn>>() != null); return default(System.Collections.ObjectModel.Collection<DataGridColumn>); } protected override System.Windows.DependencyObject GetContainerForItemOverride() { return default(System.Windows.DependencyObject); } public System.Windows.Visibility GetDetailsVisibilityForItem(Object item) { return default(System.Windows.Visibility); } protected override bool IsItemItsOwnContainerOverride(Object item) { return default(bool); } protected override System.Windows.Size MeasureOverride(System.Windows.Size availableSize) { return default(System.Windows.Size); } public override void OnApplyTemplate() { } protected virtual new void OnAutoGeneratedColumns(EventArgs e) { } protected virtual new void OnAutoGeneratingColumn(DataGridAutoGeneratingColumnEventArgs e) { } protected virtual new void OnBeginningEdit(DataGridBeginningEditEventArgs e) { } protected virtual new void OnCanExecuteBeginEdit(System.Windows.Input.CanExecuteRoutedEventArgs e) { Contract.Requires(e != null); } protected virtual new void OnCanExecuteCancelEdit(System.Windows.Input.CanExecuteRoutedEventArgs e) { Contract.Requires(e != null); } protected virtual new void OnCanExecuteCommitEdit(System.Windows.Input.CanExecuteRoutedEventArgs e) { Contract.Requires(e != null); } protected virtual new void OnCanExecuteCopy(System.Windows.Input.CanExecuteRoutedEventArgs args) { Contract.Requires(args != null); } protected virtual new void OnCanExecuteDelete(System.Windows.Input.CanExecuteRoutedEventArgs e) { Contract.Requires(e != null); } protected virtual new void OnCellEditEnding(DataGridCellEditEndingEventArgs e) { } protected internal virtual new void OnColumnDisplayIndexChanged(DataGridColumnEventArgs e) { } protected internal virtual new void OnColumnHeaderDragCompleted(System.Windows.Controls.Primitives.DragCompletedEventArgs e) { } protected internal virtual new void OnColumnHeaderDragDelta(System.Windows.Controls.Primitives.DragDeltaEventArgs e) { } protected internal virtual new void OnColumnHeaderDragStarted(System.Windows.Controls.Primitives.DragStartedEventArgs e) { } protected internal virtual new void OnColumnReordered(DataGridColumnEventArgs e) { } protected internal virtual new void OnColumnReordering(DataGridColumnReorderingEventArgs e) { } protected override void OnContextMenuOpening(ContextMenuEventArgs e) { } protected virtual new void OnCopyingRowClipboardContent(DataGridRowClipboardEventArgs args) { Contract.Requires(args != null); } protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer() { return default(System.Windows.Automation.Peers.AutomationPeer); } protected virtual new void OnCurrentCellChanged(EventArgs e) { } protected virtual new void OnExecutedBeginEdit(System.Windows.Input.ExecutedRoutedEventArgs e) { } protected virtual new void OnExecutedCancelEdit(System.Windows.Input.ExecutedRoutedEventArgs e) { Contract.Requires(e != null); } protected virtual new void OnExecutedCommitEdit(System.Windows.Input.ExecutedRoutedEventArgs e) { Contract.Requires(e != null); } protected virtual new void OnExecutedCopy(System.Windows.Input.ExecutedRoutedEventArgs args) { Contract.Requires(args != null); } protected virtual new void OnExecutedDelete(System.Windows.Input.ExecutedRoutedEventArgs e) { } protected virtual new void OnInitializingNewItem(InitializingNewItemEventArgs e) { } protected override void OnIsMouseCapturedChanged(System.Windows.DependencyPropertyChangedEventArgs e) { } protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { } protected override void OnItemsSourceChanged(System.Collections.IEnumerable oldValue, System.Collections.IEnumerable newValue) { } protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e) { } protected virtual new void OnLoadingRow(DataGridRowEventArgs e) { Contract.Requires(e != null); Contract.Requires(e.Row != null); } protected virtual new void OnLoadingRowDetails(DataGridRowDetailsEventArgs e) { } protected override void OnMouseMove(System.Windows.Input.MouseEventArgs e) { } protected internal virtual new void OnPreparingCellForEdit(DataGridPreparingCellForEditEventArgs e) { } protected internal virtual new void OnRowDetailsVisibilityChanged(DataGridRowDetailsEventArgs e) { Contract.Requires(e != null); } protected virtual new void OnRowEditEnding(DataGridRowEditEndingEventArgs e) { } protected virtual new void OnSelectedCellsChanged(SelectedCellsChangedEventArgs e) { } protected override void OnSelectionChanged(SelectionChangedEventArgs e) { } protected virtual new void OnSorting(DataGridSortingEventArgs eventArgs) { Contract.Requires(eventArgs != null); } protected override void OnTemplateChanged(ControlTemplate oldTemplate, ControlTemplate newTemplate) { } protected virtual new void OnUnloadingRow(DataGridRowEventArgs e) { Contract.Requires(e != null); } protected virtual new void OnUnloadingRowDetails(DataGridRowDetailsEventArgs e) { } protected override void PrepareContainerForItemOverride(System.Windows.DependencyObject element, Object item) { } public void ScrollIntoView(Object item) { } public void ScrollIntoView(Object item, DataGridColumn column) { } public void SelectAllCells() { } public void SetDetailsVisibilityForItem(Object item, System.Windows.Visibility detailsVisibility) { } public void UnselectAllCells() { } #endregion #region Properties and indexers public System.Windows.Media.Brush AlternatingRowBackground { get { return default(System.Windows.Media.Brush); } set { } } public bool AreRowDetailsFrozen { get { return default(bool); } set { } } public bool AutoGenerateColumns { get { return default(bool); } set { } } public bool CanUserAddRows { get { return default(bool); } set { } } public bool CanUserDeleteRows { get { return default(bool); } set { } } public bool CanUserReorderColumns { get { return default(bool); } set { } } public bool CanUserResizeColumns { get { return default(bool); } set { } } public bool CanUserResizeRows { get { return default(bool); } set { } } public bool CanUserSortColumns { get { return default(bool); } set { } } public double CellsPanelHorizontalOffset { get { return default(double); } private set { } } public System.Windows.Style CellStyle { get { return default(System.Windows.Style); } set { } } public DataGridClipboardCopyMode ClipboardCopyMode { get { return default(DataGridClipboardCopyMode); } set { } } public double ColumnHeaderHeight { get { return default(double); } set { } } public System.Windows.Style ColumnHeaderStyle { get { return default(System.Windows.Style); } set { } } public System.Collections.ObjectModel.ObservableCollection<DataGridColumn> Columns { get { Contract.Ensures(Contract.Result<System.Collections.ObjectModel.ObservableCollection<DataGridColumn>>() != null); return default(System.Collections.ObjectModel.ObservableCollection<DataGridColumn>); } } public DataGridLength ColumnWidth { get { return default(DataGridLength); } set { } } public DataGridCellInfo CurrentCell { get { return default(DataGridCellInfo); } set { } } public DataGridColumn CurrentColumn { get { return default(DataGridColumn); } set { } } public Object CurrentItem { get { return default(Object); } set { } } public static System.Windows.Input.RoutedUICommand DeleteCommand { get { Contract.Ensures(Contract.Result<System.Windows.Input.RoutedUICommand>() == System.Windows.Input.ApplicationCommands.Delete); return default(System.Windows.Input.RoutedUICommand); } } public System.Windows.Style DragIndicatorStyle { get { return default(System.Windows.Style); } set { } } public System.Windows.Style DropLocationIndicatorStyle { get { return default(System.Windows.Style); } set { } } public bool EnableColumnVirtualization { get { return default(bool); } set { } } public bool EnableRowVirtualization { get { return default(bool); } set { } } public static System.Windows.ComponentResourceKey FocusBorderBrushKey { get { Contract.Ensures(Contract.Result<System.Windows.ComponentResourceKey>() != null); return default(System.Windows.ComponentResourceKey); } } public int FrozenColumnCount { get { return default(int); } set { } } public DataGridGridLinesVisibility GridLinesVisibility { get { return default(DataGridGridLinesVisibility); } set { } } internal protected override bool HandlesScrolling { get { return default(bool); } } public DataGridHeadersVisibility HeadersVisibility { get { return default(DataGridHeadersVisibility); } set { } } public static System.Windows.Data.IValueConverter HeadersVisibilityConverter { get { Contract.Ensures(Contract.Result<System.Windows.Data.IValueConverter>() != null); return default(System.Windows.Data.IValueConverter); } } public System.Windows.Media.Brush HorizontalGridLinesBrush { get { return default(System.Windows.Media.Brush); } set { } } public ScrollBarVisibility HorizontalScrollBarVisibility { get { return default(ScrollBarVisibility); } set { } } public bool IsReadOnly { get { return default(bool); } set { } } public double MaxColumnWidth { get { return default(double); } set { } } public double MinColumnWidth { get { return default(double); } set { } } public double MinRowHeight { get { return default(double); } set { } } public double NonFrozenColumnsViewportHorizontalOffset { get { return default(double); } internal set { } } public System.Windows.Media.Brush RowBackground { get { return default(System.Windows.Media.Brush); } set { } } public static System.Windows.Data.IValueConverter RowDetailsScrollingConverter { get { Contract.Ensures(Contract.Result<System.Windows.Data.IValueConverter>() != null); return default(System.Windows.Data.IValueConverter); } } public System.Windows.DataTemplate RowDetailsTemplate { get { return default(System.Windows.DataTemplate); } set { } } public DataTemplateSelector RowDetailsTemplateSelector { get { return default(DataTemplateSelector); } set { } } public DataGridRowDetailsVisibilityMode RowDetailsVisibilityMode { get { return default(DataGridRowDetailsVisibilityMode); } set { } } public double RowHeaderActualWidth { get { return default(double); } internal set { } } public System.Windows.Style RowHeaderStyle { get { return default(System.Windows.Style); } set { } } public System.Windows.DataTemplate RowHeaderTemplate { get { return default(System.Windows.DataTemplate); } set { } } public DataTemplateSelector RowHeaderTemplateSelector { get { return default(DataTemplateSelector); } set { } } public double RowHeaderWidth { get { return default(double); } set { } } public double RowHeight { get { return default(double); } set { } } public System.Windows.Style RowStyle { get { return default(System.Windows.Style); } set { } } public StyleSelector RowStyleSelector { get { return default(StyleSelector); } set { } } public ControlTemplate RowValidationErrorTemplate { get { return default(ControlTemplate); } set { } } public System.Collections.ObjectModel.ObservableCollection<ValidationRule> RowValidationRules { get { return default(System.Collections.ObjectModel.ObservableCollection<ValidationRule>); } } public static System.Windows.Input.RoutedUICommand SelectAllCommand { get { Contract.Ensures(Contract.Result<System.Windows.Input.RoutedUICommand>() == System.Windows.Input.ApplicationCommands.SelectAll); return default(System.Windows.Input.RoutedUICommand); } } public IList<DataGridCellInfo> SelectedCells { get { return default(IList<DataGridCellInfo>); } } public DataGridSelectionMode SelectionMode { get { return default(DataGridSelectionMode); } set { } } public DataGridSelectionUnit SelectionUnit { get { return default(DataGridSelectionUnit); } set { } } public System.Windows.Media.Brush VerticalGridLinesBrush { get { return default(System.Windows.Media.Brush); } set { } } public ScrollBarVisibility VerticalScrollBarVisibility { get { return default(ScrollBarVisibility); } set { } } #endregion #region Events public event EventHandler AutoGeneratedColumns { add { } remove { } } public event EventHandler<DataGridAutoGeneratingColumnEventArgs> AutoGeneratingColumn { add { } remove { } } public event EventHandler<DataGridBeginningEditEventArgs> BeginningEdit { add { } remove { } } public event EventHandler<DataGridCellEditEndingEventArgs> CellEditEnding { add { } remove { } } public event EventHandler<DataGridColumnEventArgs> ColumnDisplayIndexChanged { add { } remove { } } public event EventHandler<System.Windows.Controls.Primitives.DragCompletedEventArgs> ColumnHeaderDragCompleted { add { } remove { } } public event EventHandler<System.Windows.Controls.Primitives.DragDeltaEventArgs> ColumnHeaderDragDelta { add { } remove { } } public event EventHandler<System.Windows.Controls.Primitives.DragStartedEventArgs> ColumnHeaderDragStarted { add { } remove { } } public event EventHandler<DataGridColumnEventArgs> ColumnReordered { add { } remove { } } public event EventHandler<DataGridColumnReorderingEventArgs> ColumnReordering { add { } remove { } } public event EventHandler<DataGridRowClipboardEventArgs> CopyingRowClipboardContent { add { } remove { } } public event EventHandler<EventArgs> CurrentCellChanged { add { } remove { } } public event InitializingNewItemEventHandler InitializingNewItem { add { } remove { } } public event EventHandler<DataGridRowEventArgs> LoadingRow { add { } remove { } } public event EventHandler<DataGridRowDetailsEventArgs> LoadingRowDetails { add { } remove { } } public event EventHandler<DataGridPreparingCellForEditEventArgs> PreparingCellForEdit { add { } remove { } } public event EventHandler<DataGridRowDetailsEventArgs> RowDetailsVisibilityChanged { add { } remove { } } public event EventHandler<DataGridRowEditEndingEventArgs> RowEditEnding { add { } remove { } } public event SelectedCellsChangedEventHandler SelectedCellsChanged { add { } remove { } } public event DataGridSortingEventHandler Sorting { add { } remove { } } public event EventHandler<DataGridRowEventArgs> UnloadingRow { add { } remove { } } public event EventHandler<DataGridRowDetailsEventArgs> UnloadingRowDetails { add { } remove { } } #endregion #region Fields public readonly static System.Windows.DependencyProperty AlternatingRowBackgroundProperty; public readonly static System.Windows.DependencyProperty AreRowDetailsFrozenProperty; public readonly static System.Windows.DependencyProperty AutoGenerateColumnsProperty; public readonly static System.Windows.Input.RoutedCommand BeginEditCommand; public readonly static System.Windows.Input.RoutedCommand CancelEditCommand; public readonly static System.Windows.DependencyProperty CanUserAddRowsProperty; public readonly static System.Windows.DependencyProperty CanUserDeleteRowsProperty; public readonly static System.Windows.DependencyProperty CanUserReorderColumnsProperty; public readonly static System.Windows.DependencyProperty CanUserResizeColumnsProperty; public readonly static System.Windows.DependencyProperty CanUserResizeRowsProperty; public readonly static System.Windows.DependencyProperty CanUserSortColumnsProperty; public readonly static System.Windows.DependencyProperty CellsPanelHorizontalOffsetProperty; public readonly static System.Windows.DependencyProperty CellStyleProperty; public readonly static System.Windows.DependencyProperty ClipboardCopyModeProperty; public readonly static System.Windows.DependencyProperty ColumnHeaderHeightProperty; public readonly static System.Windows.DependencyProperty ColumnHeaderStyleProperty; public readonly static System.Windows.DependencyProperty ColumnWidthProperty; public readonly static System.Windows.Input.RoutedCommand CommitEditCommand; public readonly static System.Windows.DependencyProperty CurrentCellProperty; public readonly static System.Windows.DependencyProperty CurrentColumnProperty; public readonly static System.Windows.DependencyProperty CurrentItemProperty; public readonly static System.Windows.DependencyProperty DragIndicatorStyleProperty; public readonly static System.Windows.DependencyProperty DropLocationIndicatorStyleProperty; public readonly static System.Windows.DependencyProperty EnableColumnVirtualizationProperty; public readonly static System.Windows.DependencyProperty EnableRowVirtualizationProperty; public readonly static System.Windows.DependencyProperty FrozenColumnCountProperty; public readonly static System.Windows.DependencyProperty GridLinesVisibilityProperty; public readonly static System.Windows.DependencyProperty HeadersVisibilityProperty; public readonly static System.Windows.DependencyProperty HorizontalGridLinesBrushProperty; public readonly static System.Windows.DependencyProperty HorizontalScrollBarVisibilityProperty; public readonly static System.Windows.DependencyProperty IsReadOnlyProperty; public readonly static System.Windows.DependencyProperty MaxColumnWidthProperty; public readonly static System.Windows.DependencyProperty MinColumnWidthProperty; public readonly static System.Windows.DependencyProperty MinRowHeightProperty; public readonly static System.Windows.DependencyProperty NonFrozenColumnsViewportHorizontalOffsetProperty; public readonly static System.Windows.DependencyProperty RowBackgroundProperty; public readonly static System.Windows.DependencyProperty RowDetailsTemplateProperty; public readonly static System.Windows.DependencyProperty RowDetailsTemplateSelectorProperty; public readonly static System.Windows.DependencyProperty RowDetailsVisibilityModeProperty; public readonly static System.Windows.DependencyProperty RowHeaderActualWidthProperty; public readonly static System.Windows.DependencyProperty RowHeaderStyleProperty; public readonly static System.Windows.DependencyProperty RowHeaderTemplateProperty; public readonly static System.Windows.DependencyProperty RowHeaderTemplateSelectorProperty; public readonly static System.Windows.DependencyProperty RowHeaderWidthProperty; public readonly static System.Windows.DependencyProperty RowHeightProperty; public readonly static System.Windows.DependencyProperty RowStyleProperty; public readonly static System.Windows.DependencyProperty RowStyleSelectorProperty; public readonly static System.Windows.DependencyProperty RowValidationErrorTemplateProperty; public readonly static System.Windows.DependencyProperty SelectionModeProperty; public readonly static System.Windows.DependencyProperty SelectionUnitProperty; public readonly static System.Windows.DependencyProperty VerticalGridLinesBrushProperty; public readonly static System.Windows.DependencyProperty VerticalScrollBarVisibilityProperty; #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Authorization { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; /// <summary> /// ProviderOperationsMetadataOperations operations. /// </summary> internal partial class ProviderOperationsMetadataOperations : IServiceOperations<AuthorizationManagementClient>, IProviderOperationsMetadataOperations { /// <summary> /// Initializes a new instance of the ProviderOperationsMetadataOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ProviderOperationsMetadataOperations(AuthorizationManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AuthorizationManagementClient /// </summary> public AuthorizationManagementClient Client { get; private set; } /// <summary> /// Gets provider operations metadata for the specified resource provider. /// </summary> /// <param name='resourceProviderNamespace'> /// The namespace of the resource provider. /// </param> /// <param name='apiVersion'> /// The API version to use for the operation. /// </param> /// <param name='expand'> /// Specifies whether to expand the values. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ProviderOperationsMetadata>> GetWithHttpMessagesAsync(string resourceProviderNamespace, string apiVersion, string expand = "resourceTypes", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceProviderNamespace == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceProviderNamespace"); } if (apiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "apiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}").ToString(); _url = _url.Replace("{resourceProviderNamespace}", Uri.EscapeDataString(resourceProviderNamespace)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ProviderOperationsMetadata>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<ProviderOperationsMetadata>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets provider operations metadata for all resource providers. /// </summary> /// <param name='apiVersion'> /// The API version to use for this operation. /// </param> /// <param name='expand'> /// Specifies whether to expand the values. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ProviderOperationsMetadata>>> ListWithHttpMessagesAsync(string apiVersion, string expand = "resourceTypes", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (apiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "apiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Authorization/providerOperations").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ProviderOperationsMetadata>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<ProviderOperationsMetadata>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets provider operations metadata for all resource providers. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ProviderOperationsMetadata>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ProviderOperationsMetadata>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<ProviderOperationsMetadata>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Cursor; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.UserInterface; using osu.Framework.Input.Events; using osu.Game.Graphics; using osu.Game.Graphics.UserInterface; using osu.Game.Tournament.Components; using osu.Game.Tournament.Models; using osu.Game.Tournament.Screens.Editors; using osuTK; using osuTK.Graphics; using osuTK.Input; namespace osu.Game.Tournament.Screens.Ladder.Components { public class DrawableMatchTeam : DrawableTournamentTeam, IHasContextMenu { private readonly TournamentMatch match; private readonly bool losers; private TournamentSpriteText scoreText; private Box background; private Box backgroundRight; private readonly Bindable<int?> score = new Bindable<int?>(); private readonly BindableBool completed = new BindableBool(); private Color4 colourWinner; private readonly Func<bool> isWinner; private LadderEditorScreen ladderEditor; [Resolved(canBeNull: true)] private LadderInfo ladderInfo { get; set; } private void setCurrent() { if (ladderInfo == null) return; //todo: tournamentgamebase? if (ladderInfo.CurrentMatch.Value != null) ladderInfo.CurrentMatch.Value.Current.Value = false; ladderInfo.CurrentMatch.Value = match; ladderInfo.CurrentMatch.Value.Current.Value = true; } [Resolved(CanBeNull = true)] private LadderEditorInfo editorInfo { get; set; } public DrawableMatchTeam(TournamentTeam team, TournamentMatch match, bool losers) : base(team) { this.match = match; this.losers = losers; Size = new Vector2(150, 40); Flag.Scale = new Vector2(0.9f); Flag.Anchor = Flag.Origin = Anchor.CentreLeft; AcronymText.Anchor = AcronymText.Origin = Anchor.CentreLeft; AcronymText.Padding = new MarginPadding { Left = 50 }; AcronymText.Font = OsuFont.Torus.With(size: 22, weight: FontWeight.Bold); if (match != null) { isWinner = () => match.Winner == Team; completed.BindTo(match.Completed); if (team != null) score.BindTo(team == match.Team1.Value ? match.Team1Score : match.Team2Score); } } [BackgroundDependencyLoader(true)] private void load(OsuColour colours, LadderEditorScreen ladderEditor) { this.ladderEditor = ladderEditor; colourWinner = losers ? Color4Extensions.FromHex("#8E7F48") : Color4Extensions.FromHex("#1462AA"); InternalChildren = new Drawable[] { background = new Box { RelativeSizeAxes = Axes.Both, }, new Container { Padding = new MarginPadding(5), RelativeSizeAxes = Axes.Both, Children = new Drawable[] { AcronymText, Flag, } }, new Container { Masking = true, Width = 0.3f, Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, RelativeSizeAxes = Axes.Both, Children = new Drawable[] { backgroundRight = new Box { Colour = OsuColour.Gray(0.1f), Alpha = 0.8f, RelativeSizeAxes = Axes.Both, }, scoreText = new TournamentSpriteText { Anchor = Anchor.Centre, Origin = Anchor.Centre, Font = OsuFont.Torus.With(size: 22), } } } }; completed.BindValueChanged(_ => updateWinStyle()); score.BindValueChanged(val => { scoreText.Text = val.NewValue?.ToString() ?? string.Empty; updateWinStyle(); }, true); } protected override bool OnClick(ClickEvent e) { if (Team == null || editorInfo != null) return false; if (!match.Current.Value) { setCurrent(); return true; } if (e.Button == MouseButton.Left) { if (score.Value == null) { match.StartMatch(); } else if (!match.Completed.Value) score.Value++; } else { if (match.Progression.Value?.Completed.Value == true) // don't allow changing scores if the match has a progression. can cause large data loss return false; if (match.Completed.Value && match.Winner != Team) // don't allow changing scores from the non-winner return false; if (score.Value > 0) score.Value--; else match.CancelMatchStart(); } return false; } private void updateWinStyle() { bool winner = completed.Value && isWinner?.Invoke() == true; background.FadeColour(winner ? Color4.White : Color4Extensions.FromHex("#444"), winner ? 500 : 0, Easing.OutQuint); backgroundRight.FadeColour(winner ? colourWinner : Color4Extensions.FromHex("#333"), winner ? 500 : 0, Easing.OutQuint); AcronymText.Colour = winner ? Color4.Black : Color4.White; scoreText.Font = scoreText.Font.With(weight: winner ? FontWeight.Bold : FontWeight.Regular); } public MenuItem[] ContextMenuItems { get { if (editorInfo == null) return Array.Empty<MenuItem>(); return new MenuItem[] { new OsuMenuItem("Set as current", MenuItemType.Standard, setCurrent), new OsuMenuItem("Join with", MenuItemType.Standard, () => ladderEditor.BeginJoin(match, false)), new OsuMenuItem("Join with (loser)", MenuItemType.Standard, () => ladderEditor.BeginJoin(match, true)), new OsuMenuItem("Remove", MenuItemType.Destructive, () => ladderEditor.Remove(match)), }; } } } }
using System; using System.Collections.Generic; using System.Linq; using Moq; using NuGet.Test.Mocks; using Xunit; namespace NuGet.Test { public class PackageRepositoryTest { [Fact] public void FindByIdReturnsPackage() { // Arrange var repo = GetLocalRepository(); // Act var package = repo.FindPackage(packageId: "A"); // Assert Assert.NotNull(package); Assert.Equal("A", package.Id); } [Fact] public void FindByIdReturnsNullWhenPackageNotFound() { // Arrange var repo = GetLocalRepository(); // Act var package = repo.FindPackage(packageId: "X"); // Assert Assert.Null(package); } [Fact] public void FindByIdAndVersionReturnsPackage() { // Arrange var repo = GetRemoteRepository(); // Act var package = repo.FindPackage(packageId: "A", version: SemanticVersion.Parse("1.0")); // Assert Assert.NotNull(package); Assert.Equal("A", package.Id); Assert.Equal(SemanticVersion.Parse("1.0"), package.Version); } [Fact] public void FindByIdAndVersionReturnsNullWhenPackageNotFound() { // Arrange var repo = GetLocalRepository(); // Act var package1 = repo.FindPackage(packageId: "X", version: SemanticVersion.Parse("1.0")); var package2 = repo.FindPackage(packageId: "A", version: SemanticVersion.Parse("1.1")); // Assert Assert.Null(package1 ?? package2); } [Fact] public void FindByIdAndVersionRangeReturnsPackage() { // Arrange var repo = GetRemoteRepository(); var versionSpec = VersionUtility.ParseVersionSpec("[0.9, 1.1]"); // Act var package = repo.FindPackage("A", versionSpec, allowPrereleaseVersions: false, allowUnlisted: true); // Assert Assert.NotNull(package); Assert.Equal("A", package.Id); Assert.Equal(SemanticVersion.Parse("1.0"), package.Version); } [Fact] public void FindByIdAndVersionRangeReturnsNullWhenPackageNotFound() { // Arrange var repo = GetLocalRepository(); var versionSpec = VersionUtility.ParseVersionSpec("[0.9, 1.1]"); // Act var package1 = repo.FindPackage("X", VersionUtility.ParseVersionSpec("[0.9, 1.1]"), allowPrereleaseVersions: false, allowUnlisted: true); var package2 = repo.FindPackage("A", VersionUtility.ParseVersionSpec("[1.4, 1.5]"), allowPrereleaseVersions: false, allowUnlisted: true); // Assert Assert.Null(package1 ?? package2); } [Fact] public void FindPackageByIdVersionAndVersionRangesUsesRangeIfExactVersionIsNull() { // Arrange var repo = GetRemoteRepository(); // Act var package = repo.FindPackage("A", VersionUtility.ParseVersionSpec("[0.6, 1.1.5]"), allowPrereleaseVersions: false, allowUnlisted: true); // Assert Assert.NotNull(package); Assert.Equal("A", package.Id); Assert.Equal(SemanticVersion.Parse("1.0"), package.Version); } [Fact] public void FindPackagesReturnsPackagesWithTermInPackageTagOrDescriptionOrId() { // Arrange var term = "TAG"; var repo = new MockPackageRepository(); repo.Add(CreateMockPackage("A", "1.0", "Description", " TAG ")); repo.Add(CreateMockPackage("B", "2.0", "Description", "Tags")); repo.Add(CreateMockPackage("C", "1.0", "This description has tags in it")); repo.Add(CreateMockPackage("D", "1.0", "Description")); repo.Add(CreateMockPackage("TagCloud", "1.0", "Description")); // Act var packages = repo.GetPackages().Find(term).ToList(); // Assert Assert.Equal(3, packages.Count); Assert.Equal("A", packages[0].Id); Assert.Equal("C", packages[1].Id); Assert.Equal("TagCloud", packages[2].Id); } [Fact] public void FindPackagesReturnsPrereleasePackagesIfTheFlagIsSetToTrue() { // Arrange var term = "B"; var repo = GetRemoteRepository(includePrerelease: true); // Act var packages = repo.GetPackages().Find(term); // Assert Assert.Equal(packages.Count(), 2); packages = packages.OrderBy(p => p.Id); Assert.Equal(packages.ElementAt(0).Id, "B"); Assert.Equal(packages.ElementAt(0).Version, new SemanticVersion("1.0")); Assert.Equal(packages.ElementAt(1).Id, "B"); Assert.Equal(packages.ElementAt(1).Version, new SemanticVersion("1.0-beta")); } [Fact] public void FindPackagesReturnsPackagesWithTerm() { // Arrange var term = "B xaml"; var repo = GetRemoteRepository(); // Act var packages = repo.GetPackages().Find(term); // Assert Assert.Equal(packages.Count(), 2); packages = packages.OrderBy(p => p.Id); Assert.Equal(packages.ElementAt(0).Id, "B"); Assert.Equal(packages.ElementAt(1).Id, "C"); } [Fact] public void FindPackagesReturnsEmptyCollectionWhenNoPackageContainsTerm() { // Arrange var term = "does-not-exist"; var repo = GetRemoteRepository(); // Act var packages = repo.GetPackages().Find(term); // Assert Assert.False(packages.Any()); } [Fact] public void FindPackagesReturnsAllPackagesWhenSearchTermIsNullOrEmpty() { // Arrange var repo = GetLocalRepository(); // Act var packages1 = repo.GetPackages().Find(String.Empty); var packages2 = repo.GetPackages().Find(null); var packages3 = repo.GetPackages(); // Assert Assert.Equal(packages1.ToList(), packages2.ToList()); Assert.Equal(packages2.ToList(), packages3.ToList()); } [Fact] public void SearchUsesInterfaceIfImplementedByRepository() { // Arrange var repo = new Mock<MockPackageRepository>(MockBehavior.Strict); repo.Setup(m => m.GetPackages()).Returns(Enumerable.Empty<IPackage>().AsQueryable()); repo.As<ISearchableRepository>().Setup(m => m.Search(It.IsAny<string>(), It.IsAny<IEnumerable<string>>(), false)) .Returns(new[] { PackageUtility.CreatePackage("A") }.AsQueryable()); // Act var packages = repo.Object.Search("Hello", new[] { ".NETFramework" }, allowPrereleaseVersions: false).ToList(); // Assert Assert.Equal(1, packages.Count); Assert.Equal("A", packages[0].Id); } [Fact] public void GetUpdatesReturnsPackagesWithUpdates() { // Arrange var localRepo = GetLocalRepository(); var remoteRepo = GetRemoteRepository(); // Act var packages = remoteRepo.GetUpdates(localRepo.GetPackages(), includePrerelease: false, includeAllVersions: false); // Assert Assert.True(packages.Any()); Assert.Equal(packages.First().Id, "A"); Assert.Equal(packages.First().Version, SemanticVersion.Parse("1.2")); } [Fact] public void GetUpdatesReturnsEmptyCollectionWhenSourceRepositoryIsEmpty() { // Arrange var localRepo = GetLocalRepository(); var remoteRepo = GetEmptyRepository(); // Act var packages = remoteRepo.GetUpdates(localRepo.GetPackages(), includePrerelease: false, includeAllVersions: false); // Assert Assert.False(packages.Any()); } [Fact] public void FindDependencyPicksHighestVersionIfNotSpecified() { // Arrange var repository = new MockPackageRepository() { PackageUtility.CreatePackage("B", "2.0"), PackageUtility.CreatePackage("B", "1.0"), PackageUtility.CreatePackage("B", "1.0.1"), PackageUtility.CreatePackage("B", "1.0.9"), PackageUtility.CreatePackage("B", "1.1") }; var dependency = new PackageDependency("B"); // Act IPackage package = repository.ResolveDependency(dependency, allowPrereleaseVersions: false, preferListedPackages: false); // Assert Assert.Equal("B", package.Id); Assert.Equal(new SemanticVersion("2.0"), package.Version); } [Fact] public void FindPackageNormalizesVersionBeforeComparing() { // Arrange var repository = new MockPackageRepository() { PackageUtility.CreatePackage("B", "1.0.0"), PackageUtility.CreatePackage("B", "1.0.0.1") }; // Act IPackage package = repository.FindPackage("B", new SemanticVersion("1.0")); // Assert Assert.Equal("B", package.Id); Assert.Equal(new SemanticVersion("1.0.0"), package.Version); } [Fact] public void FindDependencyPicksLowestMajorAndMinorVersionButHighestBuildAndRevision() { // Arrange var repository = new MockPackageRepository() { PackageUtility.CreatePackage("B", "2.0"), PackageUtility.CreatePackage("B", "1.0"), PackageUtility.CreatePackage("B", "1.0.1"), PackageUtility.CreatePackage("B", "1.0.9"), PackageUtility.CreatePackage("B", "1.1") }; // B >= 1.0 PackageDependency dependency1 = PackageDependency.CreateDependency("B", "1.0"); // B >= 1.0.0 PackageDependency dependency2 = PackageDependency.CreateDependency("B", "1.0.0"); // B >= 1.0.0.0 PackageDependency dependency3 = PackageDependency.CreateDependency("B", "1.0.0.0"); // B = 1.0 PackageDependency dependency4 = PackageDependency.CreateDependency("B", "[1.0]"); // B >= 1.0.0 && <= 1.0.8 PackageDependency dependency5 = PackageDependency.CreateDependency("B", "[1.0.0, 1.0.8]"); // Act IPackage package1 = repository.ResolveDependency(dependency1, allowPrereleaseVersions: false, preferListedPackages: false); IPackage package2 = repository.ResolveDependency(dependency2, allowPrereleaseVersions: false, preferListedPackages: false); IPackage package3 = repository.ResolveDependency(dependency3, allowPrereleaseVersions: false, preferListedPackages: false); IPackage package4 = repository.ResolveDependency(dependency4, allowPrereleaseVersions: false, preferListedPackages: false); IPackage package5 = repository.ResolveDependency(dependency5, allowPrereleaseVersions: false, preferListedPackages: false); // Assert Assert.Equal("B", package1.Id); Assert.Equal(new SemanticVersion("1.0.9"), package1.Version); Assert.Equal("B", package2.Id); Assert.Equal(new SemanticVersion("1.0.9"), package2.Version); Assert.Equal("B", package3.Id); Assert.Equal(new SemanticVersion("1.0.9"), package3.Version); Assert.Equal("B", package4.Id); Assert.Equal(new SemanticVersion("1.0"), package4.Version); Assert.Equal("B", package5.Id); Assert.Equal(new SemanticVersion("1.0.1"), package5.Version); } [Fact] public void ResolveSafeVersionReturnsNullIfPackagesNull() { // Act var package = PackageRepositoryExtensions.ResolveSafeVersion(null); // Assert Assert.Null(package); } [Fact] public void ResolveSafeVersionReturnsNullIfEmptyPackages() { // Act var package = PackageRepositoryExtensions.ResolveSafeVersion(Enumerable.Empty<IPackage>()); // Assert Assert.Null(package); } [Fact] public void ResolveSafeVersionReturnsHighestBuildAndRevisionWithLowestMajorAndMinor() { var packages = new[] { PackageUtility.CreatePackage("A", "0.9"), PackageUtility.CreatePackage("A", "0.9.3"), PackageUtility.CreatePackage("A", "1.0"), PackageUtility.CreatePackage("A", "1.0.2"), PackageUtility.CreatePackage("A", "1.0.12"), PackageUtility.CreatePackage("A", "1.0.13"), }; // Act var package = PackageRepositoryExtensions.ResolveSafeVersion(packages); // Assert Assert.NotNull(package); Assert.Equal("A", package.Id); Assert.Equal(new SemanticVersion("0.9.3"), package.Version); } private static IPackageRepository GetEmptyRepository() { Mock<IPackageRepository> repository = new Mock<IPackageRepository>(); repository.Setup(c => c.GetPackages()).Returns(() => Enumerable.Empty<IPackage>().AsQueryable()); return repository.Object; } private static IPackageRepository GetRemoteRepository(bool includePrerelease = false) { Mock<IPackageRepository> repository = new Mock<IPackageRepository>(); var packages = new List<IPackage> { CreateMockPackage("A", "1.0", "scripts style"), CreateMockPackage("B", "1.0", "testing"), CreateMockPackage("C", "2.0", "xaml"), CreateMockPackage("A", "1.2", "a updated desc") }; if (includePrerelease) { packages.Add(CreateMockPackage("A", "2.0-alpha", "a prerelease package")); packages.Add(CreateMockPackage("B", "1.0-beta", "another prerelease package")); } repository.Setup(c => c.GetPackages()).Returns(() => packages.AsQueryable()); return repository.Object; } private static IPackageRepository GetLocalRepository() { Mock<IPackageRepository> repository = new Mock<IPackageRepository>(); var packages = new[] { CreateMockPackage("A", "1.0"), CreateMockPackage("B", "1.0") }; repository.Setup(c => c.GetPackages()).Returns(() => packages.AsQueryable()); return repository.Object; } private static IPackage CreateMockPackage(string name, string version, string desc = null, string tags = null) { Mock<IPackage> package = new Mock<IPackage>(); package.SetupGet(p => p.Id).Returns(name); package.SetupGet(p => p.Version).Returns(SemanticVersion.Parse(version)); package.SetupGet(p => p.Description).Returns(desc); package.SetupGet(p => p.Tags).Returns(tags); package.SetupGet(p => p.Listed).Returns(true); return package.Object; } } }
// 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. /*============================================================ ** ** ** ** ** ** CustomAttributeBuilder is a helper class to help building custom attribute. ** ** ===========================================================*/ namespace System.Reflection.Emit { using System; using System.Reflection; using System.IO; using System.Text; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Globalization; using System.Diagnostics.Contracts; [HostProtection(MayLeakOnAbort = true)] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_CustomAttributeBuilder))] [System.Runtime.InteropServices.ComVisible(true)] public class CustomAttributeBuilder : _CustomAttributeBuilder { // public constructor to form the custom attribute with constructor and constructor // parameters. public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs) { InitCustomAttributeBuilder(con, constructorArgs, new PropertyInfo[]{}, new Object[]{}, new FieldInfo[]{}, new Object[]{}); } // public constructor to form the custom attribute with constructor, constructor // parameters and named properties. public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs, PropertyInfo[] namedProperties, Object[] propertyValues) { InitCustomAttributeBuilder(con, constructorArgs, namedProperties, propertyValues, new FieldInfo[]{}, new Object[]{}); } // public constructor to form the custom attribute with constructor and constructor // parameters. public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs, FieldInfo[] namedFields, Object[] fieldValues) { InitCustomAttributeBuilder(con, constructorArgs, new PropertyInfo[]{}, new Object[]{}, namedFields, fieldValues); } // public constructor to form the custom attribute with constructor and constructor // parameters. public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs, PropertyInfo[] namedProperties, Object[] propertyValues, FieldInfo[] namedFields, Object[] fieldValues) { InitCustomAttributeBuilder(con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues); } // Check that a type is suitable for use in a custom attribute. private bool ValidateType(Type t) { if (t.IsPrimitive || t == typeof(String) || t == typeof(Type)) return true; if (t.IsEnum) { switch (Type.GetTypeCode(Enum.GetUnderlyingType(t))) { case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: return true; default: return false; } } if (t.IsArray) { if (t.GetArrayRank() != 1) return false; return ValidateType(t.GetElementType()); } return t == typeof(Object); } internal void InitCustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs, PropertyInfo[] namedProperties, Object[] propertyValues, FieldInfo[] namedFields, Object[] fieldValues) { if (con == null) throw new ArgumentNullException("con"); if (constructorArgs == null) throw new ArgumentNullException("constructorArgs"); if (namedProperties == null) throw new ArgumentNullException("namedProperties"); if (propertyValues == null) throw new ArgumentNullException("propertyValues"); if (namedFields == null) throw new ArgumentNullException("namedFields"); if (fieldValues == null) throw new ArgumentNullException("fieldValues"); if (namedProperties.Length != propertyValues.Length) throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"), "namedProperties, propertyValues"); if (namedFields.Length != fieldValues.Length) throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"), "namedFields, fieldValues"); Contract.EndContractBlock(); if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static || (con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) throw new ArgumentException(Environment.GetResourceString("Argument_BadConstructor")); if ((con.CallingConvention & CallingConventions.Standard) != CallingConventions.Standard) throw new ArgumentException(Environment.GetResourceString("Argument_BadConstructorCallConv")); // Cache information used elsewhere. m_con = con; m_constructorArgs = new Object[constructorArgs.Length]; Array.Copy(constructorArgs, 0, m_constructorArgs, 0, constructorArgs.Length); Type[] paramTypes; int i; // Get the types of the constructor's formal parameters. paramTypes = con.GetParameterTypes(); // Since we're guaranteed a non-var calling convention, the number of arguments must equal the number of parameters. if (paramTypes.Length != constructorArgs.Length) throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterCountsForConstructor")); // Verify that the constructor has a valid signature (custom attributes only support a subset of our type system). for (i = 0; i < paramTypes.Length; i++) if (!ValidateType(paramTypes[i])) throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute")); // Now verify that the types of the actual parameters are compatible with the types of the formal parameters. for (i = 0; i < paramTypes.Length; i++) { if (constructorArgs[i] == null) continue; TypeCode paramTC = Type.GetTypeCode(paramTypes[i]); if (paramTC != Type.GetTypeCode(constructorArgs[i].GetType())) if (paramTC != TypeCode.Object || !ValidateType(constructorArgs[i].GetType())) throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForConstructor", i)); } // Allocate a memory stream to represent the CA blob in the metadata and a binary writer to help format it. MemoryStream stream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(stream); // Write the blob protocol version (currently 1). writer.Write((ushort)1); // Now emit the constructor argument values (no need for types, they're inferred from the constructor signature). for (i = 0; i < constructorArgs.Length; i++) EmitValue(writer, paramTypes[i], constructorArgs[i]); // Next a short with the count of properties and fields. writer.Write((ushort)(namedProperties.Length + namedFields.Length)); // Emit all the property sets. for (i = 0; i < namedProperties.Length; i++) { // Validate the property. if (namedProperties[i] == null) throw new ArgumentNullException("namedProperties[" + i + "]"); // Allow null for non-primitive types only. Type propType = namedProperties[i].PropertyType; if (propertyValues[i] == null && propType.IsPrimitive) throw new ArgumentNullException("propertyValues[" + i + "]"); // Validate property type. if (!ValidateType(propType)) throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute")); // Property has to be writable. if (!namedProperties[i].CanWrite) throw new ArgumentException(Environment.GetResourceString("Argument_NotAWritableProperty")); // Property has to be from the same class or base class as ConstructorInfo. if (namedProperties[i].DeclaringType != con.DeclaringType && (!(con.DeclaringType is TypeBuilderInstantiation)) && !con.DeclaringType.IsSubclassOf(namedProperties[i].DeclaringType)) { // Might have failed check because one type is a XXXBuilder // and the other is not. Deal with these special cases // separately. if (!TypeBuilder.IsTypeEqual(namedProperties[i].DeclaringType, con.DeclaringType)) { // IsSubclassOf is overloaded to do the right thing if // the constructor is a TypeBuilder, but we still need // to deal with the case where the property's declaring // type is one. if (!(namedProperties[i].DeclaringType is TypeBuilder) || !con.DeclaringType.IsSubclassOf(((TypeBuilder)namedProperties[i].DeclaringType).BakedRuntimeType)) throw new ArgumentException(Environment.GetResourceString("Argument_BadPropertyForConstructorBuilder")); } } // Make sure the property's type can take the given value. // Note that there will be no coersion. if (propertyValues[i] != null && propType != typeof(Object) && Type.GetTypeCode(propertyValues[i].GetType()) != Type.GetTypeCode(propType)) throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch")); // First a byte indicating that this is a property. writer.Write((byte)CustomAttributeEncoding.Property); // Emit the property type, name and value. EmitType(writer, propType); EmitString(writer, namedProperties[i].Name); EmitValue(writer, propType, propertyValues[i]); } // Emit all the field sets. for (i = 0; i < namedFields.Length; i++) { // Validate the field. if (namedFields[i] == null) throw new ArgumentNullException("namedFields[" + i + "]"); // Allow null for non-primitive types only. Type fldType = namedFields[i].FieldType; if (fieldValues[i] == null && fldType.IsPrimitive) throw new ArgumentNullException("fieldValues[" + i + "]"); // Validate field type. if (!ValidateType(fldType)) throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute")); // Field has to be from the same class or base class as ConstructorInfo. if (namedFields[i].DeclaringType != con.DeclaringType && (!(con.DeclaringType is TypeBuilderInstantiation)) && !con.DeclaringType.IsSubclassOf(namedFields[i].DeclaringType)) { // Might have failed check because one type is a XXXBuilder // and the other is not. Deal with these special cases // separately. if (!TypeBuilder.IsTypeEqual(namedFields[i].DeclaringType, con.DeclaringType)) { // IsSubclassOf is overloaded to do the right thing if // the constructor is a TypeBuilder, but we still need // to deal with the case where the field's declaring // type is one. if (!(namedFields[i].DeclaringType is TypeBuilder) || !con.DeclaringType.IsSubclassOf(((TypeBuilder)namedFields[i].DeclaringType).BakedRuntimeType)) throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldForConstructorBuilder")); } } // Make sure the field's type can take the given value. // Note that there will be no coersion. if (fieldValues[i] != null && fldType != typeof(Object) && Type.GetTypeCode(fieldValues[i].GetType()) != Type.GetTypeCode(fldType)) throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch")); // First a byte indicating that this is a field. writer.Write((byte)CustomAttributeEncoding.Field); // Emit the field type, name and value. EmitType(writer, fldType); EmitString(writer, namedFields[i].Name); EmitValue(writer, fldType, fieldValues[i]); } // Create the blob array. m_blob = ((MemoryStream)writer.BaseStream).ToArray(); } private void EmitType(BinaryWriter writer, Type type) { if (type.IsPrimitive) { switch (Type.GetTypeCode(type)) { case TypeCode.SByte: writer.Write((byte)CustomAttributeEncoding.SByte); break; case TypeCode.Byte: writer.Write((byte)CustomAttributeEncoding.Byte); break; case TypeCode.Char: writer.Write((byte)CustomAttributeEncoding.Char); break; case TypeCode.Boolean: writer.Write((byte)CustomAttributeEncoding.Boolean); break; case TypeCode.Int16: writer.Write((byte)CustomAttributeEncoding.Int16); break; case TypeCode.UInt16: writer.Write((byte)CustomAttributeEncoding.UInt16); break; case TypeCode.Int32: writer.Write((byte)CustomAttributeEncoding.Int32); break; case TypeCode.UInt32: writer.Write((byte)CustomAttributeEncoding.UInt32); break; case TypeCode.Int64: writer.Write((byte)CustomAttributeEncoding.Int64); break; case TypeCode.UInt64: writer.Write((byte)CustomAttributeEncoding.UInt64); break; case TypeCode.Single: writer.Write((byte)CustomAttributeEncoding.Float); break; case TypeCode.Double: writer.Write((byte)CustomAttributeEncoding.Double); break; default: Contract.Assert(false, "Invalid primitive type"); break; } } else if (type.IsEnum) { writer.Write((byte)CustomAttributeEncoding.Enum); EmitString(writer, type.AssemblyQualifiedName); } else if (type == typeof(String)) { writer.Write((byte)CustomAttributeEncoding.String); } else if (type == typeof(Type)) { writer.Write((byte)CustomAttributeEncoding.Type); } else if (type.IsArray) { writer.Write((byte)CustomAttributeEncoding.Array); EmitType(writer, type.GetElementType()); } else { // Tagged object case. writer.Write((byte)CustomAttributeEncoding.Object); } } private void EmitString(BinaryWriter writer, String str) { // Strings are emitted with a length prefix in a compressed format (1, 2 or 4 bytes) as used internally by metadata. byte[] utf8Str = Encoding.UTF8.GetBytes(str); uint length = (uint)utf8Str.Length; if (length <= 0x7f) { writer.Write((byte)length); } else if (length <= 0x3fff) { writer.Write((byte)((length >> 8) | 0x80)); writer.Write((byte)(length & 0xff)); } else { writer.Write((byte)((length >> 24) | 0xc0)); writer.Write((byte)((length >> 16) & 0xff)); writer.Write((byte)((length >> 8) & 0xff)); writer.Write((byte)(length & 0xff)); } writer.Write(utf8Str); } private void EmitValue(BinaryWriter writer, Type type, Object value) { if (type.IsEnum) { switch (Type.GetTypeCode(Enum.GetUnderlyingType(type))) { case TypeCode.SByte: writer.Write((sbyte)value); break; case TypeCode.Byte: writer.Write((byte)value); break; case TypeCode.Int16: writer.Write((short)value); break; case TypeCode.UInt16: writer.Write((ushort)value); break; case TypeCode.Int32: writer.Write((int)value); break; case TypeCode.UInt32: writer.Write((uint)value); break; case TypeCode.Int64: writer.Write((long)value); break; case TypeCode.UInt64: writer.Write((ulong)value); break; default: Contract.Assert(false, "Invalid enum base type"); break; } } else if (type == typeof(String)) { if (value == null) writer.Write((byte)0xff); else EmitString(writer, (String)value); } else if (type == typeof(Type)) { if (value == null) writer.Write((byte)0xff); else { String typeName = TypeNameBuilder.ToString((Type)value, TypeNameBuilder.Format.AssemblyQualifiedName); if (typeName == null) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeForCA", value.GetType())); EmitString(writer, typeName); } } else if (type.IsArray) { if (value == null) writer.Write((uint)0xffffffff); else { Array a = (Array)value; Type et = type.GetElementType(); writer.Write(a.Length); for (int i = 0; i < a.Length; i++) EmitValue(writer, et, a.GetValue(i)); } } else if (type.IsPrimitive) { switch (Type.GetTypeCode(type)) { case TypeCode.SByte: writer.Write((sbyte)value); break; case TypeCode.Byte: writer.Write((byte)value); break; case TypeCode.Char: writer.Write(Convert.ToUInt16((char)value)); break; case TypeCode.Boolean: writer.Write((byte)((bool)value ? 1 : 0)); break; case TypeCode.Int16: writer.Write((short)value); break; case TypeCode.UInt16: writer.Write((ushort)value); break; case TypeCode.Int32: writer.Write((int)value); break; case TypeCode.UInt32: writer.Write((uint)value); break; case TypeCode.Int64: writer.Write((long)value); break; case TypeCode.UInt64: writer.Write((ulong)value); break; case TypeCode.Single: writer.Write((float)value); break; case TypeCode.Double: writer.Write((double)value); break; default: Contract.Assert(false, "Invalid primitive type"); break; } } else if (type == typeof(object)) { // Tagged object case. Type instances aren't actually Type, they're some subclass (such as RuntimeType or // TypeBuilder), so we need to canonicalize this case back to Type. If we have a null value we follow the convention // used by C# and emit a null typed as a string (it doesn't really matter what type we pick as long as it's a // reference type). Type ot = value == null ? typeof(String) : value is Type ? typeof(Type) : value.GetType(); // value cannot be a "System.Object" object. // If we allow this we will get into an infinite recursion if (ot == typeof(object)) throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB", ot.ToString())); EmitType(writer, ot); EmitValue(writer, ot, value); } else { string typename = "null"; if (value != null) typename = value.GetType().ToString(); throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB", typename)); } } // return the byte interpretation of the custom attribute [System.Security.SecurityCritical] // auto-generated internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner) { CreateCustomAttribute(mod, tkOwner, mod.GetConstructorToken(m_con).Token, false); } //************************************************* // Upon saving to disk, we need to create the memberRef token for the custom attribute's type // first of all. So when we snap the in-memory module for on disk, this token will be there. // We also need to enforce the use of MemberRef. Because MemberDef token might move. // This function has to be called before we snap the in-memory module for on disk (i.e. Presave on // ModuleBuilder. //************************************************* [System.Security.SecurityCritical] // auto-generated internal int PrepareCreateCustomAttributeToDisk(ModuleBuilder mod) { return mod.InternalGetConstructorToken(m_con, true).Token; } //************************************************* // Call this function with toDisk=1, after on disk module has been snapped. //************************************************* [System.Security.SecurityCritical] // auto-generated internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner, int tkAttrib, bool toDisk) { TypeBuilder.DefineCustomAttribute(mod, tkOwner, tkAttrib, m_blob, toDisk, typeof(System.Diagnostics.DebuggableAttribute) == m_con.DeclaringType); } #if !FEATURE_CORECLR void _CustomAttributeBuilder.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _CustomAttributeBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _CustomAttributeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } void _CustomAttributeBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif internal ConstructorInfo m_con; internal Object[] m_constructorArgs; internal byte[] m_blob; } }
/* * 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; namespace Lucene.Net.Messages { /// <summary> MessageBundles classes extend this class, to implement a bundle. /// /// For Native Language Support (NLS), system of software internationalization. /// /// This interface is similar to the NLS class in eclipse.osgi.util.NLS class - /// initializeMessages() method resets the values of all static strings, should /// only be called by classes that extend from NLS (see TestMessages.java for /// reference) - performs validation of all message in a bundle, at class load /// time - performs per message validation at runtime - see NLSTest.java for /// usage reference /// /// MessageBundle classes may subclass this type. /// </summary> public class NLS { public interface IPriviligedAction { /// <summary> /// Performs the priviliged action. /// </summary> /// <returns>A value that may represent the result of the action.</returns> System.Object Run(); } private class AnonymousClassPrivilegedAction : IPriviligedAction { public AnonymousClassPrivilegedAction(System.Reflection.FieldInfo field) { InitBlock(field); } private void InitBlock(System.Reflection.FieldInfo field) { this.field = field; } private System.Reflection.FieldInfo field; public virtual System.Object Run() { // field.setAccessible(true); // {{Aroush-2.9}} java.lang.reflect.AccessibleObject.setAccessible return null; } } private static System.Collections.IDictionary bundles = new System.Collections.Hashtable(0); protected internal NLS() { // Do not instantiate } public static System.String GetLocalizedMessage(System.String key) { return GetLocalizedMessage(key, System.Threading.Thread.CurrentThread.CurrentCulture); } public static System.String GetLocalizedMessage(System.String key, System.Globalization.CultureInfo locale) { System.Object message = GetResourceBundleObject(key, locale); if (message == null) { return "Message with key:" + key + " and locale: " + locale + " not found."; } return message.ToString(); } public static System.String GetLocalizedMessage(System.String key, System.Globalization.CultureInfo locale, System.Object[] args) { System.String str = GetLocalizedMessage(key, locale); if (args.Length > 0) { str = System.String.Format(str, args); } return str; } public static System.String GetLocalizedMessage(System.String key, System.Object[] args) { return GetLocalizedMessage(key, System.Threading.Thread.CurrentThread.CurrentCulture, args); } /// <summary> Initialize a given class with the message bundle Keys Should be called from /// a class that extends NLS in a static block at class load time. /// /// </summary> /// <param name="bundleName">Property file with that contains the message bundle /// </param> /// <param name="clazz">where constants will reside /// </param> //@SuppressWarnings("unchecked") protected internal static void InitializeMessages(System.String bundleName, System.Type clazz) { try { Load(clazz); if (!bundles.Contains(bundleName)) bundles[bundleName] = clazz; } catch (System.Exception e) { // ignore all errors and exceptions // because this function is supposed to be called at class load time. } } private static System.Object GetResourceBundleObject(System.String messageKey, System.Globalization.CultureInfo locale) { // slow resource checking // need to loop thru all registered resource bundles for (System.Collections.IEnumerator it = bundles.Keys.GetEnumerator(); it.MoveNext(); ) { System.Type clazz = (System.Type) bundles[(System.String) it.Current]; System.Threading.Thread.CurrentThread.CurrentUICulture = locale; System.Resources.ResourceManager resourceBundle = System.Resources.ResourceManager.CreateFileBasedResourceManager(clazz.Name, "Messages", null); //{{Lucene.Net-2.9.1}} Can we make resourceDir "Messages" more general? if (resourceBundle != null) { try { System.Object obj = resourceBundle.GetObject(messageKey); if (obj != null) return obj; } catch (System.Resources.MissingManifestResourceException e) { // just continue it might be on the next resource bundle } } } // if resource is not found return null; } /// <param name="clazz"> /// </param> private static void Load(System.Type clazz) { System.Reflection.FieldInfo[] fieldArray = clazz.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Static); bool isFieldAccessible = clazz.IsPublic; // build a map of field names to Field objects int len = fieldArray.Length; System.Collections.IDictionary fields = new System.Collections.Hashtable(len * 2); for (int i = 0; i < len; i++) { fields[fieldArray[i].Name] = fieldArray[i]; LoadfieldValue(fieldArray[i], isFieldAccessible, clazz); } } /// <param name="field"> /// </param> /// <param name="isFieldAccessible"> /// </param> private static void LoadfieldValue(System.Reflection.FieldInfo field, bool isFieldAccessible, System.Type clazz) { /* int MOD_EXPECTED = Modifier.PUBLIC | Modifier.STATIC; int MOD_MASK = MOD_EXPECTED | Modifier.FINAL; if ((field.getModifiers() & MOD_MASK) != MOD_EXPECTED) return ; */ if (!(field.IsPublic || field.IsStatic)) return ; // Set a value for this empty field. if (!isFieldAccessible) MakeAccessible(field); try { field.SetValue(null, field.Name); ValidateMessage(field.Name, clazz); } catch (System.ArgumentException e) { // should not happen } catch (System.UnauthorizedAccessException e) { // should not happen } } /// <param name="key">- Message Key /// </param> private static void ValidateMessage(System.String key, System.Type clazz) { // Test if the message is present in the resource bundle try { System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture; System.Resources.ResourceManager resourceBundle = System.Resources.ResourceManager.CreateFileBasedResourceManager(clazz.FullName, "", null); if (resourceBundle != null) { System.Object obj = resourceBundle.GetObject(key); if (obj == null) { System.Console.Error.WriteLine("WARN: Message with key:" + key + " and locale: " + System.Threading.Thread.CurrentThread.CurrentCulture + " not found."); } } } catch (System.Resources.MissingManifestResourceException e) { System.Console.Error.WriteLine("WARN: Message with key:" + key + " and locale: " + System.Threading.Thread.CurrentThread.CurrentCulture + " not found."); } catch (System.Exception e) { // ignore all other errors and exceptions // since this code is just a test to see if the message is present on the // system } } /* * Make a class field accessible */ //@SuppressWarnings("unchecked") private static void MakeAccessible(System.Reflection.FieldInfo field) { if (System.Security.SecurityManager.SecurityEnabled) { //field.setAccessible(true); // {{Aroush-2.9}} java.lang.reflect.AccessibleObject.setAccessible } else { //AccessController.doPrivileged(new AnonymousClassPrivilegedAction(field)); // {{Aroush-2.9}} java.security.AccessController.doPrivileged } } } }
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.IO; namespace MixpanelSDK.UnityEditor.iOS.Xcode.PBX { internal class GUIDToCommentMap { private Dictionary<string, string> m_Dict = new Dictionary<string, string>(); public string this[string guid] { get { if (m_Dict.ContainsKey(guid)) return m_Dict[guid]; return null; } } public void Add(string guid, string comment) { if (m_Dict.ContainsKey(guid)) return; m_Dict.Add(guid, comment); } public void Remove(string guid) { m_Dict.Remove(guid); } public string Write(string guid) { string comment = this[guid]; if (comment == null) return guid; return String.Format("{0} /* {1} */", guid, comment); } public void WriteStringBuilder(StringBuilder sb, string guid) { string comment = this[guid]; if (comment == null) sb.Append(guid); else { // {0} /* {1} */ sb.Append(guid).Append(" /* ").Append(comment).Append(" */"); } } } internal class PBXGUID { internal delegate string GuidGenerator(); // We allow changing Guid generator to make testing of PBXProject possible private static GuidGenerator guidGenerator = DefaultGuidGenerator; internal static string DefaultGuidGenerator() { return Guid.NewGuid().ToString("N").Substring(8).ToUpper(); } internal static void SetGuidGenerator(GuidGenerator generator) { guidGenerator = generator; } // Generates a GUID. public static string Generate() { return guidGenerator(); } } internal class PBXRegex { public static string GuidRegexString = "[A-Fa-f0-9]{24}"; } internal class PBXStream { static bool DontNeedQuotes(string src) { // using a regex instead of explicit matching slows down common cases by 40% if (src.Length == 0) return false; bool hasSlash = false; for (int i = 0; i < src.Length; ++i) { char c = src[i]; if (Char.IsLetterOrDigit(c) || c == '.' || c == '*' || c == '_') continue; if (c == '/') { hasSlash = true; continue; } return false; } if (hasSlash) { if (src.Contains("//") || src.Contains("/*") || src.Contains("*/")) return false; } return true; } // Quotes the given string if it contains special characters. Note: if the string already // contains quotes, then they are escaped and the entire string quoted again public static string QuoteStringIfNeeded(string src) { if (DontNeedQuotes(src)) return src; return "\"" + src.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n") + "\""; } // If the given string is quoted, removes the quotes and unescapes any quotes within the string public static string UnquoteString(string src) { if (!src.StartsWith("\"") || !src.EndsWith("\"")) return src; return src.Substring(1, src.Length - 2).Replace("\\\\", "\u569f").Replace("\\\"", "\"") .Replace("\\n", "\n").Replace("\u569f", "\\"); // U+569f is a rarely used Chinese character } } internal enum PBXFileType { NotBuildable, Framework, Source, Resource, CopyFile } internal class FileTypeUtils { internal class FileTypeDesc { public FileTypeDesc(string typeName, PBXFileType type) { this.name = typeName; this.type = type; this.isExplicit = false; } public FileTypeDesc(string typeName, PBXFileType type, bool isExplicit) { this.name = typeName; this.type = type; this.isExplicit = isExplicit; } public string name; public PBXFileType type; public bool isExplicit; } private static readonly Dictionary<string, FileTypeDesc> types = new Dictionary<string, FileTypeDesc> { { ".a", new FileTypeDesc("archive.ar", PBXFileType.Framework) }, { ".app", new FileTypeDesc("wrapper.application", PBXFileType.NotBuildable, true) }, { ".appex", new FileTypeDesc("wrapper.app-extension", PBXFileType.CopyFile) }, { ".bin", new FileTypeDesc("archive.macbinary", PBXFileType.Resource) }, { ".s", new FileTypeDesc("sourcecode.asm", PBXFileType.Source) }, { ".c", new FileTypeDesc("sourcecode.c.c", PBXFileType.Source) }, { ".cc", new FileTypeDesc("sourcecode.cpp.cpp", PBXFileType.Source) }, { ".cpp", new FileTypeDesc("sourcecode.cpp.cpp", PBXFileType.Source) }, { ".swift", new FileTypeDesc("sourcecode.swift", PBXFileType.Source) }, { ".dll", new FileTypeDesc("file", PBXFileType.NotBuildable) }, { ".framework", new FileTypeDesc("wrapper.framework", PBXFileType.Framework) }, { ".h", new FileTypeDesc("sourcecode.c.h", PBXFileType.NotBuildable) }, { ".pch", new FileTypeDesc("sourcecode.c.h", PBXFileType.NotBuildable) }, { ".icns", new FileTypeDesc("image.icns", PBXFileType.Resource) }, { ".xcassets", new FileTypeDesc("folder.assetcatalog", PBXFileType.Resource) }, { ".inc", new FileTypeDesc("sourcecode.inc", PBXFileType.NotBuildable) }, { ".m", new FileTypeDesc("sourcecode.c.objc", PBXFileType.Source) }, { ".mm", new FileTypeDesc("sourcecode.cpp.objcpp", PBXFileType.Source ) }, { ".nib", new FileTypeDesc("wrapper.nib", PBXFileType.Resource) }, { ".plist", new FileTypeDesc("text.plist.xml", PBXFileType.Resource) }, { ".png", new FileTypeDesc("image.png", PBXFileType.Resource) }, { ".rtf", new FileTypeDesc("text.rtf", PBXFileType.Resource) }, { ".tiff", new FileTypeDesc("image.tiff", PBXFileType.Resource) }, { ".txt", new FileTypeDesc("text", PBXFileType.Resource) }, { ".json", new FileTypeDesc("text.json", PBXFileType.Resource) }, { ".xcodeproj", new FileTypeDesc("wrapper.pb-project", PBXFileType.NotBuildable) }, { ".xib", new FileTypeDesc("file.xib", PBXFileType.Resource) }, { ".strings", new FileTypeDesc("text.plist.strings", PBXFileType.Resource) }, { ".storyboard",new FileTypeDesc("file.storyboard", PBXFileType.Resource) }, { ".bundle", new FileTypeDesc("wrapper.plug-in", PBXFileType.Resource) }, { ".dylib", new FileTypeDesc("compiled.mach-o.dylib", PBXFileType.Framework) }, { ".tbd", new FileTypeDesc("sourcecode.text-based-dylib-definition", PBXFileType.Framework) } }; public static bool IsKnownExtension(string ext) { return types.ContainsKey(ext); } internal static bool IsFileTypeExplicit(string ext) { if (types.ContainsKey(ext)) return types[ext].isExplicit; return false; } public static PBXFileType GetFileType(string ext, bool isFolderRef) { if (isFolderRef) return PBXFileType.Resource; if (!types.ContainsKey(ext)) return PBXFileType.Resource; return types[ext].type; } public static string GetTypeName(string ext) { if (types.ContainsKey(ext)) return types[ext].name; // Xcode actually checks the file contents to determine the file type. // Text files have "text" type and all other files have "file" type. // Since we can't reasonably determine whether the file in question is // a text file, we just take the safe route and return "file" type. return "file"; } public static bool IsBuildableFile(string ext) { if (!types.ContainsKey(ext)) return true; if (types[ext].type != PBXFileType.NotBuildable) return true; return false; } public static bool IsBuildable(string ext, bool isFolderReference) { if (isFolderReference) return true; return IsBuildableFile(ext); } private static readonly Dictionary<PBXSourceTree, string> sourceTree = new Dictionary<PBXSourceTree, string> { { PBXSourceTree.Absolute, "<absolute>" }, { PBXSourceTree.Group, "<group>" }, { PBXSourceTree.Build, "BUILT_PRODUCTS_DIR" }, { PBXSourceTree.Developer, "DEVELOPER_DIR" }, { PBXSourceTree.Sdk, "SDKROOT" }, { PBXSourceTree.Source, "SOURCE_ROOT" }, }; private static readonly Dictionary<string, PBXSourceTree> stringToSourceTreeMap = new Dictionary<string, PBXSourceTree> { { "<absolute>", PBXSourceTree.Absolute }, { "<group>", PBXSourceTree.Group }, { "BUILT_PRODUCTS_DIR", PBXSourceTree.Build }, { "DEVELOPER_DIR", PBXSourceTree.Developer }, { "SDKROOT", PBXSourceTree.Sdk }, { "SOURCE_ROOT", PBXSourceTree.Source }, }; internal static string SourceTreeDesc(PBXSourceTree tree) { return sourceTree[tree]; } // returns PBXSourceTree.Source on error internal static PBXSourceTree ParseSourceTree(string tree) { if (stringToSourceTreeMap.ContainsKey(tree)) return stringToSourceTreeMap[tree]; return PBXSourceTree.Source; } internal static List<PBXSourceTree> AllAbsoluteSourceTrees() { return new List<PBXSourceTree>{PBXSourceTree.Absolute, PBXSourceTree.Build, PBXSourceTree.Developer, PBXSourceTree.Sdk, PBXSourceTree.Source}; } } internal class Utils { /// Replaces '\' with '/'. We need to apply this function to all paths that come from the user /// of the API because we store paths to pbxproj and on windows we may get path with '\' slashes /// instead of '/' slashes public static string FixSlashesInPath(string path) { if (path == null) return null; return path.Replace('\\', '/'); } public static void CombinePaths(string path1, PBXSourceTree tree1, string path2, PBXSourceTree tree2, out string resPath, out PBXSourceTree resTree) { if (tree2 == PBXSourceTree.Group) { resPath = CombinePaths(path1, path2); resTree = tree1; return; } resPath = path2; resTree = tree2; } public static string CombinePaths(string path1, string path2) { if (path2.StartsWith("/")) return path2; if (path1.EndsWith("/")) return path1 + path2; if (path1 == "") return path2; if (path2 == "") return path1; return path1 + "/" + path2; } public static string GetDirectoryFromPath(string path) { int pos = path.LastIndexOf('/'); if (pos == -1) return ""; else return path.Substring(0, pos); } public static string GetFilenameFromPath(string path) { int pos = path.LastIndexOf('/'); if (pos == -1) return path; else return path.Substring(pos + 1); } public static string[] SplitPath(string path) { if (string.IsNullOrEmpty(path)) return new string[]{}; return path.Split(new[]{'/'}, StringSplitOptions.RemoveEmptyEntries); } } } // UnityEditor.iOS.Xcode
using System; using System.ComponentModel; using System.Globalization; using System.Windows.Input; using Avalonia.Data; using Avalonia.Data.Converters; using Avalonia.Layout; using Xunit; namespace Avalonia.Base.UnitTests.Data.Converters { public class DefaultValueConverterTests { [Fact] public void Can_Convert_String_To_Int() { var result = DefaultValueConverter.Instance.Convert( "5", typeof(int), null, CultureInfo.InvariantCulture); Assert.Equal(5, result); } [Fact] public void Can_Convert_String_To_Double() { var result = DefaultValueConverter.Instance.Convert( "5", typeof(double), null, CultureInfo.InvariantCulture); Assert.Equal(5.0, result); } [Fact] public void Do_Not_Throw_On_InvalidInput_For_NullableInt() { var result = DefaultValueConverter.Instance.Convert( "<not-a-number>", typeof(int?), null, CultureInfo.InvariantCulture); Assert.IsType(typeof(BindingNotification), result); } [Fact] public void Can_Convert_Decimal_To_NullableDouble() { var result = DefaultValueConverter.Instance.Convert( 5m, typeof(double?), null, CultureInfo.InvariantCulture); Assert.Equal(5.0, result); } [Fact] public void Can_Convert_CustomType_To_Int() { var result = DefaultValueConverter.Instance.Convert( new CustomType(123), typeof(int), null, CultureInfo.InvariantCulture); Assert.Equal(123, result); } [Fact] public void Can_Convert_Int_To_CustomType() { var result = DefaultValueConverter.Instance.Convert( 123, typeof(CustomType), null, CultureInfo.InvariantCulture); Assert.Equal(new CustomType(123), result); } [Fact] public void Can_Convert_String_To_Enum() { var result = DefaultValueConverter.Instance.Convert( "Bar", typeof(TestEnum), null, CultureInfo.InvariantCulture); Assert.Equal(TestEnum.Bar, result); } [Fact] public void Can_Convert_String_To_TimeSpan() { var result = DefaultValueConverter.Instance.Convert( "00:00:10", typeof(TimeSpan), null, CultureInfo.InvariantCulture); Assert.Equal(TimeSpan.FromSeconds(10), result); } [Fact] public void Can_Convert_Int_To_Enum() { var result = DefaultValueConverter.Instance.Convert( 1, typeof(TestEnum), null, CultureInfo.InvariantCulture); Assert.Equal(TestEnum.Bar, result); } [Fact] public void Can_Convert_Double_To_String() { var result = DefaultValueConverter.Instance.Convert( 5.0, typeof(string), null, CultureInfo.InvariantCulture); Assert.Equal("5", result); } [Fact] public void Can_Convert_Enum_To_Int() { var result = DefaultValueConverter.Instance.Convert( TestEnum.Bar, typeof(int), null, CultureInfo.InvariantCulture); Assert.Equal(1, result); } [Fact] public void Can_Convert_Enum_To_String() { var result = DefaultValueConverter.Instance.Convert( TestEnum.Bar, typeof(string), null, CultureInfo.InvariantCulture); Assert.Equal("Bar", result); } [Fact] public void Can_Use_Explicit_Cast() { var result = DefaultValueConverter.Instance.Convert( new ExplicitDouble(5.0), typeof(double), null, CultureInfo.InvariantCulture); Assert.Equal(5.0, result); } [Fact] public void Cannot_Convert_Between_Different_Enum_Types() { var result = DefaultValueConverter.Instance.Convert( TestEnum.Foo, typeof(Orientation), null, CultureInfo.InvariantCulture); Assert.IsType<BindingNotification>(result); } [Fact] public void Can_Convert_From_Delegate_To_Command() { int commandResult = 0; var result = DefaultValueConverter.Instance.Convert( (Action<int>)((int i) => { commandResult = i; }), typeof(ICommand), null, CultureInfo.InvariantCulture); Assert.IsAssignableFrom<ICommand>(result); (result as ICommand).Execute(5); Assert.Equal(5, commandResult); } [Fact] public void Can_Convert_From_Delegate_To_Command_No_Parameters() { int commandResult = 0; var result = DefaultValueConverter.Instance.Convert( (Action)(() => { commandResult = 1; }), typeof(ICommand), null, CultureInfo.InvariantCulture); Assert.IsAssignableFrom<ICommand>(result); (result as ICommand).Execute(null); Assert.Equal(1, commandResult); } private enum TestEnum { Foo, Bar, } private class ExplicitDouble { public ExplicitDouble(double value) { Value = value; } public double Value { get; } public static explicit operator double (ExplicitDouble v) { return v.Value; } } [TypeConverter(typeof(CustomTypeConverter))] private class CustomType { public int Value { get; } public CustomType(int value) { Value = value; } public override bool Equals(object obj) { return obj is CustomType other && this.Value == other.Value; } public override int GetHashCode() { return 8399587^Value.GetHashCode(); } } private class CustomTypeConverter : TypeConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(int); } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(int); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { return ((CustomType)value).Value; } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { return new CustomType((int)value); } } } }
using NBitcoin; using NBitcoin.DataEncoders; using NBitcoin.Protocol; using NBitcoin.RPC; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; namespace NBitcoin.Altcoins { // Reference: https://github.com/KotoDevelopers/koto/blob/master/src/chainparams.cpp public class Koto : NetworkSetBase { public static Koto Instance { get; } = new Koto(); public override string CryptoCode => "KOTO"; private Koto() { } public class KotoConsensusFactory : ConsensusFactory { private KotoConsensusFactory() { } public static KotoConsensusFactory Instance { get; } = new KotoConsensusFactory(); public override BlockHeader CreateBlockHeader() { return new KotoBlockHeader(); } public override Block CreateBlock() { return new KotoBlock(new KotoBlockHeader()); } } #pragma warning disable CS0618 // Type or member is obsolete public class KotoBlock : Block { public KotoBlock(KotoBlockHeader header) : base(header) { } public override ConsensusFactory GetConsensusFactory() { return KotoConsensusFactory.Instance; } } public class KotoBlockHeader : BlockHeader { public override uint256 GetPoWHash() { throw new NotImplementedException(); } public override void ReadWrite(BitcoinStream stream) { base.ReadWrite(stream); } } protected override void PostInit() { RegisterDefaultCookiePath("Koto"); // Alternatively, /* RegisterDefaultCookiePath(Mainnet, ".cookie"); RegisterDefaultCookiePath(Testnet, "testnet3", ".cookie"); RegisterDefaultCookiePath(Regtest, "regtest", ".cookie"); */ } protected override NetworkBuilder CreateMainnet() { NetworkBuilder builder = new NetworkBuilder(); builder.SetConsensus(new Consensus() { SubsidyHalvingInterval = 1051200, MajorityEnforceBlockUpgrade = 750, MajorityRejectBlockOutdated = 950, MajorityWindow = 4000, BIP34Hash = new uint256("6d424c350729ae633275d51dc3496e16cd1b1d195c164da00f39c499a2e9959e"), // (Genesis) PowLimit = new Target(new uint256("0007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), PowTargetTimespan = TimeSpan.FromSeconds(1 * 60), PowTargetSpacing = TimeSpan.FromSeconds(1 * 60), PowAllowMinDifficultyBlocks = false, PowNoRetargeting = false, RuleChangeActivationThreshold = 1916, MinerConfirmationWindow = 2016, CoinbaseMaturity = 100, MinimumChainWork = new uint256("0x0000000000000000000000000000000000000000000000000000923084b2fcff"), ConsensusFactory = KotoConsensusFactory.Instance, SupportSegwit = false }) .SetBase58Bytes(Base58Type.PUBKEY_ADDRESS, new byte[] { 0x18, 0x36 }) .SetBase58Bytes(Base58Type.SCRIPT_ADDRESS, new byte[] { 0x18, 0x3B }) .SetBase58Bytes(Base58Type.SECRET_KEY, new byte[] { 0x80 }) .SetBase58Bytes(Base58Type.EXT_PUBLIC_KEY, new byte[] { 0x04, 0x88, 0xB2, 0x1E }) .SetBase58Bytes(Base58Type.EXT_SECRET_KEY, new byte[] { 0x04, 0x88, 0xAD, 0xE4 }) .SetMagic(0x4b6f746f) .SetPort(8433) .SetRPCPort(8432) .SetMaxP2PVersion(170007) .SetName("koto-main") .AddAlias("koto-mainnet") .AddDNSSeeds(new[] { new DNSSeedData("ko-to.org", "dnsseed.ko-to.org") }) .AddSeeds(new NetworkAddress[0]) .SetGenesis("04000000000000000000000000000000000000000000000000000000000000000000000072bb817c4c07ab244baca568f5f465db3a87520fa165e9a9e68adaa820eb8de1ceb32c5affff071fcc0a00000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff2504ffff071f01041d4b6f746f3a4a6170616e6573652063727970746f2d63757272656e6379ffffffff010000000000000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000"); return builder; } //For TestNet v3 protected override NetworkBuilder CreateTestnet() { var builder = new NetworkBuilder(); builder.SetConsensus(new Consensus() { SubsidyHalvingInterval = 1051200, MajorityEnforceBlockUpgrade = 51, MajorityRejectBlockOutdated = 75, MajorityWindow = 400, BIP34Hash = new uint256("bf84afbde20c2d213b68b231ddb585ab616ef7567226820f00d9b397d774d2f0"), PowLimit = new Target(new uint256("07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), PowTargetTimespan = TimeSpan.FromSeconds(1 * 60), PowTargetSpacing = TimeSpan.FromSeconds(1 * 60), PowAllowMinDifficultyBlocks = true, PowNoRetargeting = false, RuleChangeActivationThreshold = 1512, MinerConfirmationWindow = 2016, CoinbaseMaturity = 100, MinimumChainWork = new uint256("0x0000000000000000000000000000000000000000000000000000000072c3a6f1"), ConsensusFactory = KotoConsensusFactory.Instance, SupportSegwit = false }) .SetBase58Bytes(Base58Type.PUBKEY_ADDRESS, new byte[] { 0x18, 0xA4 }) .SetBase58Bytes(Base58Type.SCRIPT_ADDRESS, new byte[] { 0x18, 0x39 }) .SetBase58Bytes(Base58Type.SECRET_KEY, new byte[] { 0xEF }) .SetBase58Bytes(Base58Type.EXT_PUBLIC_KEY, new byte[] { 0x04, 0x35, 0x87, 0xCF }) .SetBase58Bytes(Base58Type.EXT_SECRET_KEY, new byte[] { 0x04, 0x35, 0x83, 0x94 }) .SetMagic(0x546f6b6f) .SetPort(18433) .SetRPCPort(18432) .SetMaxP2PVersion(170007) .SetName("koto-test") .AddAlias("koto-testnet") .AddDNSSeeds(new[] { new DNSSeedData("ko-to.org", "testnet.ko-to.org") }) .AddSeeds(new NetworkAddress[0]) .SetGenesis("04000000000000000000000000000000000000000000000000000000000000000000000072bb817c4c07ab244baca568f5f465db3a87520fa165e9a9e68adaa820eb8de1cfb32c5affff07201c0000000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff2504ffff071f01041d4b6f746f3a4a6170616e6573652063727970746f2d63757272656e6379ffffffff010000000000000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000"); return builder; } protected override NetworkBuilder CreateRegtest() { var builder = new NetworkBuilder(); builder.SetConsensus(new Consensus() { SubsidyHalvingInterval = 200, MajorityEnforceBlockUpgrade = 750, MajorityRejectBlockOutdated = 950, MajorityWindow = 1000, BIP34Hash = new uint256(), PowLimit = new Target(new uint256("0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f")), PowTargetTimespan = TimeSpan.FromSeconds(1 * 60), PowTargetSpacing = TimeSpan.FromSeconds(1 * 60), PowAllowMinDifficultyBlocks = true, MinimumChainWork = uint256.Zero, PowNoRetargeting = true, RuleChangeActivationThreshold = 108, MinerConfirmationWindow = 144, CoinbaseMaturity = 100, ConsensusFactory = KotoConsensusFactory.Instance, SupportSegwit = false }) .SetBase58Bytes(Base58Type.PUBKEY_ADDRESS, new byte[] { 0x18, 0xA4 }) .SetBase58Bytes(Base58Type.SCRIPT_ADDRESS, new byte[] { 0x18, 0x39 }) .SetBase58Bytes(Base58Type.SECRET_KEY, new byte[] { 0xEF }) .SetBase58Bytes(Base58Type.EXT_PUBLIC_KEY, new byte[] { 0x04, 0x35, 0x87, 0xCF }) .SetBase58Bytes(Base58Type.EXT_SECRET_KEY, new byte[] { 0x04, 0x35, 0x83, 0x94 }) .SetMagic(0x52656b6f) .SetPort(18433) .SetRPCPort(18432) .SetMaxP2PVersion(170006) .SetName("koto-reg") .AddAlias("koto-regtest") .SetGenesis("04000000000000000000000000000000000000000000000000000000000000000000000072bb817c4c07ab244baca568f5f465db3a87520fa165e9a9e68adaa820eb8de1cfb32c5affff07201c0000000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff2504ffff071f01041d4b6f746f3a4a6170616e6573652063727970746f2d63757272656e6379ffffffff010000000000000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000"); return builder; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using Python.Runtime; using System.Collections.Generic; using QuantConnect.Data.Market; using QuantConnect.Python; namespace QuantConnect.Tests.Python { [TestFixture] public class DataConsolidatorPythonWrapperTests { [Test] public void UpdatePyConsolidator() { using (Py.GIL()) { var module = PythonEngine.ModuleFromString(Guid.NewGuid().ToString(), "from AlgorithmImports import *\n" + "class CustomConsolidator():\n" + " def __init__(self):\n" + " self.UpdateWasCalled = False\n" + " self.InputType = QuoteBar\n" + " self.OutputType = QuoteBar\n" + " self.Consolidated = None\n" + " self.WorkingData = None\n" + " def Update(self, data):\n" + " self.UpdateWasCalled = True\n"); var customConsolidator = module.GetAttr("CustomConsolidator").Invoke(); var wrapper = new DataConsolidatorPythonWrapper(customConsolidator); var time = DateTime.Today; var period = TimeSpan.FromMinutes(1); var bar1 = new QuoteBar { Time = time, Symbol = Symbols.SPY, Bid = new Bar(1, 2, 0.75m, 1.25m), LastBidSize = 3, Ask = null, LastAskSize = 0, Value = 1, Period = period }; wrapper.Update(bar1); bool called; customConsolidator.GetAttr("UpdateWasCalled").TryConvert(out called); Assert.True(called); } } [Test] public void ScanPyConsolidator() { using (Py.GIL()) { var module = PythonEngine.ModuleFromString(Guid.NewGuid().ToString(), "from AlgorithmImports import *\n" + "class CustomConsolidator():\n" + " def __init__(self):\n" + " self.ScanWasCalled = False\n" + " self.InputType = QuoteBar\n" + " self.OutputType = QuoteBar\n" + " self.Consolidated = None\n" + " self.WorkingData = None\n" + " def Scan(self,time):\n" + " self.ScanWasCalled = True\n"); var customConsolidator = module.GetAttr("CustomConsolidator").Invoke(); var wrapper = new DataConsolidatorPythonWrapper(customConsolidator); var time = DateTime.Today; var period = TimeSpan.FromMinutes(1); wrapper.Scan(DateTime.Now); bool called; customConsolidator.GetAttr("ScanWasCalled").TryConvert(out called); Assert.True(called); } } [Test] public void InputTypePyConsolidator() { using (Py.GIL()) { var module = PythonEngine.ModuleFromString(Guid.NewGuid().ToString(), "from AlgorithmImports import *\n" + "class CustomConsolidator():\n" + " def __init__(self):\n" + " self.InputType = QuoteBar\n" + " self.OutputType = QuoteBar\n" + " self.Consolidated = None\n" + " self.WorkingData = None\n"); var customConsolidator = module.GetAttr("CustomConsolidator").Invoke(); var wrapper = new DataConsolidatorPythonWrapper(customConsolidator); var time = DateTime.Today; var period = TimeSpan.FromMinutes(1); var type = wrapper.InputType; Assert.True(type == typeof(QuoteBar)); } } [Test] public void OutputTypePyConsolidator() { using (Py.GIL()) { var module = PythonEngine.ModuleFromString(Guid.NewGuid().ToString(), "from AlgorithmImports import *\n" + "class CustomConsolidator():\n" + " def __init__(self):\n" + " self.InputType = QuoteBar\n" + " self.OutputType = QuoteBar\n" + " self.Consolidated = None\n" + " self.WorkingData = None\n"); var customConsolidator = module.GetAttr("CustomConsolidator").Invoke(); var wrapper = new DataConsolidatorPythonWrapper(customConsolidator); var time = DateTime.Today; var period = TimeSpan.FromMinutes(1); var type = wrapper.OutputType; Assert.True(type == typeof(QuoteBar)); } } [Test] public void RunRegressionAlgorithm() { var parameter = new RegressionTests.AlgorithmStatisticsTestParameters("CustomConsolidatorRegressionAlgorithm", new Dictionary<string, string> { {"Total Trades", "49"}, {"Average Win", "0.25%"}, {"Average Loss", "-0.01%"}, {"Compounding Annual Return", "65.750%"}, {"Drawdown", "0.300%"}, {"Expectancy", "2.577"}, {"Net Profit", "1.067%"}, {"Sharpe Ratio", "8.793"}, {"Probabilistic Sharpe Ratio", "89.147%"}, {"Loss Rate", "80%"}, {"Win Rate", "20%"}, {"Profit-Loss Ratio", "16.88"}, {"Alpha", "0.522"}, {"Beta", "0.345"}, {"Annual Standard Deviation", "0.081"}, {"Annual Variance", "0.007"}, {"Information Ratio", "1.136"}, {"Tracking Error", "0.144"}, {"Treynor Ratio", "2.061"}, {"Total Fees", "$69.81"} }, Language.Python, AlgorithmStatus.Completed); AlgorithmRunner.RunLocalBacktest(parameter.Algorithm, parameter.Statistics, parameter.AlphaStatistics, parameter.Language, parameter.ExpectedFinalStatus); } [Test] public void AttachAndTriggerEvent() { using (Py.GIL()) { var module = PythonEngine.ModuleFromString(Guid.NewGuid().ToString(), "from AlgorithmImports import *\n" + "class ImplementingClass():\n" + " def __init__(self):\n" + " self.EventCalled = False\n" + " self.Consolidator = CustomConsolidator(timedelta(minutes=1))\n" + " self.Consolidator.DataConsolidated += self.ConsolidatorEvent\n" + " def ConsolidatorEvent(self, sender, bar):\n" + " self.EventCalled = True\n" + "class CustomConsolidator(QuoteBarConsolidator):\n" + " def __init__(self,span):\n" + " self.Span = span"); var implementingClass = module.GetAttr("ImplementingClass").Invoke(); var customConsolidator = implementingClass.GetAttr("Consolidator"); var wrapper = new DataConsolidatorPythonWrapper(customConsolidator); bool called; implementingClass.GetAttr("EventCalled").TryConvert(out called); Assert.False(called); var time = DateTime.Today; var period = TimeSpan.FromMinutes(1); var bar1 = new QuoteBar { Time = time, Symbol = Symbols.SPY, Bid = new Bar(1, 2, 0.75m, 1.25m), LastBidSize = 3, Ask = null, LastAskSize = 0, Value = 1, Period = period }; wrapper.Update(bar1); wrapper.Scan(time.AddMinutes(1)); implementingClass.GetAttr("EventCalled").TryConvert(out called); Assert.True(called); } } } }