context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedVpnGatewaysClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<VpnGateways.VpnGatewaysClient> mockGrpcClient = new moq::Mock<VpnGateways.VpnGatewaysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetVpnGatewayRequest request = new GetVpnGatewayRequest { Region = "regionedb20d96", Project = "projectaa6ff846", VpnGateway = "vpn_gatewayaa15de14", }; VpnGateway expectedResponse = new VpnGateway { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", VpnInterfaces = { new VpnGatewayVpnGatewayInterface(), }, Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", Network = "networkd22ce091", Description = "description2cf9da67", StackType = "stack_type3a495e39", SelfLink = "self_link7e87f12d", Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); VpnGatewaysClient client = new VpnGatewaysClientImpl(mockGrpcClient.Object, null); VpnGateway response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<VpnGateways.VpnGatewaysClient> mockGrpcClient = new moq::Mock<VpnGateways.VpnGatewaysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetVpnGatewayRequest request = new GetVpnGatewayRequest { Region = "regionedb20d96", Project = "projectaa6ff846", VpnGateway = "vpn_gatewayaa15de14", }; VpnGateway expectedResponse = new VpnGateway { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", VpnInterfaces = { new VpnGatewayVpnGatewayInterface(), }, Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", Network = "networkd22ce091", Description = "description2cf9da67", StackType = "stack_type3a495e39", SelfLink = "self_link7e87f12d", Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<VpnGateway>(stt::Task.FromResult(expectedResponse), null, null, null, null)); VpnGatewaysClient client = new VpnGatewaysClientImpl(mockGrpcClient.Object, null); VpnGateway responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); VpnGateway responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<VpnGateways.VpnGatewaysClient> mockGrpcClient = new moq::Mock<VpnGateways.VpnGatewaysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetVpnGatewayRequest request = new GetVpnGatewayRequest { Region = "regionedb20d96", Project = "projectaa6ff846", VpnGateway = "vpn_gatewayaa15de14", }; VpnGateway expectedResponse = new VpnGateway { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", VpnInterfaces = { new VpnGatewayVpnGatewayInterface(), }, Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", Network = "networkd22ce091", Description = "description2cf9da67", StackType = "stack_type3a495e39", SelfLink = "self_link7e87f12d", Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); VpnGatewaysClient client = new VpnGatewaysClientImpl(mockGrpcClient.Object, null); VpnGateway response = client.Get(request.Project, request.Region, request.VpnGateway); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<VpnGateways.VpnGatewaysClient> mockGrpcClient = new moq::Mock<VpnGateways.VpnGatewaysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetVpnGatewayRequest request = new GetVpnGatewayRequest { Region = "regionedb20d96", Project = "projectaa6ff846", VpnGateway = "vpn_gatewayaa15de14", }; VpnGateway expectedResponse = new VpnGateway { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", VpnInterfaces = { new VpnGatewayVpnGatewayInterface(), }, Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", Network = "networkd22ce091", Description = "description2cf9da67", StackType = "stack_type3a495e39", SelfLink = "self_link7e87f12d", Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<VpnGateway>(stt::Task.FromResult(expectedResponse), null, null, null, null)); VpnGatewaysClient client = new VpnGatewaysClientImpl(mockGrpcClient.Object, null); VpnGateway responseCallSettings = await client.GetAsync(request.Project, request.Region, request.VpnGateway, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); VpnGateway responseCancellationToken = await client.GetAsync(request.Project, request.Region, request.VpnGateway, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetStatusRequestObject() { moq::Mock<VpnGateways.VpnGatewaysClient> mockGrpcClient = new moq::Mock<VpnGateways.VpnGatewaysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetStatusVpnGatewayRequest request = new GetStatusVpnGatewayRequest { Region = "regionedb20d96", Project = "projectaa6ff846", VpnGateway = "vpn_gatewayaa15de14", }; VpnGatewaysGetStatusResponse expectedResponse = new VpnGatewaysGetStatusResponse { Result = new VpnGatewayStatus(), }; mockGrpcClient.Setup(x => x.GetStatus(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); VpnGatewaysClient client = new VpnGatewaysClientImpl(mockGrpcClient.Object, null); VpnGatewaysGetStatusResponse response = client.GetStatus(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetStatusRequestObjectAsync() { moq::Mock<VpnGateways.VpnGatewaysClient> mockGrpcClient = new moq::Mock<VpnGateways.VpnGatewaysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetStatusVpnGatewayRequest request = new GetStatusVpnGatewayRequest { Region = "regionedb20d96", Project = "projectaa6ff846", VpnGateway = "vpn_gatewayaa15de14", }; VpnGatewaysGetStatusResponse expectedResponse = new VpnGatewaysGetStatusResponse { Result = new VpnGatewayStatus(), }; mockGrpcClient.Setup(x => x.GetStatusAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<VpnGatewaysGetStatusResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); VpnGatewaysClient client = new VpnGatewaysClientImpl(mockGrpcClient.Object, null); VpnGatewaysGetStatusResponse responseCallSettings = await client.GetStatusAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); VpnGatewaysGetStatusResponse responseCancellationToken = await client.GetStatusAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetStatus() { moq::Mock<VpnGateways.VpnGatewaysClient> mockGrpcClient = new moq::Mock<VpnGateways.VpnGatewaysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetStatusVpnGatewayRequest request = new GetStatusVpnGatewayRequest { Region = "regionedb20d96", Project = "projectaa6ff846", VpnGateway = "vpn_gatewayaa15de14", }; VpnGatewaysGetStatusResponse expectedResponse = new VpnGatewaysGetStatusResponse { Result = new VpnGatewayStatus(), }; mockGrpcClient.Setup(x => x.GetStatus(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); VpnGatewaysClient client = new VpnGatewaysClientImpl(mockGrpcClient.Object, null); VpnGatewaysGetStatusResponse response = client.GetStatus(request.Project, request.Region, request.VpnGateway); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetStatusAsync() { moq::Mock<VpnGateways.VpnGatewaysClient> mockGrpcClient = new moq::Mock<VpnGateways.VpnGatewaysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetStatusVpnGatewayRequest request = new GetStatusVpnGatewayRequest { Region = "regionedb20d96", Project = "projectaa6ff846", VpnGateway = "vpn_gatewayaa15de14", }; VpnGatewaysGetStatusResponse expectedResponse = new VpnGatewaysGetStatusResponse { Result = new VpnGatewayStatus(), }; mockGrpcClient.Setup(x => x.GetStatusAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<VpnGatewaysGetStatusResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); VpnGatewaysClient client = new VpnGatewaysClientImpl(mockGrpcClient.Object, null); VpnGatewaysGetStatusResponse responseCallSettings = await client.GetStatusAsync(request.Project, request.Region, request.VpnGateway, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); VpnGatewaysGetStatusResponse responseCancellationToken = await client.GetStatusAsync(request.Project, request.Region, request.VpnGateway, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsRequestObject() { moq::Mock<VpnGateways.VpnGatewaysClient> mockGrpcClient = new moq::Mock<VpnGateways.VpnGatewaysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsVpnGatewayRequest request = new TestIamPermissionsVpnGatewayRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); VpnGatewaysClient client = new VpnGatewaysClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsRequestObjectAsync() { moq::Mock<VpnGateways.VpnGatewaysClient> mockGrpcClient = new moq::Mock<VpnGateways.VpnGatewaysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsVpnGatewayRequest request = new TestIamPermissionsVpnGatewayRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); VpnGatewaysClient client = new VpnGatewaysClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissions() { moq::Mock<VpnGateways.VpnGatewaysClient> mockGrpcClient = new moq::Mock<VpnGateways.VpnGatewaysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsVpnGatewayRequest request = new TestIamPermissionsVpnGatewayRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); VpnGatewaysClient client = new VpnGatewaysClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsAsync() { moq::Mock<VpnGateways.VpnGatewaysClient> mockGrpcClient = new moq::Mock<VpnGateways.VpnGatewaysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsVpnGatewayRequest request = new TestIamPermissionsVpnGatewayRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); VpnGatewaysClient client = new VpnGatewaysClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoadSoftDelete.Business.ERLevel { /// <summary> /// E07_RegionColl (editable child list).<br/> /// This is a generated base class of <see cref="E07_RegionColl"/> business object. /// </summary> /// <remarks> /// This class is child of <see cref="E06_Country"/> editable child object.<br/> /// The items of the collection are <see cref="E08_Region"/> objects. /// </remarks> [Serializable] public partial class E07_RegionColl : BusinessListBase<E07_RegionColl, E08_Region> { #region Collection Business Methods /// <summary> /// Removes a <see cref="E08_Region"/> item from the collection. /// </summary> /// <param name="region_ID">The Region_ID of the item to be removed.</param> public void Remove(int region_ID) { foreach (var e08_Region in this) { if (e08_Region.Region_ID == region_ID) { Remove(e08_Region); break; } } } /// <summary> /// Determines whether a <see cref="E08_Region"/> item is in the collection. /// </summary> /// <param name="region_ID">The Region_ID of the item to search for.</param> /// <returns><c>true</c> if the E08_Region is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int region_ID) { foreach (var e08_Region in this) { if (e08_Region.Region_ID == region_ID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="E08_Region"/> item is in the collection's DeletedList. /// </summary> /// <param name="region_ID">The Region_ID of the item to search for.</param> /// <returns><c>true</c> if the E08_Region is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int region_ID) { foreach (var e08_Region in DeletedList) { if (e08_Region.Region_ID == region_ID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="E08_Region"/> item of the <see cref="E07_RegionColl"/> collection, based on item key properties. /// </summary> /// <param name="region_ID">The Region_ID.</param> /// <returns>A <see cref="E08_Region"/> object.</returns> public E08_Region FindE08_RegionByParentProperties(int region_ID) { for (var i = 0; i < this.Count; i++) { if (this[i].Region_ID.Equals(region_ID)) { return this[i]; } } return null; } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="E07_RegionColl"/> collection. /// </summary> /// <returns>A reference to the created <see cref="E07_RegionColl"/> collection.</returns> internal static E07_RegionColl NewE07_RegionColl() { return DataPortal.CreateChild<E07_RegionColl>(); } /// <summary> /// Factory method. Loads a <see cref="E07_RegionColl"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="E07_RegionColl"/> object.</returns> internal static E07_RegionColl GetE07_RegionColl(SafeDataReader dr) { E07_RegionColl obj = new E07_RegionColl(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="E07_RegionColl"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public E07_RegionColl() { // 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 all <see cref="E07_RegionColl"/> 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; var args = new DataPortalHookArgs(dr); OnFetchPre(args); while (dr.Read()) { Add(E08_Region.GetE08_Region(dr)); } OnFetchPost(args); RaiseListChangedEvents = rlce; } /// <summary> /// Loads <see cref="E08_Region"/> items on the E07_RegionObjects collection. /// </summary> /// <param name="collection">The grand parent <see cref="E05_CountryColl"/> collection.</param> internal void LoadItems(E05_CountryColl collection) { foreach (var item in this) { var obj = collection.FindE06_CountryByParentProperties(item.parent_Country_ID); var rlce = obj.E07_RegionObjects.RaiseListChangedEvents; obj.E07_RegionObjects.RaiseListChangedEvents = false; obj.E07_RegionObjects.Add(item); obj.E07_RegionObjects.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 UnityEngine; using System.Collections; /// <summary> /// Provides functionality to use sprites in your scenes that display a multi-coloured gradient /// </summary> public class OTGradientSprite : OTSprite { /// <summary> /// Gradient orientation enumeration /// </summary> public enum GradientOrientation { /// <summary> /// Vertical gradient orientation /// </summary> Vertical, /// <summary> /// Horizontal gradient orientation /// </summary> Horizontal } //----------------------------------------------------------------------------- // Editor settings //----------------------------------------------------------------------------- public GradientOrientation _gradientOrientation = GradientOrientation.Vertical; public OTGradientSpriteColor[] _gradientColors; //----------------------------------------------------------------------------- // public attributes (get/set) //----------------------------------------------------------------------------- /// <summary> /// Gets or sets the gradient orientation. /// </summary> /// <value> /// The gradient orientation. /// </value> public GradientOrientation gradientOrientation { get { return _gradientOrientation; } set { if (value!=_gradientOrientation) { _gradientOrientation = value; meshDirty = true; isDirty = true; } } } /// <summary> /// Gets or sets the gradient colors. /// </summary> /// <value> /// An array with OTGradientSpriteColor elements /// </value> public OTGradientSpriteColor[] gradientColors { get { return _gradientColors; } set { _gradientColors = value; meshDirty = true; isDirty = true; } } private OTGradientSpriteColor[] _gradientColors_; private GradientOrientation _gradientOrientation_ = GradientOrientation.Vertical; void GradientVerts(int vr, int vp, int pos) { if (_gradientOrientation == GradientOrientation.Horizontal) { float dd = (_meshsize_.x/100) * (_gradientColors[vr].position + pos); verts[vp * 2] = new Vector3(mLeft + dd, mTop , 0); // top verts[(vp * 2) +1] = new Vector3(mLeft + dd, mBottom , 0); // bottom } else { float dd = (_meshsize_.y/100) * (_gradientColors[vr].position + pos); verts[vp * 2] = new Vector3(mLeft, mTop - dd , 0); // left verts[(vp * 2) +1] = new Vector3(mRight, mTop - dd , 0); // right } } Vector3[] verts = new Vector3[]{}; /// <exclude/> protected override Mesh GetMesh() { Mesh mesh = InitMesh(); int count = _gradientColors.Length; for (int vr=0; vr<_gradientColors.Length; vr++) if (_gradientColors[vr].size>0) count++; verts = new Vector3[count * 2]; int vp = 0; for (int vr=0; vr<_gradientColors.Length; vr++) { GradientVerts(vr,vp++,0); if (_gradientColors[vr].size>0) GradientVerts(vr,vp++,_gradientColors[vr].size); } mesh.vertices = verts; int[] tris = new int[(count-1) * 6]; for (int vr=0; vr<count-1; vr++) { int vv = vr*2; if (_gradientOrientation == GradientOrientation.Horizontal) { int[] _tris = new int[] { vv,vv+2,vv+3,vv+3,vv+1,vv }; _tris.CopyTo(tris, vr * 6); } else { int[] _tris = new int[] { vv,vv+1,vv+3,vv+3,vv+2,vv }; _tris.CopyTo(tris, vr * 6); } } mesh.triangles = tris; float[] gradientPositions = new float[count]; vp = 0; for(int g = 0; g<gradientColors.Length; g++) { gradientPositions[vp] = gradientColors[g].position; vp++; if (gradientColors[g].size>0) { gradientPositions[vp] = gradientColors[g].position + gradientColors[g].size; vp++; } } mesh.uv = SpliceUV( new Vector2[] { new Vector2(0,1), new Vector2(1,1), new Vector2(1,0), new Vector2(0,0) },gradientPositions, _gradientOrientation == GradientOrientation.Horizontal); return mesh; } void CloneGradientColors() { _gradientColors_ = new OTGradientSpriteColor[_gradientColors.Length]; for (int c=0; c<_gradientColors.Length; c++) { _gradientColors_[c] = new OTGradientSpriteColor(); _gradientColors_[c].position = _gradientColors[c].position; _gradientColors_[c].size = _gradientColors[c].size; _gradientColors_[c].color = _gradientColors[c].color; } } //----------------------------------------------------------------------------- // overridden subclass methods //----------------------------------------------------------------------------- protected override void CheckDirty() { base.CheckDirty(); if (_gradientColors.Length!=_gradientColors_.Length || GradientMeshChanged() || _gradientOrientation_ != _gradientOrientation) meshDirty = true; else if (GradientColorChanged()) isDirty = true; } protected override void CheckSettings() { base.CheckSettings(); if (_gradientColors.Length<2) System.Array.Resize(ref _gradientColors,2); } protected override string GetTypeName() { return "Gradient"; } /// <exclude/> protected override void HandleUV() { if (spriteContainer != null && spriteContainer.isReady) { OTContainer.Frame frame = spriteContainer.GetFrame(frameIndex); // adjust this sprites UV coords if (frame.uv != null && mesh != null) { int count = _gradientColors.Length; for (int vr=0; vr<_gradientColors.Length; vr++) if (_gradientColors[vr].size>0) count++; // get positions for UV splicing float[] gradientPositions = new float[count]; int vp = 0; for(int g = 0; g<gradientColors.Length; g++) { gradientPositions[vp] = gradientColors[g].position; vp++; if (gradientColors[g].size>0) { gradientPositions[vp] = gradientColors[g].position + gradientColors[g].size; vp++; } } // splice UV that we got from the container. mesh.uv = SpliceUV(frame.uv.Clone() as Vector2[],gradientPositions,gradientOrientation == GradientOrientation.Horizontal); } } } /// <exclude/> protected override void Clean() { base.Clean(); if (mesh == null) return; _gradientColors[0].position = 0; _gradientColors[_gradientColors.Length-1].position = 100-_gradientColors[_gradientColors.Length-1].size; CloneGradientColors(); _gradientOrientation_ = _gradientOrientation; var colors = new Color[mesh.vertexCount]; int vp = 0; for (int c=0; c<_gradientColors.Length; c++) { if (vp < mesh.vertexCount/2) { colors[(vp*2)] = _gradientColors[c].color; colors[(vp*2)+1] = _gradientColors[c].color; } vp++; if (_gradientColors[c].size>0 && vp < mesh.vertexCount/2) { colors[(vp*2)] = _gradientColors[c].color; colors[(vp*2)+1] = _gradientColors[c].color; vp++; } } mesh.colors = colors; } //----------------------------------------------------------------------------- // class methods //----------------------------------------------------------------------------- bool GradientMeshChanged() { bool res = false; for (int c = 0; c < _gradientColors.Length; c++) { if (_gradientColors[c].position < 0) _gradientColors[c].position = 0; if (_gradientColors[c].position > 100) _gradientColors[c].position = 100; if (_gradientColors[c].size < 0) _gradientColors[c].size = 0; if (_gradientColors[c].size > 100) _gradientColors[c].size = 100; if (_gradientColors[c].position+_gradientColors[c].size > 100) _gradientColors[c].position = 100-_gradientColors[c].size; if (_gradientColors[c].position!=_gradientColors_[c].position || _gradientColors[c].size!=_gradientColors_[c].size) res = true; } return res; } bool GradientColorChanged() { for (int c = 0; c < _gradientColors.Length; c++) { if (!_gradientColors[c].color.Equals(_gradientColors_[c].color)) { return true; } } return false; } protected override void Awake() { CloneGradientColors(); _gradientOrientation_ = _gradientOrientation; base.Awake(); } new void Start() { base.Start(); } // Update is called once per frame new void Update() { base.Update(); } } /// <summary> /// OT gradient sprite color element /// </summary> [System.Serializable] public class OTGradientSpriteColor { /// <summary> /// The position of the color (0-100) /// </summary> public int position = 0; /// <summary> /// The size of solid color area (0-100) /// </summary> public int size = 0; /// <summary> /// The color of this element /// </summary> public Color color = Color.white; }
//----------------------------------------------------------------------- // <copyright file="GvrEditorEmulator.cs" company="Google Inc."> // Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- using UnityEngine; using System; using System.Collections.Generic; using Gvr.Internal; /// Provides mouse-controlled head tracking emulation in the Unity editor. [HelpURL("https://developers.google.com/vr/unity/reference/class/GvrEditorEmulator")] public class GvrEditorEmulator : MonoBehaviour { // GvrEditorEmulator should only be compiled in the Editor. // // Otherwise, it will override the camera pose every frame on device which causes the // following behaviour: // // The rendered camera pose will still be correct because the VR.InputTracking pose // gets applied after LateUpdate has occured. However, any functionality that // queries the camera pose during Update or LateUpdate after GvrEditorEmulator has been // updated will get the wrong value applied by GvrEditorEmulator intsead. #if UNITY_EDITOR private static GvrEditorEmulator instance; private static bool instance_searched_for = false; public static GvrEditorEmulator Instance { get { if (instance == null && !instance_searched_for) { instance = FindObjectOfType<GvrEditorEmulator>(); instance_searched_for = true; } return instance; } } // Allocate an initial capacity; this will be resized if needed. private static Camera[] AllCameras = new Camera[32]; private const string AXIS_MOUSE_X = "Mouse X"; private const string AXIS_MOUSE_Y = "Mouse Y"; // Simulated neck model. Vector from the neck pivot point to the point between the eyes. private static readonly Vector3 NECK_OFFSET = new Vector3(0, 0.075f, 0.08f); // Use mouse to emulate head in the editor. // These variables must be static so that head pose is maintained between scene changes, // as it is on device. private float mouseX = 0; private float mouseY = 0; private float mouseZ = 0; public Vector3 HeadPosition { get; private set; } public Quaternion HeadRotation { get; private set; } public void Recenter() { mouseX = mouseZ = 0; // Do not reset pitch, which is how it works on the phone. UpdateHeadPositionAndRotation(); ApplyHeadOrientationToVRCameras(); } public void UpdateEditorEmulation() { if (GvrControllerInput.Recentered) { Recenter(); } bool rolled = false; if (CanChangeYawPitch()) { GvrCursorHelper.HeadEmulationActive = true; mouseX += Input.GetAxis(AXIS_MOUSE_X) * 5; if (mouseX <= -180) { mouseX += 360; } else if (mouseX > 180) { mouseX -= 360; } mouseY -= Input.GetAxis(AXIS_MOUSE_Y) * 2.4f; mouseY = Mathf.Clamp(mouseY, -85, 85); } else if (CanChangeRoll()) { GvrCursorHelper.HeadEmulationActive = true; rolled = true; mouseZ += Input.GetAxis(AXIS_MOUSE_X) * 5; mouseZ = Mathf.Clamp(mouseZ, -85, 85); } else { GvrCursorHelper.HeadEmulationActive = false; } if (!rolled) { // People don't usually leave their heads tilted to one side for long. mouseZ = Mathf.Lerp(mouseZ, 0, Time.deltaTime / (Time.deltaTime + 0.1f)); } UpdateHeadPositionAndRotation(); ApplyHeadOrientationToVRCameras(); } void Awake() { if (Instance == null) { instance = this; } else if (Instance != this) { Debug.LogError("More than one active GvrEditorEmulator instance was found in your scene. " + "Ensure that there is only one active GvrEditorEmulator."); this.enabled = false; return; } } void Start() { UpdateAllCameras(); for (int i = 0; i < Camera.allCamerasCount; ++i) { Camera cam = AllCameras[i]; // Only check camera if it is an enabled VR Camera. if (cam && cam.enabled && cam.stereoTargetEye != StereoTargetEyeMask.None) { if (cam.nearClipPlane > 0.1 && GvrSettings.ViewerPlatform == GvrSettings.ViewerPlatformType.Daydream) { Debug.LogWarningFormat( "Camera \"{0}\" has Near clipping plane set to {1} meters, which might " + "cause the rendering of the Daydream controller to clip unexpectedly.\n" + "Suggest using a lower value, 0.1 meters or less.", cam.name, cam.nearClipPlane); } } } } void Update() { // GvrControllerInput automatically updates GvrEditorEmulator. // This guarantees that GvrEditorEmulator is updated before anything else responds to // controller input, which ensures that re-centering works correctly in the editor. // If GvrControllerInput is not available, then fallback to using Update(). if (GvrControllerInput.ApiStatus != GvrControllerApiStatus.Error) { return; } UpdateEditorEmulation(); } private bool CanChangeYawPitch() { // If the MouseControllerProvider is currently active, then don't move the camera. if (MouseControllerProvider.IsActivateButtonPressed) { return false; } return Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt); } private bool CanChangeRoll() { // If the MouseControllerProvider is currently active, then don't move the camera. if (MouseControllerProvider.IsActivateButtonPressed) { return false; } return Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl); } private void UpdateHeadPositionAndRotation() { HeadRotation = Quaternion.Euler(mouseY, mouseX, mouseZ); HeadPosition = HeadRotation * NECK_OFFSET - NECK_OFFSET.y * Vector3.up; } private void ApplyHeadOrientationToVRCameras() { UpdateAllCameras(); // Update all VR cameras using Head position and rotation information. for (int i = 0; i < Camera.allCamerasCount; ++i) { Camera cam = AllCameras[i]; // Check if the Camera is a valid VR Camera, and if so update it to track head motion. if (cam && cam.enabled && cam.stereoTargetEye != StereoTargetEyeMask.None) { cam.transform.localPosition = HeadPosition * cam.transform.lossyScale.y; cam.transform.localRotation = HeadRotation; } } } // Avoids per-frame allocations. Allocates only when AllCameras array is resized. private void UpdateAllCameras() { // Get all Cameras in the scene using persistent data structures. if (Camera.allCamerasCount > AllCameras.Length) { int newAllCamerasSize = Camera.allCamerasCount; while (Camera.allCamerasCount > newAllCamerasSize) { newAllCamerasSize *= 2; } AllCameras = new Camera[newAllCamerasSize]; } // The GetAllCameras method doesn't allocate memory (Camera.allCameras does). Camera.GetAllCameras(AllCameras); } #endif // UNITY_EDITOR }
using System; using System.Configuration; using System.Text; namespace MetX.Standard.Archived.Web { /// <summary>An xlgPage with XslPage rendering and SecureUserProfile functionality built in.</summary> public class SecureXslPage : xlgPage { /// <summary>The SecureUserProfile automatically loaded prior to Page_Load firing.</summary> public SecureUserProfile Security = new SecureUserProfile(); /// <summary>The path to the .xsl file to render the XML against. If blank, the system uses the xsl file with the same name as the class (Default.xsl for Default.aspx for instance)</summary> public string xsltPath = string.Empty; /// <summary>The value of the DebugState attribute to place in root element. Default value is pulled from the Web.config setting xlgSecurity.Debug</summary> public string DebugState = string.Empty; private StringBuilder sb; private string RootName = string.Empty; private string _OutputFormat; /// <summary>The XSL transformation class with (MetX.xml)</summary> public xml Transformer = new xml(); /// <summary>Used to target a manual page creation at a specific user.</summary> public string TargetUserName; /// <summary>Clears the internal xml string area</summary> public void Clear() { sb = new StringBuilder(); } /// <summary>The OnLoad event fired that causes the SecureUserProfile to load.</summary> /// <param name="e">Standard OnLoad event arguments</param> protected override void OnLoad(System.EventArgs e) { Clear(); if (TargetUserName == null || TargetUserName.Length == 0) Security.Start(HttpContext.Current); else Security.Start(HttpContext.Current, TargetUserName); sb.AppendLine("<?xml version=\"1.0\"?>"); if (Request["xslfile"] != null && Request["xslfile"].Length > 0) { xsltPath = Request["xslfile"] + string.Empty; if ((xsltPath.IndexOf(".xsl", 0) + 1) == 0) xsltPath += ".xsl"; } base.OnLoad(e); } /// <summary>Writes the beginning xlgDoc root element to the internal xml string with no attributes</summary> public void Begin() { Begin("xlgDoc", string.Empty); } /// <summary>Writes the beginning root element to the internal xml string with no attributes</summary> /// <param name="RootNodeName">The root element name</param> public void Begin(string RootNodeName) { Begin(RootNodeName, string.Empty); } /// <summary>Writes the beginning root element to the internal xml string with attributes</summary> /// <param name="RootNodeName">The root element name</param> /// <param name="Attributes">The attributes to place in the root element</param> public void Begin(string RootNodeName, string Attributes) { if (RootNodeName != null && RootNodeName.Length > 0) { RootName = RootNodeName.Replace("<", string.Empty).Replace(">", string.Empty).Replace("\"", string.Empty).Replace("'", string.Empty); sb.Append("<" + RootName); if (Attributes != null && Attributes.Length > 0) { sb.Append(" " + Attributes.Trim() + " "); } if (Request["debug"] != null && Request["debug"].Length > 0) { DebugState = Request["debug"]; } else if (ConfigurationManager.AppSettings["xlgDoc.Debug"] == "True") { DebugState = ConfigurationManager.AppSettings["xlgDoc.Debug"]; } string ProbableURL = Request.Url.AbsoluteUri; //Path & Request.ServerVariables("URL") & "?" & Request.QueryString.ToString if (Request.QueryString.ToString().Length == 0) { ProbableURL += "?" + Request.Form.ToString(); } string URLPath = Token.First(ProbableURL, "?"); URLPath = Token.Before(URLPath, Token.Count(URLPath, "/"), "/") + "/"; string ServerPath = Token.Before(URLPath, Token.Count(URLPath, "/") - 1, "/") + "/"; string VDirPath = Token.Before(URLPath, 5, "/") + "/"; if ((ProbableURL.IndexOf("&format=", 0) + 1) > -1) ProbableURL = ProbableURL.Replace("&format=" + Request["format"], string.Empty); sb.AppendLine(" ServerPath=\"" + xml.AttributeEncode(ServerPath) + "\" URLPath=\"" + xml.AttributeEncode(URLPath) + "\" VDirPath=\"" + xml.AttributeEncode(VDirPath) + "\" ProbableURL=\"" + xml.AttributeEncode(ProbableURL) + "\" Format=\"" + OutputFormat + "\" Version=\"" + ConfigurationManager.AppSettings["xlgDoc.Version"] + "\" DebugState=\"" + xml.AttributeEncode(DebugState) + "\">"); sb.Append(Security.InnerXml); } } /// <summary>Writes the closing element to the internal xml string using this.RootName</summary> private void EndDocument() { if (RootName != null && RootName.Length > 0) sb.Append("</" + RootName + ">"); } /// <summary>Appends an xml string to the internal xml string</summary> /// <param name="sToAppend">The xml string to append (usually one or more well formed elements)</param> public void Append(string sToAppend) { sb.Append(sToAppend); } /// <summary>Outputs the internal xml string to the Response</summary> public void RawXml() { Response.ContentType = "text/xml"; NoTransform(); } /// <summary>Returns the Cache object if the Web.config settings "xlgDoc.Cache" = "True"</summary> public System.Web.Caching.Cache PageCache { get { if (ConfigurationManager.AppSettings["xlgDoc.Cache"] == "True") { return Cache; } return null; } } /// <summary>Transforms the internal xml string with the supplied xslt path and filename</summary> /// <param name="xsltPath">The path and filename to render the internal xml string against</param> public void Transform(string xsltPath) { if (OutputFormat == "xml") { RawXml(); } else { EndDocument(); WriteToOutput(Transformer.xslTransform(PageCache, sb, MassageXsltPath(xsltPath))); } } /// <summary>Renders the internal xml string and outputs it to the Response object. Set OutputFormat (or passing in "format" on the request query string) will override rendering options.</summary> public void Transform() { if (OutputFormat == "xml") RawXml(); else if (OutputFormat == "excel") TransformToExcelDownload(); else { EndDocument(); if (xsltPath == null || xsltPath.Length == 0) { WriteToOutput(Transformer.xslTransform(PageCache, sb, MassageXsltPath(Security.PageName))); } else { WriteToOutput(Transformer.xslTransform(PageCache, sb, MassageXsltPath(xsltPath))); } } } /// <summary>Renders the internal xml string as Excel 2003 readable HTML and redirects to the unsecured viewtempdatafile internal handler to allow downloading in Excel. File will be available for about 5 minutes from the temporary folder.</summary> public void TransformToExcelDownload() { Response.Clear(); Session["vfilename"] = sTransformToExcelDownload(); Session["format"] = "excel"; Response.Redirect("viewtempdatafile.aspx"); } /// <summary>Renders the internal xml string as Excel 2003 readable HTML and returns the results.</summary> /// <returns>The render Excel 2003 readable HTML string</returns> public string sTransformToExcelDownload() { string BatchNum = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString() + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(); string xlsFilename = "s" + BatchNum + ".xls"; string tempDir = Server.MapPath(ConfigurationManager.AppSettings["xlgSecurity.TempDataFolder"]); //if (!Directory.Exists(tempDir)) // Directory.CreateDirectory(tempDir); string OutputFilename = tempDir + "\\" + xlsFilename; //if (File.Exists(OutputFilename)) //{ // File.SetAttributes(OutputFilename, FileAttributes.Normal); // File.Delete(OutputFilename); //} //StringBuilder FileContents = sTransform(); Session["vcontent"] = sTransform(); //StreamWriter sw = File.CreateText(OutputFilename); //sw.WriteLine(FileContents); //sw.Flush(); //sw.Close(); //sw.Dispose(); return OutputFilename; } /// <summary>Renders the internal xml string and returns the output. OutputFormat will not override this transformation.</summary> /// <returns>The rendered output</returns> public StringBuilder sTransform() { EndDocument(); if (xsltPath == null || xsltPath.Length == 0) return Transformer.xslTransform(PageCache, sb, MassageXsltPath(Security.PageName)); return Transformer.xslTransform(PageCache, sb, MassageXsltPath(xsltPath)); } /// <summary>Returns the contents of the internal xml string</summary> /// <returns>The internal xml string contents</returns> public string sRawXml() { string ReturnValue = null; EndDocument(); ReturnValue = sb.ToString(); return ReturnValue; } /// <summary>Causes the internal xml string to be written to the output</summary> public void NoTransform() { EndDocument(); WriteToOutput(sb); } /// <summary>Performs garbage collection on page unloda</summary> /// <param name="e">Stadnard event arguments</param> override protected void OnUnload(System.EventArgs e) { base.OnUnload(e); GC.Collect(); } /// <summary>Writes a string to the Response object.</summary> /// <param name="ToWrite">The string to write</param> private void WriteToOutput(ref string ToWrite) { Response.Write(ToWrite); } /// <summary>Writes a string to the Response object.</summary> /// <param name="ToWrite">The StringBuilder to write</param> private void WriteToOutput(StringBuilder ToWrite) { Response.Write(ToWrite); } /// <summary>The format to render the page as. If not set, it will be set to the Request variable "format"</summary> public string OutputFormat { get { if (_OutputFormat == null || _OutputFormat.Length == 0) { _OutputFormat = Request["format"]; } return _OutputFormat; } set { _OutputFormat = value; } } } }
// 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.IO; using System.Linq; using System.Reflection; using System.Threading; using osu.Framework.Logging; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using System.Text; namespace osu.Framework.Testing { [SuppressMessage("Interoperability", "CA1416:Validate platform compatibility")] internal class DynamicClassCompiler<T> : IDisposable where T : IDynamicallyCompile { public event Action CompilationStarted; public event Action<Type> CompilationFinished; public event Action<Exception> CompilationFailed; private readonly List<FileSystemWatcher> watchers = new List<FileSystemWatcher>(); private readonly HashSet<string> requiredFiles = new HashSet<string>(); private T target; public void SetRecompilationTarget(T target) { if (this.target?.GetType().Name != target?.GetType().Name) { requiredFiles.Clear(); referenceBuilder.Reset(); } this.target = target; } private ITypeReferenceBuilder referenceBuilder; public void Start() { if (Debugger.IsAttached) { referenceBuilder = new EmptyTypeReferenceBuilder(); Logger.Log("Dynamic compilation disabled (debugger attached)."); return; } var di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory); string basePath = getSolutionPath(di); if (!Directory.Exists(basePath)) { referenceBuilder = new EmptyTypeReferenceBuilder(); Logger.Log("Dynamic compilation disabled (no solution file found)."); return; } #if NET6_0 referenceBuilder = new RoslynTypeReferenceBuilder(); #else referenceBuilder = new EmptyTypeReferenceBuilder(); #endif Task.Run(async () => { Logger.Log("Initialising dynamic compilation..."); await referenceBuilder.Initialise(Directory.GetFiles(basePath, "*.sln").First()).ConfigureAwait(false); foreach (string dir in Directory.GetDirectories(basePath)) { // only watch directories which house a csproj. this avoids submodules and directories like .git which can contain many files. if (!Directory.GetFiles(dir, "*.csproj").Any()) continue; var fsw = new FileSystemWatcher(dir, @"*.cs") { EnableRaisingEvents = true, IncludeSubdirectories = true, NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime | NotifyFilters.FileName, }; fsw.Renamed += onChange; fsw.Changed += onChange; fsw.Created += onChange; watchers.Add(fsw); } Logger.Log("Dynamic compilation is now available."); }); } private static string getSolutionPath(DirectoryInfo d) { if (d == null) return null; return d.GetFiles().Any(f => f.Extension == ".sln") ? d.FullName : getSolutionPath(d.Parent); } private void onChange(object sender, FileSystemEventArgs args) => Task.Run(async () => await recompileAsync(target?.GetType(), args.FullPath).ConfigureAwait(false)); private int currentVersion; private bool isCompiling; private async Task recompileAsync(Type targetType, string changedFile) { if (targetType == null || isCompiling || referenceBuilder is EmptyTypeReferenceBuilder) return; isCompiling = true; try { while (!checkFileReady(changedFile)) Thread.Sleep(10); Logger.Log($@"Recompiling {Path.GetFileName(targetType.Name)}...", LoggingTarget.Runtime, LogLevel.Important); CompilationStarted?.Invoke(); foreach (string f in await referenceBuilder.GetReferencedFiles(targetType, changedFile).ConfigureAwait(false)) requiredFiles.Add(f); var assemblies = await referenceBuilder.GetReferencedAssemblies(targetType, changedFile).ConfigureAwait(false); using (var pdbStream = new MemoryStream()) using (var peStream = new MemoryStream()) { var compilationResult = createCompilation(targetType, requiredFiles, assemblies).Emit(peStream, pdbStream); if (compilationResult.Success) { peStream.Seek(0, SeekOrigin.Begin); pdbStream.Seek(0, SeekOrigin.Begin); CompilationFinished?.Invoke( Assembly.Load(peStream.ToArray(), pdbStream.ToArray()).GetModules()[0].GetTypes().LastOrDefault(t => t.FullName == targetType.FullName) ); } else { var exceptions = new List<Exception>(); foreach (var diagnostic in compilationResult.Diagnostics) { if (diagnostic.Severity < DiagnosticSeverity.Error) continue; exceptions.Add(new InvalidOperationException(diagnostic.ToString())); } throw new AggregateException(exceptions.ToArray()); } } } catch (Exception ex) { CompilationFailed?.Invoke(ex); } finally { isCompiling = false; } } private CSharpCompilationOptions createCompilationOptions() { var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) .WithMetadataImportOptions(MetadataImportOptions.Internal); // This is an internal property which allows the compiler to ignore accessibility checks. // https://www.strathweb.com/2018/10/no-internalvisibleto-no-problem-bypassing-c-visibility-rules-with-roslyn/ var topLevelBinderFlagsProperty = typeof(CSharpCompilationOptions).GetProperty("TopLevelBinderFlags", BindingFlags.Instance | BindingFlags.NonPublic); Debug.Assert(topLevelBinderFlagsProperty != null); topLevelBinderFlagsProperty.SetValue(options, (uint)1 << 22); return options; } private CSharpCompilation createCompilation(Type targetType, IEnumerable<string> files, IEnumerable<AssemblyReference> assemblies) { // ReSharper disable once RedundantExplicitArrayCreation this doesn't compile when the array is empty var parseOptions = new CSharpParseOptions(preprocessorSymbols: new string[] { #if DEBUG "DEBUG", #endif #if TRACE "TRACE", #endif #if RELEASE "RELEASE", #endif }, languageVersion: LanguageVersion.Latest); // Add the syntax trees for all referenced files. var syntaxTrees = new List<SyntaxTree>(); foreach (string f in files) syntaxTrees.Add(CSharpSyntaxTree.ParseText(File.ReadAllText(f, Encoding.UTF8), parseOptions, f, encoding: Encoding.UTF8)); // Add the new assembly version, such that it replaces any existing dynamic assembly. string assemblyVersion = $"{++currentVersion}.0.*"; syntaxTrees.Add(CSharpSyntaxTree.ParseText($"using System.Reflection; [assembly: AssemblyVersion(\"{assemblyVersion}\")]", parseOptions)); // Add a custom compiler attribute to allow ignoring access checks. syntaxTrees.Add(CSharpSyntaxTree.ParseText(ignores_access_checks_to_attribute_syntax, parseOptions)); // Ignore access checks for assemblies that have had their internal types referenced. var ignoreAccessChecksText = new StringBuilder(); ignoreAccessChecksText.AppendLine("using System.Runtime.CompilerServices;"); foreach (var asm in assemblies.Where(asm => asm.IgnoreAccessChecks)) ignoreAccessChecksText.AppendLine($"[assembly: IgnoresAccessChecksTo(\"{asm.Assembly.GetName().Name}\")]"); syntaxTrees.Add(CSharpSyntaxTree.ParseText(ignoreAccessChecksText.ToString(), parseOptions)); // Determine the new assembly name, ensuring that the dynamic suffix is not duplicated. string assemblyNamespace = targetType.Assembly.GetName().Name?.Replace(".Dynamic", ""); string dynamicNamespace = $"{assemblyNamespace}.Dynamic"; return CSharpCompilation.Create( dynamicNamespace, syntaxTrees, assemblies.Select(asm => asm.GetReference()), createCompilationOptions() ); } /// <summary> /// Check whether a file has finished being written to. /// </summary> private static bool checkFileReady(string filename) { try { using (FileStream inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None)) return inputStream.Length > 0; } catch (Exception) { return false; } } #region IDisposable Support private bool isDisposed; protected virtual void Dispose(bool disposing) { if (!isDisposed) { isDisposed = true; watchers.ForEach(w => w.Dispose()); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion private const string ignores_access_checks_to_attribute_syntax = @"namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { AssemblyName = assemblyName; } public string AssemblyName { get; } } }"; } }
// // ListBrowserSourceContents.cs // // Authors: // Aaron Bockover <abockover@novell.com> // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2007-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 System.Reflection; using System.Collections.Generic; using Gtk; using Mono.Unix; using Hyena; using Hyena.Data; using Hyena.Data.Gui; using Hyena.Widgets; using Banshee.Sources; using Banshee.ServiceStack; using Banshee.Collection; using Banshee.Configuration; using Banshee.Gui; using Banshee.Collection.Gui; using ScrolledWindow=Gtk.ScrolledWindow; namespace Banshee.Sources.Gui { public abstract class FilteredListSourceContents : VBox, ISourceContents { private string name; private object main_view; private Gtk.ScrolledWindow main_scrolled_window; private List<object> filter_views = new List<object> (); protected List<ScrolledWindow> filter_scrolled_windows = new List<ScrolledWindow> (); private Dictionary<object, double> model_positions = new Dictionary<object, double> (); private Paned container; private Widget browser_container; private InterfaceActionService action_service; private ActionGroup browser_view_actions; private static string menu_xml = @" <ui> <menubar name=""MainMenu""> <menu name=""ViewMenu"" action=""ViewMenuAction""> <placeholder name=""BrowserViews""> <menuitem name=""BrowserVisible"" action=""BrowserVisibleAction"" /> <separator /> <menuitem name=""BrowserTop"" action=""BrowserTopAction"" /> <menuitem name=""BrowserLeft"" action=""BrowserLeftAction"" /> <separator /> </placeholder> </menu> </menubar> </ui> "; public FilteredListSourceContents (string name) { this.name = name; InitializeViews (); string position = Layout (); if (ForcePosition != null) { return; } if (ServiceManager.Contains ("InterfaceActionService")) { action_service = ServiceManager.Get<InterfaceActionService> (); if (action_service.FindActionGroup ("BrowserView") == null) { browser_view_actions = new ActionGroup ("BrowserView"); browser_view_actions.Add (new RadioActionEntry [] { new RadioActionEntry ("BrowserLeftAction", null, Catalog.GetString ("Browser on Left"), null, Catalog.GetString ("Show the artist/album browser to the left of the track list"), 0), new RadioActionEntry ("BrowserTopAction", null, Catalog.GetString ("Browser on Top"), null, Catalog.GetString ("Show the artist/album browser above the track list"), 1), }, position == "top" ? 1 : 0, null); browser_view_actions.Add (new ToggleActionEntry [] { new ToggleActionEntry ("BrowserVisibleAction", null, Catalog.GetString ("Show Browser"), "<control>B", Catalog.GetString ("Show or hide the artist/album browser"), null, BrowserVisible.Get ()) }); action_service.AddActionGroup (browser_view_actions); //action_merge_id = action_service.UIManager.NewMergeId (); action_service.UIManager.AddUiFromString (menu_xml); } (action_service.FindAction("BrowserView.BrowserLeftAction") as RadioAction).Changed += OnViewModeChanged; (action_service.FindAction("BrowserView.BrowserTopAction") as RadioAction).Changed += OnViewModeChanged; action_service.FindAction("BrowserView.BrowserVisibleAction").Activated += OnToggleBrowser; } ServiceManager.SourceManager.ActiveSourceChanged += delegate { ThreadAssist.ProxyToMain (delegate { browser_container.Visible = ActiveSourceCanHasBrowser ? BrowserVisible.Get () : false; }); }; NoShowAll = true; } protected abstract void InitializeViews (); protected void SetupMainView<T> (ListView<T> main_view) { this.main_view = main_view; main_scrolled_window = SetupView (main_view); } protected void SetupFilterView<T> (ListView<T> filter_view) { ScrolledWindow window = SetupView (filter_view); filter_scrolled_windows.Add (window); filter_view.HeaderVisible = false; filter_view.SelectionProxy.Changed += OnBrowserViewSelectionChanged; } private ScrolledWindow SetupView (Widget view) { ScrolledWindow window = null; //if (!Banshee.Base.ApplicationContext.CommandLine.Contains ("no-smooth-scroll")) { if (ApplicationContext.CommandLine.Contains ("smooth-scroll")) { window = new SmoothScrolledWindow (); } else { window = new ScrolledWindow (); } window.Add (view); window.HscrollbarPolicy = PolicyType.Automatic; window.VscrollbarPolicy = PolicyType.Automatic; return window; } private void Reset () { // Unparent the views' scrolled window parents so they can be re-packed in // a new layout. The main container gets destroyed since it will be recreated. foreach (ScrolledWindow window in filter_scrolled_windows) { Paned filter_container = window.Parent as Paned; if (filter_container != null) { filter_container.Remove (window); } } if (container != null && main_scrolled_window != null) { container.Remove (main_scrolled_window); } if (container != null) { Remove (container); } } protected string Layout () { string position = ForcePosition == null ? BrowserPosition.Get () : ForcePosition; if (position == "top") { LayoutTop (); } else { LayoutLeft (); } return position; } private void LayoutLeft () { Layout (false); } private void LayoutTop () { Layout (true); } private void Layout (bool top) { //Hyena.Log.Information ("ListBrowser LayoutLeft"); Reset (); container = GetPane (!top); Paned filter_box = GetPane (top); filter_box.PositionSet = true; Paned current_pane = filter_box; for (int i = 0; i < filter_scrolled_windows.Count; i++) { ScrolledWindow window = filter_scrolled_windows[i]; bool last_even_filter = (i == filter_scrolled_windows.Count - 1 && filter_scrolled_windows.Count % 2 == 0); if (i > 0 && !last_even_filter) { Paned new_pane = GetPane (top); current_pane.Pack2 (new_pane, true, false); current_pane.Position = top ? 180 : 350; PersistentPaneController.Control (current_pane, ControllerName (top, i)); current_pane = new_pane; } if (last_even_filter) { current_pane.Pack2 (window, true, false); current_pane.Position = top ? 180 : 350; PersistentPaneController.Control (current_pane, ControllerName (top, i)); } else { current_pane.Pack1 (window, false, false); } } container.Pack1 (filter_box, false, false); container.Pack2 (main_scrolled_window, true, false); browser_container = filter_box; container.Position = top ? 375 : 275; PersistentPaneController.Control (container, ControllerName (top, -1)); ShowPack (); } private string ControllerName (bool top, int filter) { if (filter == -1) return String.Format ("{0}.browser.{1}", name, top ? "top" : "left"); else return String.Format ("{0}.browser.{1}.{2}", name, top ? "top" : "left", filter); } private Paned GetPane (bool hpane) { if (hpane) return new HPaned (); else return new VPaned (); } private void ShowPack () { PackStart (container, true, true, 0); NoShowAll = false; ShowAll (); NoShowAll = true; browser_container.Visible = ForcePosition != null || BrowserVisible.Get (); } private void OnViewModeChanged (object o, ChangedArgs args) { //Hyena.Log.InformationFormat ("ListBrowser mode toggled, val = {0}", args.Current.Value); if (args.Current.Value == 0) { LayoutLeft (); BrowserPosition.Set ("left"); } else { LayoutTop (); BrowserPosition.Set ("top"); } } private void OnToggleBrowser (object o, EventArgs args) { ToggleAction action = (ToggleAction)o; browser_container.Visible = action.Active && ActiveSourceCanHasBrowser; BrowserVisible.Set (action.Active); if (!browser_container.Visible) { ClearFilterSelections (); } } protected abstract void ClearFilterSelections (); protected virtual void OnBrowserViewSelectionChanged (object o, EventArgs args) { // If the All item is now selected, scroll to the top Hyena.Collections.Selection selection = (Hyena.Collections.Selection) o; if (selection.AllSelected) { // Find the view associated with this selection; a bit yuck; pass view in args? foreach (IListView view in filter_views) { if (view.Selection == selection) { view.ScrollTo (0); break; } } } } protected void SetModel<T> (IListModel<T> model) { ListView<T> view = FindListView <T> (); if (view != null) { SetModel (view, model); } else { Hyena.Log.DebugFormat ("Unable to find view for model {0}", model); } } protected void SetModel<T> (ListView<T> view, IListModel<T> model) { if (view.Model != null) { model_positions[view.Model] = view.Vadjustment != null ? view.Vadjustment.Value : 0; } if (model == null) { view.SetModel (null); return; } if (!model_positions.ContainsKey (model)) { model_positions[model] = 0.0; } view.SetModel (model, model_positions[model]); } private ListView<T> FindListView<T> () { if (main_view is ListView<T>) return (ListView<T>) main_view; foreach (object view in filter_views) if (view is ListView<T>) return (ListView<T>) view; return null; } protected virtual string ForcePosition { get { return null; } } protected abstract bool ActiveSourceCanHasBrowser { get; } #region Implement ISourceContents protected ISource source; public abstract bool SetSource (ISource source); public abstract void ResetSource (); public ISource Source { get { return source; } } public Widget Widget { get { return this; } } #endregion public static readonly SchemaEntry<bool> BrowserVisible = new SchemaEntry<bool> ( "browser", "visible", true, "Artist/Album Browser Visibility", "Whether or not to show the Artist/Album browser" ); public static readonly SchemaEntry<string> BrowserPosition = new SchemaEntry<string> ( "browser", "position", "top", "Artist/Album Browser Position", "The position of the Artist/Album browser; either 'top' or 'left'" ); } }
namespace EIDSS.Reports.Document.Human.CaseInvestigation { partial class TherapyReport { /// <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 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(TherapyReport)); this.Detail = new DevExpress.XtraReports.UI.DetailBand(); this.xrTable2 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.PageHeader = new DevExpress.XtraReports.UI.PageHeaderBand(); this.PageFooter = new DevExpress.XtraReports.UI.PageFooterBand(); this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.xrLabel1 = new DevExpress.XtraReports.UI.XRLabel(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.therapyDataSet1 = new EIDSS.Reports.Document.Human.CaseInvestigation.TherapyDataSet(); this.sp_rep_HUM_TherapyTableAdapter = new EIDSS.Reports.Document.Human.CaseInvestigation.TherapyDataSetTableAdapters.sp_rep_HUM_TherapyTableAdapter(); this.xrCrossBandLine1 = new DevExpress.XtraReports.UI.XRCrossBandLine(); this.xrCrossBandLine2 = new DevExpress.XtraReports.UI.XRCrossBandLine(); this.topMarginBand1 = new DevExpress.XtraReports.UI.TopMarginBand(); this.bottomMarginBand1 = new DevExpress.XtraReports.UI.BottomMarginBand(); ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.therapyDataSet1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // Detail // this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable2}); resources.ApplyResources(this.Detail, "Detail"); this.Detail.Name = "Detail"; this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); // // xrTable2 // this.xrTable2.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTable2, "xrTable2"); this.xrTable2.Name = "xrTable2"; this.xrTable2.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow4}); this.xrTable2.StylePriority.UseBorders = false; this.xrTable2.StylePriority.UseFont = false; this.xrTable2.StylePriority.UsePadding = false; this.xrTable2.StylePriority.UseTextAlignment = false; // // xrTableRow4 // this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell8, this.xrTableCell9, this.xrTableCell10}); this.xrTableRow4.Name = "xrTableRow4"; this.xrTableRow4.Weight = 1; // // xrTableCell8 // this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumTherapy.AntibioticName")}); this.xrTableCell8.Name = "xrTableCell8"; this.xrTableCell8.Weight = 0.878748370273794; // // xrTableCell9 // this.xrTableCell9.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumTherapy.AntibioticDose")}); this.xrTableCell9.Name = "xrTableCell9"; this.xrTableCell9.Weight = 1.0430247718383314; // // xrTableCell10 // this.xrTableCell10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumTherapy.FirstAdministeredDate", "{0:dd/MM/yyyy}")}); this.xrTableCell10.Name = "xrTableCell10"; this.xrTableCell10.Weight = 1.0430247718383312; // // PageHeader // resources.ApplyResources(this.PageHeader, "PageHeader"); this.PageHeader.Name = "PageHeader"; this.PageHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); // // PageFooter // resources.ApplyResources(this.PageFooter, "PageFooter"); this.PageFooter.Name = "PageFooter"; this.PageFooter.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); // // ReportHeader // this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrLabel1, this.xrTable1}); resources.ApplyResources(this.ReportHeader, "ReportHeader"); this.ReportHeader.Name = "ReportHeader"; this.ReportHeader.StylePriority.UseTextAlignment = false; // // xrLabel1 // resources.ApplyResources(this.xrLabel1, "xrLabel1"); this.xrLabel1.Name = "xrLabel1"; this.xrLabel1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.xrLabel1.StylePriority.UseFont = false; this.xrLabel1.StylePriority.UsePadding = false; this.xrLabel1.StylePriority.UseTextAlignment = false; // // xrTable1 // this.xrTable1.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1, this.xrTableRow2}); this.xrTable1.StylePriority.UseBorders = false; this.xrTable1.StylePriority.UseFont = false; this.xrTable1.StylePriority.UsePadding = false; this.xrTable1.StylePriority.UseTextAlignment = false; // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell2, this.xrTableCell3}); this.xrTableRow1.Name = "xrTableRow1"; this.xrTableRow1.Weight = 1; // // xrTableCell2 // this.xrTableCell2.Name = "xrTableCell2"; this.xrTableCell2.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell2, "xrTableCell2"); this.xrTableCell2.Weight = 1.9217730227474128; // // xrTableCell3 // this.xrTableCell3.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); this.xrTableCell3.Name = "xrTableCell3"; this.xrTableCell3.StylePriority.UseBorders = false; this.xrTableCell3.Weight = 1.0430248912030435; // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell4, this.xrTableCell5, this.xrTableCell6}); this.xrTableRow2.Name = "xrTableRow2"; this.xrTableRow2.Weight = 1; // // xrTableCell4 // this.xrTableCell4.Name = "xrTableCell4"; resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); this.xrTableCell4.Weight = 0.878748370273794; // // xrTableCell5 // this.xrTableCell5.Name = "xrTableCell5"; resources.ApplyResources(this.xrTableCell5, "xrTableCell5"); this.xrTableCell5.Weight = 1.0430247718383314; // // xrTableCell6 // this.xrTableCell6.Name = "xrTableCell6"; this.xrTableCell6.Weight = 1.0430247718383312; // // therapyDataSet1 // this.therapyDataSet1.DataSetName = "TherapyDataSet"; this.therapyDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // sp_rep_HUM_TherapyTableAdapter // this.sp_rep_HUM_TherapyTableAdapter.ClearBeforeFill = true; // // xrCrossBandLine1 // this.xrCrossBandLine1.EndBand = this.Detail; resources.ApplyResources(this.xrCrossBandLine1, "xrCrossBandLine1"); this.xrCrossBandLine1.Name = "xrCrossBandLine1"; this.xrCrossBandLine1.StartBand = this.ReportHeader; this.xrCrossBandLine1.WidthF = 1F; // // xrCrossBandLine2 // this.xrCrossBandLine2.EndBand = this.Detail; resources.ApplyResources(this.xrCrossBandLine2, "xrCrossBandLine2"); this.xrCrossBandLine2.Name = "xrCrossBandLine2"; this.xrCrossBandLine2.StartBand = this.ReportHeader; this.xrCrossBandLine2.WidthF = 1F; // // topMarginBand1 // resources.ApplyResources(this.topMarginBand1, "topMarginBand1"); this.topMarginBand1.Name = "topMarginBand1"; // // bottomMarginBand1 // resources.ApplyResources(this.bottomMarginBand1, "bottomMarginBand1"); this.bottomMarginBand1.Name = "bottomMarginBand1"; // // TherapyReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.PageHeader, this.PageFooter, this.ReportHeader, this.topMarginBand1, this.bottomMarginBand1}); this.CrossBandControls.AddRange(new DevExpress.XtraReports.UI.XRCrossBandControl[] { this.xrCrossBandLine1, this.xrCrossBandLine2}); this.DataAdapter = this.sp_rep_HUM_TherapyTableAdapter; this.DataMember = "spRepHumTherapy"; this.DataSource = this.therapyDataSet1; resources.ApplyResources(this, "$this"); this.Version = "10.1"; ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.therapyDataSet1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailBand Detail; private DevExpress.XtraReports.UI.PageHeaderBand PageHeader; private DevExpress.XtraReports.UI.PageFooterBand PageFooter; private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell3; private DevExpress.XtraReports.UI.XRLabel xrLabel1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRTable xrTable2; private DevExpress.XtraReports.UI.XRTableRow xrTableRow4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private TherapyDataSet therapyDataSet1; private TherapyDataSetTableAdapters.sp_rep_HUM_TherapyTableAdapter sp_rep_HUM_TherapyTableAdapter; private DevExpress.XtraReports.UI.XRCrossBandLine xrCrossBandLine1; private DevExpress.XtraReports.UI.XRCrossBandLine xrCrossBandLine2; private DevExpress.XtraReports.UI.TopMarginBand topMarginBand1; private DevExpress.XtraReports.UI.BottomMarginBand bottomMarginBand1; } }
using System; using DarkMultiPlayerCommon; using UnityEngine; namespace DarkMultiPlayer { public class ConnectionWindow { public bool display = false; public bool networkWorkerDisconnected = true; public bool connectEventHandled = true; public bool disconnectEventHandled = true; public bool addEventHandled = true; public bool editEventHandled = true; public bool removeEventHandled = true; public bool renameEventHandled = true; public bool addingServer = false; public bool addingServerSafe = false; public int selected = -1; private int selectedSafe = -1; public string status = ""; public ServerEntry addEntry = null; public ServerEntry editEntry = null; private bool initialized; //Add window private string serverName = "Local"; private string serverAddress = "127.0.0.1"; private string serverPort = "6702"; //GUI Layout private Rect windowRect; private Rect moveRect; private GUILayoutOption[] labelOptions; private GUILayoutOption[] layoutOptions; private GUIStyle windowStyle; private GUIStyle buttonStyle; private GUIStyle textAreaStyle; private GUIStyle statusStyle; private Vector2 scrollPos; //const private const float WINDOW_HEIGHT = 400; private const float WINDOW_WIDTH = 400; //version private string version() { if (Common.PROGRAM_VERSION.Length == 40) { return "build " + Common.PROGRAM_VERSION.Substring(0, 7); } return Common.PROGRAM_VERSION; } //Services Settings dmpSettings; OptionsWindow optionsWindow; public ConnectionWindow(Settings dmpSettings, OptionsWindow optionsWindow) { this.dmpSettings = dmpSettings; this.optionsWindow = optionsWindow; } public void Update() { selectedSafe = selected; addingServerSafe = addingServer; display = (HighLogic.LoadedScene == GameScenes.MAINMENU); } private void InitGUI() { //Setup GUI stuff windowRect = new Rect(Screen.width * 0.9f - WINDOW_WIDTH, Screen.height / 2f - WINDOW_HEIGHT / 2f, WINDOW_WIDTH, WINDOW_HEIGHT); moveRect = new Rect(0, 0, 10000, 20); windowStyle = new GUIStyle(GUI.skin.window); textAreaStyle = new GUIStyle(GUI.skin.textArea); buttonStyle = new GUIStyle(GUI.skin.button); //buttonStyle.fontSize = 10; statusStyle = new GUIStyle(GUI.skin.label); //statusStyle.fontSize = 10; statusStyle.normal.textColor = Color.yellow; layoutOptions = new GUILayoutOption[4]; layoutOptions[0] = GUILayout.MinWidth(WINDOW_WIDTH); layoutOptions[1] = GUILayout.MaxWidth(WINDOW_WIDTH); layoutOptions[2] = GUILayout.MinHeight(WINDOW_HEIGHT); layoutOptions[3] = GUILayout.MaxHeight(WINDOW_HEIGHT); labelOptions = new GUILayoutOption[1]; labelOptions[0] = GUILayout.Width(100); } public void Draw() { if (!initialized) { initialized = true; InitGUI(); } if (display) { windowRect = DMPGuiUtil.PreventOffscreenWindow(GUILayout.Window(6702 + Client.WINDOW_OFFSET, windowRect, DrawContent, "DarkMultiPlayer " + version(), windowStyle, layoutOptions)); } } private void DrawContent(int windowID) { GUILayout.BeginVertical(); GUI.DragWindow(moveRect); GUILayout.Space(20); GUILayout.BeginHorizontal(); GUILayout.Label("Player name:", labelOptions); string oldPlayerName = dmpSettings.playerName; dmpSettings.playerName = GUILayout.TextArea(dmpSettings.playerName, 32, textAreaStyle); // Max 32 characters if (oldPlayerName != dmpSettings.playerName) { dmpSettings.playerName = dmpSettings.playerName.Replace("\n", ""); renameEventHandled = false; } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); //Draw add button string addMode = selectedSafe == -1 ? "Add" : "Edit"; string buttonAddMode = addMode; if (addingServer) { buttonAddMode = "Cancel"; } addingServer = GUILayout.Toggle(addingServer, buttonAddMode, buttonStyle); if (addingServer && !addingServerSafe) { if (selected != -1) { //Load the existing server settings serverName = dmpSettings.servers[selected].name; serverAddress = dmpSettings.servers[selected].address; serverPort = dmpSettings.servers[selected].port.ToString(); } } //Draw connect button if (networkWorkerDisconnected) { GUI.enabled = (selectedSafe != -1); if (GUILayout.Button("Connect", buttonStyle)) { connectEventHandled = false; } } else { if (GUILayout.Button("Disconnect", buttonStyle)) { disconnectEventHandled = false; } } //Draw remove button if (GUILayout.Button("Remove", buttonStyle)) { if (removeEventHandled == true) { removeEventHandled = false; } } GUI.enabled = true; optionsWindow.display = GUILayout.Toggle(optionsWindow.display, "Options", buttonStyle); GUILayout.EndHorizontal(); if (addingServerSafe) { GUILayout.BeginHorizontal(); GUILayout.Label("Name:", labelOptions); serverName = GUILayout.TextArea(serverName, textAreaStyle); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Address:", labelOptions); serverAddress = GUILayout.TextArea(serverAddress, textAreaStyle).Trim(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Port:", labelOptions); serverPort = GUILayout.TextArea(serverPort, textAreaStyle).Trim(); GUILayout.EndHorizontal(); if (GUILayout.Button(addMode + " server", buttonStyle)) { if (addEventHandled == true) { if (selected == -1) { addEntry = new ServerEntry(); addEntry.name = serverName; addEntry.address = serverAddress; addEntry.port = 6702; Int32.TryParse(serverPort, out addEntry.port); addEventHandled = false; } else { editEntry = new ServerEntry(); editEntry.name = serverName; editEntry.address = serverAddress; editEntry.port = 6702; Int32.TryParse(serverPort, out editEntry.port); editEventHandled = false; } } } } GUILayout.Label("Servers:"); if (dmpSettings.servers.Count == 0) { GUILayout.Label("(None - Add a server first)"); } scrollPos = GUILayout.BeginScrollView(scrollPos, GUILayout.Width(WINDOW_WIDTH - 5), GUILayout.Height(WINDOW_HEIGHT - 100)); for (int serverPos = 0; serverPos < dmpSettings.servers.Count; serverPos++) { bool thisSelected = GUILayout.Toggle(serverPos == selectedSafe, dmpSettings.servers[serverPos].name, buttonStyle); if (selected == selectedSafe) { if (thisSelected) { if (selected != serverPos) { selected = serverPos; addingServer = false; } } else if (selected == serverPos) { selected = -1; addingServer = false; } } } GUILayout.EndScrollView(); //Draw status message GUILayout.Label(status, statusStyle); GUILayout.EndVertical(); } } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// /// </summary> [DataContract] public partial class BillOfLadingOrderInfoLine : IEquatable<BillOfLadingOrderInfoLine> { /// <summary> /// Initializes a new instance of the <see cref="BillOfLadingOrderInfoLine" /> class. /// Initializes a new instance of the <see cref="BillOfLadingOrderInfoLine" />class. /// </summary> /// <param name="CustomerOrderNo">CustomerOrderNo.</param> /// <param name="NoPackages">NoPackages.</param> /// <param name="Weight">Weight.</param> /// <param name="Palletslip">Palletslip (default to false).</param> /// <param name="AdditionalShipperInfo">AdditionalShipperInfo (required).</param> /// <param name="CustomFields">CustomFields.</param> public BillOfLadingOrderInfoLine(string CustomerOrderNo = null, int? NoPackages = null, int? Weight = null, bool? Palletslip = null, string AdditionalShipperInfo = null, Dictionary<string, Object> CustomFields = null) { // to ensure "AdditionalShipperInfo" is required (not null) if (AdditionalShipperInfo == null) { throw new InvalidDataException("AdditionalShipperInfo is a required property for BillOfLadingOrderInfoLine and cannot be null"); } else { this.AdditionalShipperInfo = AdditionalShipperInfo; } this.CustomerOrderNo = CustomerOrderNo; this.NoPackages = NoPackages; this.Weight = Weight; // use default value if no "Palletslip" provided if (Palletslip == null) { this.Palletslip = false; } else { this.Palletslip = Palletslip; } this.CustomFields = CustomFields; } /// <summary> /// Gets or Sets CustomerOrderNo /// </summary> [DataMember(Name="customerOrderNo", EmitDefaultValue=false)] public string CustomerOrderNo { get; set; } /// <summary> /// Gets or Sets NoPackages /// </summary> [DataMember(Name="noPackages", EmitDefaultValue=false)] public int? NoPackages { get; set; } /// <summary> /// Gets or Sets Weight /// </summary> [DataMember(Name="weight", EmitDefaultValue=false)] public int? Weight { get; set; } /// <summary> /// Gets or Sets Palletslip /// </summary> [DataMember(Name="palletslip", EmitDefaultValue=false)] public bool? Palletslip { get; set; } /// <summary> /// Gets or Sets AdditionalShipperInfo /// </summary> [DataMember(Name="additionalShipperInfo", EmitDefaultValue=false)] public string AdditionalShipperInfo { get; set; } /// <summary> /// Gets or Sets CustomFields /// </summary> [DataMember(Name="customFields", EmitDefaultValue=false)] public Dictionary<string, Object> CustomFields { 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 BillOfLadingOrderInfoLine {\n"); sb.Append(" CustomerOrderNo: ").Append(CustomerOrderNo).Append("\n"); sb.Append(" NoPackages: ").Append(NoPackages).Append("\n"); sb.Append(" Weight: ").Append(Weight).Append("\n"); sb.Append(" Palletslip: ").Append(Palletslip).Append("\n"); sb.Append(" AdditionalShipperInfo: ").Append(AdditionalShipperInfo).Append("\n"); sb.Append(" CustomFields: ").Append(CustomFields).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 BillOfLadingOrderInfoLine); } /// <summary> /// Returns true if BillOfLadingOrderInfoLine instances are equal /// </summary> /// <param name="other">Instance of BillOfLadingOrderInfoLine to be compared</param> /// <returns>Boolean</returns> public bool Equals(BillOfLadingOrderInfoLine other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.CustomerOrderNo == other.CustomerOrderNo || this.CustomerOrderNo != null && this.CustomerOrderNo.Equals(other.CustomerOrderNo) ) && ( this.NoPackages == other.NoPackages || this.NoPackages != null && this.NoPackages.Equals(other.NoPackages) ) && ( this.Weight == other.Weight || this.Weight != null && this.Weight.Equals(other.Weight) ) && ( this.Palletslip == other.Palletslip || this.Palletslip != null && this.Palletslip.Equals(other.Palletslip) ) && ( this.AdditionalShipperInfo == other.AdditionalShipperInfo || this.AdditionalShipperInfo != null && this.AdditionalShipperInfo.Equals(other.AdditionalShipperInfo) ) && ( this.CustomFields == other.CustomFields || this.CustomFields != null && this.CustomFields.SequenceEqual(other.CustomFields) ); } /// <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.CustomerOrderNo != null) hash = hash * 59 + this.CustomerOrderNo.GetHashCode(); if (this.NoPackages != null) hash = hash * 59 + this.NoPackages.GetHashCode(); if (this.Weight != null) hash = hash * 59 + this.Weight.GetHashCode(); if (this.Palletslip != null) hash = hash * 59 + this.Palletslip.GetHashCode(); if (this.AdditionalShipperInfo != null) hash = hash * 59 + this.AdditionalShipperInfo.GetHashCode(); if (this.CustomFields != null) hash = hash * 59 + this.CustomFields.GetHashCode(); return hash; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using Lucene.Net.Support; 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 IDictionary<string, Type> bundles = new HashMap<string, Type>(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, params 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, params 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<T>(System.String bundleName) { try { Load<T>(); if (!bundles.ContainsKey(bundleName)) bundles[bundleName] = typeof(T); } catch (System.Exception) { // 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 (var it = bundles.Keys.GetEnumerator(); it.MoveNext(); ) { System.Type clazz = bundles[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) { // just continue it might be on the next resource bundle } } } // if resource is not found return null; } private static void Load<T>() { var clazz = typeof (T); 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; var fields = new HashMap<string, System.Reflection.FieldInfo>(len * 2); for (int i = 0; i < len; i++) { fields[fieldArray[i].Name] = fieldArray[i]; LoadfieldValue<T>(fieldArray[i], isFieldAccessible); } } /// <param name="field"></param> /// <param name="isFieldAccessible"></param> private static void LoadfieldValue<T>(System.Reflection.FieldInfo field, bool isFieldAccessible) { var clazz = typeof (T); /* 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<T>(field.Name); } catch (System.ArgumentException) { // should not happen } catch (System.UnauthorizedAccessException) { // should not happen } } /// <param name="key">- Message Key /// </param> private static void ValidateMessage<T>(System.String key) { // Test if the message is present in the resource bundle var clazz = typeof (T); 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) { System.Console.Error.WriteLine("WARN: Message with key:" + key + " and locale: " + System.Threading.Thread.CurrentThread.CurrentCulture + " not found."); } catch (System.Exception) { // 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; using System.Collections.Generic; using StructureMap.Pipeline; using StructureMap.Query; namespace StructureMap { /// <summary> /// The main "container" object that implements the Service Locator pattern /// </summary> public interface IContainer : IDisposable { /// <summary> /// Provides queryable access to the configured PluginType's and Instances of this Container /// </summary> IModel Model { get; } /// <summary> /// Creates or finds the named instance of the pluginType /// </summary> /// <param name="pluginType"></param> /// <param name="instanceKey"></param> /// <returns></returns> object GetInstance(Type pluginType, string instanceKey); /// <summary> /// Creates or finds the default instance of the pluginType /// </summary> /// <param name="pluginType"></param> /// <returns></returns> object GetInstance(Type pluginType); /// <summary> /// Creates a new instance of the requested type using the supplied Instance. Mostly used internally /// </summary> /// <param name="pluginType"></param> /// <param name="instance"></param> /// <returns></returns> object GetInstance(Type pluginType, Instance instance); /// <summary> /// Creates or finds the named instance of T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instanceKey"></param> /// <returns></returns> T GetInstance<T>(string instanceKey); /// <summary> /// Creates or finds the default instance of type T /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> T GetInstance<T>(); /// <summary> /// Creates a new instance of the requested type T using the supplied Instance. Mostly used internally /// </summary> /// <param name="instance"></param> /// <returns></returns> T GetInstance<T>(Instance instance); /// <summary> /// Creates or resolves all registered instances of type T /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> IEnumerable<T> GetAllInstances<T>(); /// <summary> /// Creates or resolves all registered instances of the pluginType /// </summary> /// <param name="pluginType"></param> /// <returns></returns> IEnumerable GetAllInstances(Type pluginType); /// <summary> /// Creates or finds the named instance of the pluginType. Returns null if the named instance is not known to the container. /// </summary> /// <param name="pluginType"></param> /// <param name="instanceKey"></param> /// <returns></returns> object TryGetInstance(Type pluginType, string instanceKey); /// <summary> /// Creates or finds the default instance of the pluginType. Returns null if the pluginType is not known to the container. /// </summary> /// <param name="pluginType"></param> /// <returns></returns> object TryGetInstance(Type pluginType); /// <summary> /// Creates or finds the default instance of type T. Returns the default value of T if it is not known to the container. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> T TryGetInstance<T>(); /// <summary> /// Creates or finds the named instance of type T. Returns the default value of T if the named instance is not known to the container. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> T TryGetInstance<T>(string instanceKey); /// <summary> /// Used to add additional configuration to a Container *after* the initialization. /// </summary> /// <param name="configure"></param> void Configure(Action<ConfigurationExpression> configure); /// <summary> /// Injects the given object into a Container as the default for the designated /// TPluginType. Mostly used for temporarily setting up return values of the Container /// to introduce mocks or stubs during automated testing scenarios /// </summary> /// <typeparam name="TPluginType"></typeparam> /// <param name="instance"></param> void Inject<TPluginType>(TPluginType instance); void Inject<TPluginType>(string name, TPluginType value); /// <summary> /// Injects the given object into a Container as the default for the designated /// pluginType. Mostly used for temporarily setting up return values of the Container /// to introduce mocks or stubs during automated testing scenarios /// </summary> /// <param name="pluginType"></param> /// <param name="object"></param> void Inject(Type pluginType, object @object); /// <summary> /// Gets a new child container for the named profile using that profile's defaults with /// fallback to the original parent /// </summary> /// <param name="profileName"></param> /// <returns></returns> IContainer GetProfile(string profileName); /// <summary> /// Returns a report detailing the complete configuration of all PluginTypes and Instances /// </summary> /// <returns></returns> string WhatDoIHave(); /// <summary> /// Use with caution! Does a full environment test of the configuration of this container. Will try to create every configured /// instance and afterward calls any methods marked with the [ValidationMethod] attribute /// </summary> void AssertConfigurationIsValid(); /// <summary> /// Gets all configured instances of type T using explicitly configured arguments from the "args" /// </summary> /// <typeparam name="T"></typeparam> /// <param name="args"></param> /// <returns></returns> IEnumerable<T> GetAllInstances<T>(ExplicitArguments args); /// <summary> /// Gets the default instance of type T using the explicitly configured arguments from the "args" /// </summary> /// <param name="type"></param> /// <param name="args"></param> /// <returns></returns> IEnumerable GetAllInstances(Type type, ExplicitArguments args); T GetInstance<T>(ExplicitArguments args); /// <summary> /// Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency /// of type T should be "arg" /// </summary> /// <typeparam name="T"></typeparam> /// <param name="arg"></param> /// <returns></returns> ExplicitArgsExpression With<T>(T arg); /// <summary> /// Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency or primitive argument /// with the designated name should be the next value. /// </summary> /// <param name="argName"></param> /// <returns></returns> IExplicitProperty With(string argName); /// <summary> /// Gets the default instance of the pluginType using the explicitly configured arguments from the "args" /// </summary> /// <param name="pluginType"></param> /// <param name="args"></param> /// <returns></returns> object GetInstance(Type pluginType, ExplicitArguments args); /// <summary> /// Removes all configured instances of type T from the Container. Use with caution! /// </summary> /// <typeparam name="T"></typeparam> void EjectAllInstancesOf<T>(); /// <summary> /// The "BuildUp" method takes in an already constructed object /// and uses Setter Injection to push in configured dependencies /// of that object /// </summary> /// <param name="target"></param> void BuildUp(object target); /// <summary> /// Convenience method to request an object using an Open Generic /// Type and its parameter Types /// </summary> /// <param name="templateType"></param> /// <returns></returns> /// <example> /// IFlattener flattener1 = container.ForGenericType(typeof (IFlattener&lt;&gt;)) /// .WithParameters(typeof (Address)).GetInstanceAs&lt;IFlattener&gt;(); /// </example> Container.OpenGenericTypeExpression ForGenericType(Type templateType); /// <summary> /// Gets the named instance of the pluginType using the explicitly configured arguments from the "args" /// </summary> /// <typeparam name="T"></typeparam> /// <param name="args"></param> /// <param name="name"></param> /// <returns></returns> T GetInstance<T>(ExplicitArguments args, string name); /// <summary> /// Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency /// of type T should be "arg" /// </summary> /// <param name="pluginType"></param> /// <param name="arg"></param> /// <returns></returns> ExplicitArgsExpression With(Type pluginType, object arg); /// <summary> /// Shortcut syntax for using an object to find a service that handles /// that type of object by using an open generic type /// </summary> /// <example> /// IHandler handler = container.ForObject(shipment) /// .GetClosedTypeOf(typeof (IHandler<>)) /// .As<IHandler>(); /// </example> /// <param name="subject"></param> /// <returns></returns> CloseGenericTypeExpression ForObject(object subject); /// <summary> /// Starts a "Nested" Container for atomic, isolated access /// </summary> /// <returns></returns> IContainer GetNestedContainer(); /// <summary> /// Starts a new "Nested" Container for atomic, isolated service location. Opens /// </summary> /// <param name="profileName"></param> /// <returns></returns> IContainer GetNestedContainer(string profileName); /// <summary> /// The name of the container. By default this is set to /// a random Guid. This is a convience property to /// assist with debugging. Feel free to set to anything, /// as this is not used in any logic. /// </summary> string Name { get; set; } } }
#region License // // The Open Toolkit Library License // // Copyright (c) 2006 - 2009 the Open Toolkit library. // // 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 OpenTK.Graphics.ES11 { using System; using System.Text; using System.Runtime.InteropServices; #pragma warning disable 3019 #pragma warning disable 1591 partial class GL { internal static partial class Core { [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glActiveTexture", ExactSpelling = true)] internal extern static void ActiveTexture(OpenTK.Graphics.ES11.All texture); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glAlphaFunc", ExactSpelling = true)] internal extern static void AlphaFunc(OpenTK.Graphics.ES11.All func, Single @ref); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glAlphaFuncx", ExactSpelling = true)] internal extern static void AlphaFuncx(OpenTK.Graphics.ES11.All func, int @ref); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glAlphaFuncxOES", ExactSpelling = true)] internal extern static void AlphaFuncxOES(OpenTK.Graphics.ES11.All func, int @ref); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glBindBuffer", ExactSpelling = true)] internal extern static void BindBuffer(OpenTK.Graphics.ES11.All target, UInt32 buffer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glBindFramebufferOES", ExactSpelling = true)] internal extern static void BindFramebufferOES(OpenTK.Graphics.ES11.All target, UInt32 framebuffer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glBindRenderbufferOES", ExactSpelling = true)] internal extern static void BindRenderbufferOES(OpenTK.Graphics.ES11.All target, UInt32 renderbuffer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glBindTexture", ExactSpelling = true)] internal extern static void BindTexture(OpenTK.Graphics.ES11.All target, UInt32 texture); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glBlendEquationOES", ExactSpelling = true)] internal extern static void BlendEquationOES(OpenTK.Graphics.ES11.All mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glBlendEquationSeparateOES", ExactSpelling = true)] internal extern static void BlendEquationSeparateOES(OpenTK.Graphics.ES11.All modeRGB, OpenTK.Graphics.ES11.All modeAlpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glBlendFunc", ExactSpelling = true)] internal extern static void BlendFunc(OpenTK.Graphics.ES11.All sfactor, OpenTK.Graphics.ES11.All dfactor); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glBlendFuncSeparateOES", ExactSpelling = true)] internal extern static void BlendFuncSeparateOES(OpenTK.Graphics.ES11.All srcRGB, OpenTK.Graphics.ES11.All dstRGB, OpenTK.Graphics.ES11.All srcAlpha, OpenTK.Graphics.ES11.All dstAlpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glBufferData", ExactSpelling = true)] internal extern static void BufferData(OpenTK.Graphics.ES11.All target, IntPtr size, IntPtr data, OpenTK.Graphics.ES11.All usage); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glBufferSubData", ExactSpelling = true)] internal extern static void BufferSubData(OpenTK.Graphics.ES11.All target, IntPtr offset, IntPtr size, IntPtr data); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glCheckFramebufferStatusOES", ExactSpelling = true)] internal extern static OpenTK.Graphics.ES11.All CheckFramebufferStatusOES(OpenTK.Graphics.ES11.All target); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClear", ExactSpelling = true)] internal extern static void Clear(UInt32 mask); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClearColor", ExactSpelling = true)] internal extern static void ClearColor(Single red, Single green, Single blue, Single alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClearColorx", ExactSpelling = true)] internal extern static void ClearColorx(int red, int green, int blue, int alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClearColorxOES", ExactSpelling = true)] internal extern static void ClearColorxOES(int red, int green, int blue, int alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClearDepthf", ExactSpelling = true)] internal extern static void ClearDepthf(Single depth); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClearDepthfOES", ExactSpelling = true)] internal extern static void ClearDepthfOES(Single depth); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClearDepthx", ExactSpelling = true)] internal extern static void ClearDepthx(int depth); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClearDepthxOES", ExactSpelling = true)] internal extern static void ClearDepthxOES(int depth); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClearStencil", ExactSpelling = true)] internal extern static void ClearStencil(Int32 s); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClientActiveTexture", ExactSpelling = true)] internal extern static void ClientActiveTexture(OpenTK.Graphics.ES11.All texture); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClipPlanef", ExactSpelling = true)] internal extern static unsafe void ClipPlanef(OpenTK.Graphics.ES11.All plane, Single* equation); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClipPlanefIMG", ExactSpelling = true)] internal extern static unsafe void ClipPlanefIMG(OpenTK.Graphics.ES11.All p, Single* eqn); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClipPlanefOES", ExactSpelling = true)] internal extern static unsafe void ClipPlanefOES(OpenTK.Graphics.ES11.All plane, Single* equation); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClipPlanex", ExactSpelling = true)] internal extern static unsafe void ClipPlanex(OpenTK.Graphics.ES11.All plane, int* equation); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClipPlanexIMG", ExactSpelling = true)] internal extern static unsafe void ClipPlanexIMG(OpenTK.Graphics.ES11.All p, int* eqn); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClipPlanexOES", ExactSpelling = true)] internal extern static unsafe void ClipPlanexOES(OpenTK.Graphics.ES11.All plane, int* equation); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glColor4f", ExactSpelling = true)] internal extern static void Color4f(Single red, Single green, Single blue, Single alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glColor4ub", ExactSpelling = true)] internal extern static void Color4ub(Byte red, Byte green, Byte blue, Byte alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glColor4x", ExactSpelling = true)] internal extern static void Color4x(int red, int green, int blue, int alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glColor4xOES", ExactSpelling = true)] internal extern static void Color4xOES(int red, int green, int blue, int alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glColorMask", ExactSpelling = true)] internal extern static void ColorMask(bool red, bool green, bool blue, bool alpha); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glColorPointer", ExactSpelling = true)] internal extern static void ColorPointer(Int32 size, OpenTK.Graphics.ES11.All type, Int32 stride, IntPtr pointer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glCompressedTexImage2D", ExactSpelling = true)] internal extern static void CompressedTexImage2D(OpenTK.Graphics.ES11.All target, Int32 level, OpenTK.Graphics.ES11.All internalformat, Int32 width, Int32 height, Int32 border, Int32 imageSize, IntPtr data); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glCompressedTexSubImage2D", ExactSpelling = true)] internal extern static void CompressedTexSubImage2D(OpenTK.Graphics.ES11.All target, Int32 level, Int32 xoffset, Int32 yoffset, Int32 width, Int32 height, OpenTK.Graphics.ES11.All format, Int32 imageSize, IntPtr data); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glCopyTexImage2D", ExactSpelling = true)] internal extern static void CopyTexImage2D(OpenTK.Graphics.ES11.All target, Int32 level, OpenTK.Graphics.ES11.All internalformat, Int32 x, Int32 y, Int32 width, Int32 height, Int32 border); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glCopyTexSubImage2D", ExactSpelling = true)] internal extern static void CopyTexSubImage2D(OpenTK.Graphics.ES11.All target, Int32 level, Int32 xoffset, Int32 yoffset, Int32 x, Int32 y, Int32 width, Int32 height); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glCullFace", ExactSpelling = true)] internal extern static void CullFace(OpenTK.Graphics.ES11.All mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glCurrentPaletteMatrixOES", ExactSpelling = true)] internal extern static void CurrentPaletteMatrixOES(UInt32 matrixpaletteindex); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDeleteBuffers", ExactSpelling = true)] internal extern static unsafe void DeleteBuffers(Int32 n, UInt32* buffers); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDeleteFencesNV", ExactSpelling = true)] internal extern static unsafe void DeleteFencesNV(Int32 n, UInt32* fences); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDeleteFramebuffersOES", ExactSpelling = true)] internal extern static unsafe void DeleteFramebuffersOES(Int32 n, UInt32* framebuffers); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDeleteRenderbuffersOES", ExactSpelling = true)] internal extern static unsafe void DeleteRenderbuffersOES(Int32 n, UInt32* renderbuffers); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDeleteTextures", ExactSpelling = true)] internal extern static unsafe void DeleteTextures(Int32 n, UInt32* textures); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDepthFunc", ExactSpelling = true)] internal extern static void DepthFunc(OpenTK.Graphics.ES11.All func); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDepthMask", ExactSpelling = true)] internal extern static void DepthMask(bool flag); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDepthRangef", ExactSpelling = true)] internal extern static void DepthRangef(Single zNear, Single zFar); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDepthRangefOES", ExactSpelling = true)] internal extern static void DepthRangefOES(Single zNear, Single zFar); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDepthRangex", ExactSpelling = true)] internal extern static void DepthRangex(int zNear, int zFar); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDepthRangexOES", ExactSpelling = true)] internal extern static void DepthRangexOES(int zNear, int zFar); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDisable", ExactSpelling = true)] internal extern static void Disable(OpenTK.Graphics.ES11.All cap); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDisableClientState", ExactSpelling = true)] internal extern static void DisableClientState(OpenTK.Graphics.ES11.All array); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDisableDriverControlQCOM", ExactSpelling = true)] internal extern static void DisableDriverControlQCOM(UInt32 driverControl); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDrawArrays", ExactSpelling = true)] internal extern static void DrawArrays(OpenTK.Graphics.ES11.All mode, Int32 first, Int32 count); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDrawElements", ExactSpelling = true)] internal extern static void DrawElements(OpenTK.Graphics.ES11.All mode, Int32 count, OpenTK.Graphics.ES11.All type, IntPtr indices); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDrawTexfOES", ExactSpelling = true)] internal extern static void DrawTexfOES(Single x, Single y, Single z, Single width, Single height); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDrawTexfvOES", ExactSpelling = true)] internal extern static unsafe void DrawTexfvOES(Single* coords); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDrawTexiOES", ExactSpelling = true)] internal extern static void DrawTexiOES(Int32 x, Int32 y, Int32 z, Int32 width, Int32 height); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDrawTexivOES", ExactSpelling = true)] internal extern static unsafe void DrawTexivOES(Int32* coords); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDrawTexsOES", ExactSpelling = true)] internal extern static void DrawTexsOES(Int16 x, Int16 y, Int16 z, Int16 width, Int16 height); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDrawTexsvOES", ExactSpelling = true)] internal extern static unsafe void DrawTexsvOES(Int16* coords); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDrawTexxOES", ExactSpelling = true)] internal extern static void DrawTexxOES(int x, int y, int z, int width, int height); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDrawTexxvOES", ExactSpelling = true)] internal extern static unsafe void DrawTexxvOES(int* coords); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glEGLImageTargetRenderbufferStorageOES", ExactSpelling = true)] internal extern static void EGLImageTargetRenderbufferStorageOES(OpenTK.Graphics.ES11.All target, IntPtr image); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glEGLImageTargetTexture2DOES", ExactSpelling = true)] internal extern static void EGLImageTargetTexture2DOES(OpenTK.Graphics.ES11.All target, IntPtr image); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glEnable", ExactSpelling = true)] internal extern static void Enable(OpenTK.Graphics.ES11.All cap); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glEnableClientState", ExactSpelling = true)] internal extern static void EnableClientState(OpenTK.Graphics.ES11.All array); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glEnableDriverControlQCOM", ExactSpelling = true)] internal extern static void EnableDriverControlQCOM(UInt32 driverControl); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFinish", ExactSpelling = true)] internal extern static void Finish(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFinishFenceNV", ExactSpelling = true)] internal extern static void FinishFenceNV(UInt32 fence); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFlush", ExactSpelling = true)] internal extern static void Flush(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFogf", ExactSpelling = true)] internal extern static void Fogf(OpenTK.Graphics.ES11.All pname, Single param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFogfv", ExactSpelling = true)] internal extern static unsafe void Fogfv(OpenTK.Graphics.ES11.All pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFogx", ExactSpelling = true)] internal extern static void Fogx(OpenTK.Graphics.ES11.All pname, int param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFogxOES", ExactSpelling = true)] internal extern static void FogxOES(OpenTK.Graphics.ES11.All pname, int param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFogxv", ExactSpelling = true)] internal extern static unsafe void Fogxv(OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFogxvOES", ExactSpelling = true)] internal extern static unsafe void FogxvOES(OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFramebufferRenderbufferOES", ExactSpelling = true)] internal extern static void FramebufferRenderbufferOES(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All attachment, OpenTK.Graphics.ES11.All renderbuffertarget, UInt32 renderbuffer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFramebufferTexture2DOES", ExactSpelling = true)] internal extern static void FramebufferTexture2DOES(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All attachment, OpenTK.Graphics.ES11.All textarget, UInt32 texture, Int32 level); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFrontFace", ExactSpelling = true)] internal extern static void FrontFace(OpenTK.Graphics.ES11.All mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFrustumf", ExactSpelling = true)] internal extern static void Frustumf(Single left, Single right, Single bottom, Single top, Single zNear, Single zFar); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFrustumfOES", ExactSpelling = true)] internal extern static void FrustumfOES(Single left, Single right, Single bottom, Single top, Single zNear, Single zFar); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFrustumx", ExactSpelling = true)] internal extern static void Frustumx(int left, int right, int bottom, int top, int zNear, int zFar); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFrustumxOES", ExactSpelling = true)] internal extern static void FrustumxOES(int left, int right, int bottom, int top, int zNear, int zFar); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGenBuffers", ExactSpelling = true)] internal extern static unsafe void GenBuffers(Int32 n, UInt32* buffers); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGenerateMipmapOES", ExactSpelling = true)] internal extern static void GenerateMipmapOES(OpenTK.Graphics.ES11.All target); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGenFencesNV", ExactSpelling = true)] internal extern static unsafe void GenFencesNV(Int32 n, UInt32* fences); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGenFramebuffersOES", ExactSpelling = true)] internal extern static unsafe void GenFramebuffersOES(Int32 n, UInt32* framebuffers); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGenRenderbuffersOES", ExactSpelling = true)] internal extern static unsafe void GenRenderbuffersOES(Int32 n, UInt32* renderbuffers); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGenTextures", ExactSpelling = true)] internal extern static unsafe void GenTextures(Int32 n, UInt32* textures); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetBooleanv", ExactSpelling = true)] internal extern static unsafe void GetBooleanv(OpenTK.Graphics.ES11.All pname, bool* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetBufferParameteriv", ExactSpelling = true)] internal extern static unsafe void GetBufferParameteriv(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetBufferPointervOES", ExactSpelling = true)] internal extern static void GetBufferPointervOES(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, IntPtr @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetClipPlanef", ExactSpelling = true)] internal extern static unsafe void GetClipPlanef(OpenTK.Graphics.ES11.All pname, Single* eqn); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetClipPlanefOES", ExactSpelling = true)] internal extern static unsafe void GetClipPlanefOES(OpenTK.Graphics.ES11.All pname, Single* eqn); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetClipPlanex", ExactSpelling = true)] internal extern static unsafe void GetClipPlanex(OpenTK.Graphics.ES11.All pname, int* eqn); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetClipPlanexOES", ExactSpelling = true)] internal extern static unsafe void GetClipPlanexOES(OpenTK.Graphics.ES11.All pname, int* eqn); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetDriverControlsQCOM", ExactSpelling = true)] internal extern static unsafe void GetDriverControlsQCOM(Int32* num, Int32 size, UInt32* driverControls); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetDriverControlStringQCOM", ExactSpelling = true)] internal extern static unsafe void GetDriverControlStringQCOM(UInt32 driverControl, Int32 bufSize, Int32* length, String driverControlString); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetError", ExactSpelling = true)] internal extern static OpenTK.Graphics.ES11.All GetError(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetFenceivNV", ExactSpelling = true)] internal extern static unsafe void GetFenceivNV(UInt32 fence, OpenTK.Graphics.ES11.All pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetFixedv", ExactSpelling = true)] internal extern static unsafe void GetFixedv(OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetFixedvOES", ExactSpelling = true)] internal extern static unsafe void GetFixedvOES(OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetFloatv", ExactSpelling = true)] internal extern static unsafe void GetFloatv(OpenTK.Graphics.ES11.All pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetFramebufferAttachmentParameterivOES", ExactSpelling = true)] internal extern static unsafe void GetFramebufferAttachmentParameterivOES(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All attachment, OpenTK.Graphics.ES11.All pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetIntegerv", ExactSpelling = true)] internal extern static unsafe void GetIntegerv(OpenTK.Graphics.ES11.All pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetLightfv", ExactSpelling = true)] internal extern static unsafe void GetLightfv(OpenTK.Graphics.ES11.All light, OpenTK.Graphics.ES11.All pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetLightxv", ExactSpelling = true)] internal extern static unsafe void GetLightxv(OpenTK.Graphics.ES11.All light, OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetLightxvOES", ExactSpelling = true)] internal extern static unsafe void GetLightxvOES(OpenTK.Graphics.ES11.All light, OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetMaterialfv", ExactSpelling = true)] internal extern static unsafe void GetMaterialfv(OpenTK.Graphics.ES11.All face, OpenTK.Graphics.ES11.All pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetMaterialxv", ExactSpelling = true)] internal extern static unsafe void GetMaterialxv(OpenTK.Graphics.ES11.All face, OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetMaterialxvOES", ExactSpelling = true)] internal extern static unsafe void GetMaterialxvOES(OpenTK.Graphics.ES11.All face, OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetPointerv", ExactSpelling = true)] internal extern static void GetPointerv(OpenTK.Graphics.ES11.All pname, IntPtr @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetRenderbufferParameterivOES", ExactSpelling = true)] internal extern static unsafe void GetRenderbufferParameterivOES(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetString", ExactSpelling = true)] internal extern static unsafe System.IntPtr GetString(OpenTK.Graphics.ES11.All name); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetTexEnvfv", ExactSpelling = true)] internal extern static unsafe void GetTexEnvfv(OpenTK.Graphics.ES11.All env, OpenTK.Graphics.ES11.All pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetTexEnviv", ExactSpelling = true)] internal extern static unsafe void GetTexEnviv(OpenTK.Graphics.ES11.All env, OpenTK.Graphics.ES11.All pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetTexEnvxv", ExactSpelling = true)] internal extern static unsafe void GetTexEnvxv(OpenTK.Graphics.ES11.All env, OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetTexEnvxvOES", ExactSpelling = true)] internal extern static unsafe void GetTexEnvxvOES(OpenTK.Graphics.ES11.All env, OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetTexGenfvOES", ExactSpelling = true)] internal extern static unsafe void GetTexGenfvOES(OpenTK.Graphics.ES11.All coord, OpenTK.Graphics.ES11.All pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetTexGenivOES", ExactSpelling = true)] internal extern static unsafe void GetTexGenivOES(OpenTK.Graphics.ES11.All coord, OpenTK.Graphics.ES11.All pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetTexGenxvOES", ExactSpelling = true)] internal extern static unsafe void GetTexGenxvOES(OpenTK.Graphics.ES11.All coord, OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetTexParameterfv", ExactSpelling = true)] internal extern static unsafe void GetTexParameterfv(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetTexParameteriv", ExactSpelling = true)] internal extern static unsafe void GetTexParameteriv(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetTexParameterxv", ExactSpelling = true)] internal extern static unsafe void GetTexParameterxv(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetTexParameterxvOES", ExactSpelling = true)] internal extern static unsafe void GetTexParameterxvOES(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glHint", ExactSpelling = true)] internal extern static void Hint(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glIsBuffer", ExactSpelling = true)] internal extern static bool IsBuffer(UInt32 buffer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glIsEnabled", ExactSpelling = true)] internal extern static bool IsEnabled(OpenTK.Graphics.ES11.All cap); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glIsFenceNV", ExactSpelling = true)] internal extern static bool IsFenceNV(UInt32 fence); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glIsFramebufferOES", ExactSpelling = true)] internal extern static bool IsFramebufferOES(UInt32 framebuffer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glIsRenderbufferOES", ExactSpelling = true)] internal extern static bool IsRenderbufferOES(UInt32 renderbuffer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glIsTexture", ExactSpelling = true)] internal extern static bool IsTexture(UInt32 texture); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightf", ExactSpelling = true)] internal extern static void Lightf(OpenTK.Graphics.ES11.All light, OpenTK.Graphics.ES11.All pname, Single param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightfv", ExactSpelling = true)] internal extern static unsafe void Lightfv(OpenTK.Graphics.ES11.All light, OpenTK.Graphics.ES11.All pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightModelf", ExactSpelling = true)] internal extern static void LightModelf(OpenTK.Graphics.ES11.All pname, Single param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightModelfv", ExactSpelling = true)] internal extern static unsafe void LightModelfv(OpenTK.Graphics.ES11.All pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightModelx", ExactSpelling = true)] internal extern static void LightModelx(OpenTK.Graphics.ES11.All pname, int param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightModelxOES", ExactSpelling = true)] internal extern static void LightModelxOES(OpenTK.Graphics.ES11.All pname, int param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightModelxv", ExactSpelling = true)] internal extern static unsafe void LightModelxv(OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightModelxvOES", ExactSpelling = true)] internal extern static unsafe void LightModelxvOES(OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightx", ExactSpelling = true)] internal extern static void Lightx(OpenTK.Graphics.ES11.All light, OpenTK.Graphics.ES11.All pname, int param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightxOES", ExactSpelling = true)] internal extern static void LightxOES(OpenTK.Graphics.ES11.All light, OpenTK.Graphics.ES11.All pname, int param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightxv", ExactSpelling = true)] internal extern static unsafe void Lightxv(OpenTK.Graphics.ES11.All light, OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightxvOES", ExactSpelling = true)] internal extern static unsafe void LightxvOES(OpenTK.Graphics.ES11.All light, OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLineWidth", ExactSpelling = true)] internal extern static void LineWidth(Single width); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLineWidthx", ExactSpelling = true)] internal extern static void LineWidthx(int width); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLineWidthxOES", ExactSpelling = true)] internal extern static void LineWidthxOES(int width); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLoadIdentity", ExactSpelling = true)] internal extern static void LoadIdentity(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLoadMatrixf", ExactSpelling = true)] internal extern static unsafe void LoadMatrixf(Single* m); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLoadMatrixx", ExactSpelling = true)] internal extern static unsafe void LoadMatrixx(int* m); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLoadMatrixxOES", ExactSpelling = true)] internal extern static unsafe void LoadMatrixxOES(int* m); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLoadPaletteFromModelViewMatrixOES", ExactSpelling = true)] internal extern static void LoadPaletteFromModelViewMatrixOES(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLogicOp", ExactSpelling = true)] internal extern static void LogicOp(OpenTK.Graphics.ES11.All opcode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMapBufferOES", ExactSpelling = true)] internal extern static unsafe System.IntPtr MapBufferOES(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All access); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMaterialf", ExactSpelling = true)] internal extern static void Materialf(OpenTK.Graphics.ES11.All face, OpenTK.Graphics.ES11.All pname, Single param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMaterialfv", ExactSpelling = true)] internal extern static unsafe void Materialfv(OpenTK.Graphics.ES11.All face, OpenTK.Graphics.ES11.All pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMaterialx", ExactSpelling = true)] internal extern static void Materialx(OpenTK.Graphics.ES11.All face, OpenTK.Graphics.ES11.All pname, int param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMaterialxOES", ExactSpelling = true)] internal extern static void MaterialxOES(OpenTK.Graphics.ES11.All face, OpenTK.Graphics.ES11.All pname, int param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMaterialxv", ExactSpelling = true)] internal extern static unsafe void Materialxv(OpenTK.Graphics.ES11.All face, OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMaterialxvOES", ExactSpelling = true)] internal extern static unsafe void MaterialxvOES(OpenTK.Graphics.ES11.All face, OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMatrixIndexPointerOES", ExactSpelling = true)] internal extern static void MatrixIndexPointerOES(Int32 size, OpenTK.Graphics.ES11.All type, Int32 stride, IntPtr pointer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMatrixMode", ExactSpelling = true)] internal extern static void MatrixMode(OpenTK.Graphics.ES11.All mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMultiTexCoord4f", ExactSpelling = true)] internal extern static void MultiTexCoord4f(OpenTK.Graphics.ES11.All target, Single s, Single t, Single r, Single q); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMultiTexCoord4x", ExactSpelling = true)] internal extern static void MultiTexCoord4x(OpenTK.Graphics.ES11.All target, int s, int t, int r, int q); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMultiTexCoord4xOES", ExactSpelling = true)] internal extern static void MultiTexCoord4xOES(OpenTK.Graphics.ES11.All target, int s, int t, int r, int q); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMultMatrixf", ExactSpelling = true)] internal extern static unsafe void MultMatrixf(Single* m); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMultMatrixx", ExactSpelling = true)] internal extern static unsafe void MultMatrixx(int* m); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMultMatrixxOES", ExactSpelling = true)] internal extern static unsafe void MultMatrixxOES(int* m); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glNormal3f", ExactSpelling = true)] internal extern static void Normal3f(Single nx, Single ny, Single nz); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glNormal3x", ExactSpelling = true)] internal extern static void Normal3x(int nx, int ny, int nz); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glNormal3xOES", ExactSpelling = true)] internal extern static void Normal3xOES(int nx, int ny, int nz); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glNormalPointer", ExactSpelling = true)] internal extern static void NormalPointer(OpenTK.Graphics.ES11.All type, Int32 stride, IntPtr pointer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glOrthof", ExactSpelling = true)] internal extern static void Orthof(Single left, Single right, Single bottom, Single top, Single zNear, Single zFar); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glOrthofOES", ExactSpelling = true)] internal extern static void OrthofOES(Single left, Single right, Single bottom, Single top, Single zNear, Single zFar); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glOrthox", ExactSpelling = true)] internal extern static void Orthox(int left, int right, int bottom, int top, int zNear, int zFar); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glOrthoxOES", ExactSpelling = true)] internal extern static void OrthoxOES(int left, int right, int bottom, int top, int zNear, int zFar); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPixelStorei", ExactSpelling = true)] internal extern static void PixelStorei(OpenTK.Graphics.ES11.All pname, Int32 param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPointParameterf", ExactSpelling = true)] internal extern static void PointParameterf(OpenTK.Graphics.ES11.All pname, Single param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPointParameterfv", ExactSpelling = true)] internal extern static unsafe void PointParameterfv(OpenTK.Graphics.ES11.All pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPointParameterx", ExactSpelling = true)] internal extern static void PointParameterx(OpenTK.Graphics.ES11.All pname, int param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPointParameterxOES", ExactSpelling = true)] internal extern static void PointParameterxOES(OpenTK.Graphics.ES11.All pname, int param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPointParameterxv", ExactSpelling = true)] internal extern static unsafe void PointParameterxv(OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPointParameterxvOES", ExactSpelling = true)] internal extern static unsafe void PointParameterxvOES(OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPointSize", ExactSpelling = true)] internal extern static void PointSize(Single size); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPointSizePointerOES", ExactSpelling = true)] internal extern static void PointSizePointerOES(OpenTK.Graphics.ES11.All type, Int32 stride, IntPtr pointer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPointSizex", ExactSpelling = true)] internal extern static void PointSizex(int size); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPointSizexOES", ExactSpelling = true)] internal extern static void PointSizexOES(int size); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPolygonOffset", ExactSpelling = true)] internal extern static void PolygonOffset(Single factor, Single units); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPolygonOffsetx", ExactSpelling = true)] internal extern static void PolygonOffsetx(int factor, int units); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPolygonOffsetxOES", ExactSpelling = true)] internal extern static void PolygonOffsetxOES(int factor, int units); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPopMatrix", ExactSpelling = true)] internal extern static void PopMatrix(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPushMatrix", ExactSpelling = true)] internal extern static void PushMatrix(); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glQueryMatrixxOES", ExactSpelling = true)] internal extern static unsafe Int32 QueryMatrixxOES(int* mantissa, Int32* exponent); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glReadPixels", ExactSpelling = true)] internal extern static void ReadPixels(Int32 x, Int32 y, Int32 width, Int32 height, OpenTK.Graphics.ES11.All format, OpenTK.Graphics.ES11.All type, IntPtr pixels); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glRenderbufferStorageOES", ExactSpelling = true)] internal extern static void RenderbufferStorageOES(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All internalformat, Int32 width, Int32 height); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glRotatef", ExactSpelling = true)] internal extern static void Rotatef(Single angle, Single x, Single y, Single z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glRotatex", ExactSpelling = true)] internal extern static void Rotatex(int angle, int x, int y, int z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glRotatexOES", ExactSpelling = true)] internal extern static void RotatexOES(int angle, int x, int y, int z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glSampleCoverage", ExactSpelling = true)] internal extern static void SampleCoverage(Single value, bool invert); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glSampleCoveragex", ExactSpelling = true)] internal extern static void SampleCoveragex(int value, bool invert); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glSampleCoveragexOES", ExactSpelling = true)] internal extern static void SampleCoveragexOES(int value, bool invert); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glScalef", ExactSpelling = true)] internal extern static void Scalef(Single x, Single y, Single z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glScalex", ExactSpelling = true)] internal extern static void Scalex(int x, int y, int z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glScalexOES", ExactSpelling = true)] internal extern static void ScalexOES(int x, int y, int z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glScissor", ExactSpelling = true)] internal extern static void Scissor(Int32 x, Int32 y, Int32 width, Int32 height); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glSetFenceNV", ExactSpelling = true)] internal extern static void SetFenceNV(UInt32 fence, OpenTK.Graphics.ES11.All condition); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glShadeModel", ExactSpelling = true)] internal extern static void ShadeModel(OpenTK.Graphics.ES11.All mode); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glStencilFunc", ExactSpelling = true)] internal extern static void StencilFunc(OpenTK.Graphics.ES11.All func, Int32 @ref, UInt32 mask); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glStencilMask", ExactSpelling = true)] internal extern static void StencilMask(UInt32 mask); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glStencilOp", ExactSpelling = true)] internal extern static void StencilOp(OpenTK.Graphics.ES11.All fail, OpenTK.Graphics.ES11.All zfail, OpenTK.Graphics.ES11.All zpass); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTestFenceNV", ExactSpelling = true)] internal extern static bool TestFenceNV(UInt32 fence); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexCoordPointer", ExactSpelling = true)] internal extern static void TexCoordPointer(Int32 size, OpenTK.Graphics.ES11.All type, Int32 stride, IntPtr pointer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexEnvf", ExactSpelling = true)] internal extern static void TexEnvf(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, Single param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexEnvfv", ExactSpelling = true)] internal extern static unsafe void TexEnvfv(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexEnvi", ExactSpelling = true)] internal extern static void TexEnvi(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, Int32 param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexEnviv", ExactSpelling = true)] internal extern static unsafe void TexEnviv(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexEnvx", ExactSpelling = true)] internal extern static void TexEnvx(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, int param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexEnvxOES", ExactSpelling = true)] internal extern static void TexEnvxOES(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, int param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexEnvxv", ExactSpelling = true)] internal extern static unsafe void TexEnvxv(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexEnvxvOES", ExactSpelling = true)] internal extern static unsafe void TexEnvxvOES(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexGenfOES", ExactSpelling = true)] internal extern static void TexGenfOES(OpenTK.Graphics.ES11.All coord, OpenTK.Graphics.ES11.All pname, Single param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexGenfvOES", ExactSpelling = true)] internal extern static unsafe void TexGenfvOES(OpenTK.Graphics.ES11.All coord, OpenTK.Graphics.ES11.All pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexGeniOES", ExactSpelling = true)] internal extern static void TexGeniOES(OpenTK.Graphics.ES11.All coord, OpenTK.Graphics.ES11.All pname, Int32 param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexGenivOES", ExactSpelling = true)] internal extern static unsafe void TexGenivOES(OpenTK.Graphics.ES11.All coord, OpenTK.Graphics.ES11.All pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexGenxOES", ExactSpelling = true)] internal extern static void TexGenxOES(OpenTK.Graphics.ES11.All coord, OpenTK.Graphics.ES11.All pname, int param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexGenxvOES", ExactSpelling = true)] internal extern static unsafe void TexGenxvOES(OpenTK.Graphics.ES11.All coord, OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexImage2D", ExactSpelling = true)] internal extern static void TexImage2D(OpenTK.Graphics.ES11.All target, Int32 level, Int32 internalformat, Int32 width, Int32 height, Int32 border, OpenTK.Graphics.ES11.All format, OpenTK.Graphics.ES11.All type, IntPtr pixels); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexParameterf", ExactSpelling = true)] internal extern static void TexParameterf(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, Single param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexParameterfv", ExactSpelling = true)] internal extern static unsafe void TexParameterfv(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, Single* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexParameteri", ExactSpelling = true)] internal extern static void TexParameteri(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, Int32 param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexParameteriv", ExactSpelling = true)] internal extern static unsafe void TexParameteriv(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, Int32* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexParameterx", ExactSpelling = true)] internal extern static void TexParameterx(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, int param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexParameterxOES", ExactSpelling = true)] internal extern static void TexParameterxOES(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, int param); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexParameterxv", ExactSpelling = true)] internal extern static unsafe void TexParameterxv(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexParameterxvOES", ExactSpelling = true)] internal extern static unsafe void TexParameterxvOES(OpenTK.Graphics.ES11.All target, OpenTK.Graphics.ES11.All pname, int* @params); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexSubImage2D", ExactSpelling = true)] internal extern static void TexSubImage2D(OpenTK.Graphics.ES11.All target, Int32 level, Int32 xoffset, Int32 yoffset, Int32 width, Int32 height, OpenTK.Graphics.ES11.All format, OpenTK.Graphics.ES11.All type, IntPtr pixels); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTranslatef", ExactSpelling = true)] internal extern static void Translatef(Single x, Single y, Single z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTranslatex", ExactSpelling = true)] internal extern static void Translatex(int x, int y, int z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTranslatexOES", ExactSpelling = true)] internal extern static void TranslatexOES(int x, int y, int z); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glUnmapBufferOES", ExactSpelling = true)] internal extern static bool UnmapBufferOES(OpenTK.Graphics.ES11.All target); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glVertexPointer", ExactSpelling = true)] internal extern static void VertexPointer(Int32 size, OpenTK.Graphics.ES11.All type, Int32 stride, IntPtr pointer); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glViewport", ExactSpelling = true)] internal extern static void Viewport(Int32 x, Int32 y, Int32 width, Int32 height); [System.Security.SuppressUnmanagedCodeSecurity()] [System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glWeightPointerOES", ExactSpelling = true)] internal extern static void WeightPointerOES(Int32 size, OpenTK.Graphics.ES11.All type, Int32 stride, IntPtr pointer); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass001.regclass001; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; using System.Reflection; public class MyClass { public int Field = 0; } public struct MyStruct { public int Number; } public enum MyEnum { First = 1, Second = 2, Third = 3 } public class MemberClass { /* Example of calling it: MemberClass staticMC =new MemberClass(); dynamic mc = staticMC; bool myBool; //This test the getter for the property myBool = true; staticMC.myBool = myBool; //We set the inner field myBool = mc.Property_bool; //We use the property to get the field if (myBool != true) return 1; //This tests the setter for the property myBool = true; mc.Property_bool = myBool; //We set the property myBool = statMc.myBool; // We get the inner field if (myBool != true) return 1; */ public bool myBool = true; public bool? myBoolNull = true; public bool?[] myBoolNullArr = new bool?[2]; public bool[] myBoolArr = new bool[2]; public char myChar = 'a'; public char? myCharNull = 'a'; public char?[] myCharNullArr = new char?[2]; public char[] myCharArr = new char[2]; public decimal myDecimal = 1m; public decimal? myDecimalNull = 1m; public decimal?[] myDecimalNullArr = new decimal?[2]; public decimal[] myDecimalArr = new decimal[2]; public dynamic myDynamic = new object(); public float myFloat = 3f; public float?[] myFloatNullArr = new float?[] { } ; public MyClass myClass = new MyClass() { Field = 2 } ; public MyClass[] myClassArr = new MyClass[3]; public MyEnum myEnum = MyEnum.First; public MyEnum? myEnumNull = MyEnum.First; public MyEnum?[] myEnumNullArr = new MyEnum?[3]; public MyEnum[] myEnumArr = new MyEnum[3]; public MyStruct myStruct = new MyStruct() { Number = 3 } ; public MyStruct? myStructNull = new MyStruct() { Number = 3 } ; public MyStruct?[] myStructNullArr = new MyStruct?[3]; public MyStruct[] myStructArr = new MyStruct[3]; public short myShort = 1; public short? myShortNull = 1; public short?[] myShortNullArr = new short?[2]; public short[] myShortArr = new short[2]; public string myString = string.Empty; public string[] myStringArr = new string[2]; public ulong myUlong = 1; public ulong? myUlongNull = 1; public ulong?[] myUlongNullArr = new ulong?[2]; public ulong[] myUlongArr = new ulong[2]; public bool Property_bool { protected set { myBool = value; } get { return false; } } public bool? Property_boolNull { protected set { myBoolNull = value; } get { return null; } } public bool?[] Property_boolNullArr { protected set { myBoolNullArr = value; } get { return new bool?[] { true, null, false } ; } } public bool[] Property_boolArr { protected set { myBoolArr = value; } get { return new bool[] { true, false } ; } } public char Property_char { private set { myChar = value; } get { return myChar; } } public char? Property_charNull { private set { myCharNull = value; } get { return myCharNull; } } public char?[] Property_charNullArr { private set { myCharNullArr = value; } get { return myCharNullArr; } } public char[] Property_charArr { private set { myCharArr = value; } get { return myCharArr; } } public decimal Property_decimal { internal set { myDecimal = value; } get { return myDecimal; } } public decimal? Property_decimalNull { internal set { myDecimalNull = value; } get { return myDecimalNull; } } public decimal?[] Property_decimalNullArr { protected internal set { myDecimalNullArr = value; } get { return myDecimalNullArr; } } public decimal[] Property_decimalArr { protected internal set { myDecimalArr = value; } get { return myDecimalArr; } } public dynamic Property_dynamic { get { return myDynamic; } set { myDynamic = value; } } public float Property_Float { get { return myFloat; } set { myFloat = value; } } public float?[] Property_FloatNullArr { get { return myFloatNullArr; } set { myFloatNullArr = value; } } public MyClass Property_MyClass { set { myClass = value; } } public MyClass[] Property_MyClassArr { set { myClassArr = value; } } public MyEnum Property_MyEnum { set { myEnum = value; } get { return myEnum; } } public MyEnum? Property_MyEnumNull { set { myEnumNull = value; } private get { return myEnumNull; } } public MyEnum?[] Property_MyEnumNullArr { set { myEnumNullArr = value; } private get { return myEnumNullArr; } } public MyEnum[] Property_MyEnumArr { set { myEnumArr = value; } private get { return myEnumArr; } } public MyStruct Property_MyStruct { get { return myStruct; } set { myStruct = value; } } public MyStruct? Property_MyStructNull { get { return myStructNull; } } public MyStruct?[] Property_MyStructNullArr { get { return myStructNullArr; } } public MyStruct[] Property_MyStructArr { get { return myStructArr; } } public short Property_short { set { myShort = value; } protected get { return myShort; } } public short? Property_shortNull { set { myShortNull = value; } protected get { return myShortNull; } } public short?[] Property_shortNullArr { set { myShortNullArr = value; } protected get { return myShortNullArr; } } public short[] Property_shortArr { set { myShortArr = value; } protected get { return myShortArr; } } public string Property_string { set { myString = value; } get { return myString; } } public string[] Property_stringArr { set { myStringArr = value; } get { return myStringArr; } } public ulong Property_ulong { set { myUlong = value; } protected internal get { return myUlong; } } public ulong? Property_ulongNull { set { myUlongNull = value; } protected internal get { return myUlongNull; } } public ulong?[] Property_ulongNullArr { set { myUlongNullArr = value; } protected internal get { return myUlongNullArr; } } public ulong[] Property_ulongArr { set { myUlongArr = value; } protected internal get { return myUlongArr; } } public static bool myBoolStatic; public static MyClass myClassStatic = new MyClass(); public static bool Property_boolStatic { protected set { myBoolStatic = value; } get { return myBoolStatic; } } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass001.regclass001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass001.regclass001; // <Title> Tests regular class regular property used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { return Test.TestGetMethod(new MemberClass()) + Test.TestSetMethod(new MemberClass()) == 0 ? 0 : 1; } public static int TestGetMethod(MemberClass mc) { dynamic dy = mc; dy.myBool = true; if (dy.Property_bool) //always return false return 1; else return 0; } public static int TestSetMethod(MemberClass mc) { dynamic dy = mc; try { dy.Property_bool = true; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleSetter, e.Message, "MemberClass.Property_bool", "set")) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass002.regclass002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass002.regclass002; // <Title> Tests regular class regular property used in argements of method invocation.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { private delegate int TestDec(char[] c); private static char[] s_charArray = new char[] { '0', 'a' }; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); TestDec td = t.TestMethod; MemberClass mc = new MemberClass(); mc.myCharArr = s_charArray; dynamic dy = mc; return td((char[])dy.Property_charArr); } public int TestMethod(char[] c) { if (ReferenceEquals(c, s_charArray) && c[0] == '0' && c[1] == 'a') return 0; else return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass003.regclass003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass003.regclass003; // <Title> Tests regular class regular property used in property-set body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { private static dynamic s_mc = new MemberClass(); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Dec = new short?[] { null, 0, -1 } ; if (s_mc.myShortNullArr[0] == null && s_mc.myShortNullArr[1] == 0 && s_mc.myShortNullArr[2] == -1) return 0; return 1; } public static short?[] Dec { set { s_mc.Property_shortNullArr = value; } get { return null; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass004.regclass004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass004.regclass004; // <Title> Tests regular class regular property used in short-circuit boolean expression and ternary operator expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); int loopCount = 0; dy.Property_decimal = 0M; while (dy.Property_decimal < 10) { System.Console.WriteLine((object)dy.Property_decimal); dy.Property_decimal++; loopCount++; } return (dy.Property_decimal == 10 && loopCount == 10) ? 0 : 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass005.regclass005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass005.regclass005; // <Title> Tests regular class regular property used in property set.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); try { t.TestProperty = null; //protected, should have exception return 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleSetter, e.Message, "MemberClass.Property_boolNull")) return 0; } return 1; } public bool? TestProperty { set { dynamic dy = new MemberClass(); dy.Property_boolNull = value; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass006.regclass006 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass006.regclass006; // <Title> Tests regular class regular property used in property get body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); bool?[] array = t.TestProperty; if (array.Length == 3 && array[0] == true && array[1] == null && array[2] == false) return 0; return 1; } public bool?[] TestProperty { get { dynamic dy = new MemberClass(); return dy.Property_boolNullArr; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass007.regclass007 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass007.regclass007; // <Title> Tests regular class regular property used in static method body.</Title> // <Description> // Derived class call protected parent property. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test : MemberClass { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test mc = new Test(); dynamic dy = mc; dy.Property_boolArr = new bool[3]; bool[] result = dy.Property_boolArr; if (result.Length != 2 || result[0] != true || result[1] != false) return 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass008.regclass008 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass008.regclass008; // <Title> Tests regular class regular property used in indexer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Collections.Generic; public class Test { private Dictionary<string, int> _dic = new Dictionary<string, int>(); private MemberClass _mc = new MemberClass(); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { if (TestSet() == 0 && TestGet() == 0) return 0; else return 1; } private static int TestSet() { Test t = new Test(); t["a"] = 10; t[string.Empty] = -1; if (t._dic["a"] == 10 && t._dic[string.Empty] == -1 && (string)t._mc.Property_string == string.Empty) return 0; else return 1; } private static int TestGet() { Test t = new Test(); t._dic["Test0"] = 2; if (t["Test0"] == 2) return 0; else return 1; } public int this[string i] { set { dynamic dy = _mc; dy.Property_string = i; _dic.Add((string)dy.Property_string, value); _mc = dy; //this is to circumvent the boxing of the struct } get { _mc.Property_string = i; dynamic dy = _mc; return _dic[(string)dy.Property_string]; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass010.regclass010 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass010.regclass010; // <Title> Tests regular class regular property used in try/catch/finally.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); dynamic dy = mc; dy.myChar = 'a'; try { dy.Property_char = 'x'; //private, should have exception. return 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (!ErrorVerifier.Verify(ErrorMessageId.InaccessibleSetter, e.Message, "MemberClass.Property_char")) return 1; if ((char)dy.Property_char != 'a') return 1; } finally { dy.myChar = 'b'; } if ((char)dy.Property_char != 'b') return 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass011.regclass011 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass011.regclass011; // <Title> Tests regular class regular property used in anonymous method.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); dynamic dy = mc; Func<char, char?> func = delegate (char arg) { mc.myCharNull = arg; dy = mc; // struct need to re-assign the value. return dy.Property_charNull; } ; char? result = func('a'); if (result == 'a') return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass012.regclass012 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass012.regclass012; // <Title> Tests regular class regular property used in lambda expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Linq; public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { return TestGet() + TestSet(); } private static int TestSet() { MemberClass mc = new MemberClass(); dynamic dy = mc; dy.Property_ulongArr = new ulong[] { 1, 2, 3, 4, 3, 4 } ; dy.Property_ulong = (ulong)4; var list = mc.Property_ulongArr.Where(p => p == (ulong)mc.Property_ulong).ToList(); return list.Count - 2; } private static int TestGet() { MemberClass mc = new MemberClass(); dynamic dy = mc; mc.Property_ulongArr = new ulong[] { 1, 2, 3, 4, 3, 4 } ; mc.Property_ulong = 4; var list = ((ulong[])dy.Property_ulongArr).Where(p => p == (ulong)dy.Property_ulong).ToList(); return list.Count - 2; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass013.regclass013 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass013.regclass013; // <Title> Tests regular class regular property used in the foreach loop body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); dynamic dy = mc; char result = default(char); char[] LoopArray = new char[] { 'a', 'b' } ; foreach (char c in LoopArray) { mc.myCharNullArr = new char?[] { c } ; dy = mc; result = ((char?[])dy.myCharNullArr)[0].Value; } if (result == 'b') return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass014.regclass014 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass014.regclass014; // <Title> Tests regular class regular property used in do/while expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); mc.Property_decimalNull = -10.1M; dynamic dy = mc; do { mc.Property_decimalNull += 1; dy = mc; // for struct we should re-assign. } while ((decimal?)dy.Property_decimalNull < 0M); if ((decimal?)mc.Property_decimalNull == 0.9M) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass017.regclass017 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass017.regclass017; // <Title> Tests regular class regular property used in using expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.IO; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); mc.myChar = (char)256; dynamic dy = mc; using (MemoryStream ms = new MemoryStream((int)dy.Property_char)) { if (ms.Capacity != 256) return 1; } return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass018.regclass018 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass018.regclass018; // <Title> Tests regular class regular property used in try/catch/finally.</Title> // <Description> // try/catch/finally that uses an anonymous method and refer two dynamic parameters. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); mc.Property_decimalNullArr = new decimal?[] { 0M, 1M, 1.3M } ; mc.myStruct = new MyStruct() { Number = 3 } ; dynamic dy = mc; int result = -1; try { Func<decimal?[], MyStruct, int> func = delegate (decimal?[] x, MyStruct y) { int tmp = 0; foreach (decimal? d in x) { tmp += (int)d.Value; } tmp += y.Number; return tmp; } ; result = func((decimal?[])dy.Property_decimalNullArr, (MyStruct)dy.Property_MyStruct); } finally { result += (int)dy.Property_MyStruct.Number; } if (result != 8) return 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass019.regclass019 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass019.regclass019; // <Title> Tests regular class regular property used in foreach.</Title> // <Description> // foreach inside a using statement that uses the dynamic introduced by the using statement. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.IO; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int[] array = new int[] { 1, 2 } ; MemoryStream ms = new MemoryStream(new byte[] { 84, 101, 115, 116 } ); //Test MemberClass mc = new MemberClass(); mc.Property_dynamic = true; dynamic dy = mc; string result = string.Empty; using (dynamic sr = new StreamReader(ms, (bool)dy.Property_dynamic)) { foreach (int s in array) { ms.Position = 0; string m = ((StreamReader)sr).ReadToEnd(); result += m + s.ToString(); } } //Test1Test2 if (result == "Test1Test2") return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass020.regclass020 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass020.regclass020; // <Title> Tests regular class regular property used in iterator that calls to a lambda expression.</Title> // <Description> // foreach inside a using statement that uses the dynamic introduced by the using statement. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Collections; public class Test { private static MemberClass s_mc; private static dynamic s_dy; static Test() { s_mc = new MemberClass(); } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { decimal index = 1M; s_mc.Property_decimalArr = new decimal[] { 1M, 2M, 3M } ; s_dy = s_mc; Test t = new Test(); foreach (decimal i in t.Increment(0)) { if (i != index) return 1; index = index + 1; } if (index != 4) return 1; return 0; } public IEnumerable Increment(int number) { while (number < s_mc.Property_decimalArr.Length) { Func<decimal[], decimal> func = (decimal[] x) => x[number++]; yield return func(s_dy.Property_decimalArr); } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass021.regclass021 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass021.regclass021; // <Title> Tests regular class regular property used in object initializer inside a collection initializer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Collections.Generic; public class Test { private float _field1; private float?[] _field2; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); mc.Property_Float = 1.23f; mc.Property_FloatNullArr = new float?[] { null, 1.33f } ; dynamic dy = mc; List<Test> list = new List<Test>() { new Test() { _field1 = dy.Property_Float, _field2 = dy.Property_FloatNullArr } } ; if (list.Count == 1 && list[0]._field1 == 1.23f && list[0]._field2.Length == 2 && list[0]._field2[0] == null && list[0]._field2[1] == 1.33f) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass022.regclass022 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass022.regclass022; // <Title> Tests regular class regular property used in static method body.</Title> // <Description> // set only property access. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); dynamic dy = mc; dy.Property_MyClass = new MyClass() { Field = -1 } ; mc = dy; //to circumvent the boxing of the struct if (mc.myClass.Field == -1) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass023.regclass023 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass023.regclass023; // <Title> Tests regular class regular property used in static method body.</Title> // <Description> // Negative: set only property access // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); dynamic dy = mc; dy.Property_MyClass = new MyClass() { Field = -1 } ; mc = dy; //to circumvent the boxing of the struct if (mc.myClass.Field != -1) return 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass024.regclass024 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass024.regclass024; // <Title> Tests regular class regular property used in throws.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); dynamic dy = mc; dy.Property_string = "Test Message"; try { throw new ArithmeticException((string)dy.Property_string); } catch (ArithmeticException ae) { if (ae.Message == "Test Message") return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass025.regclass025 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass025.regclass025; // <Title> Tests regular class regular property used in field initializer.</Title> // <Description> // Negative // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { private static MemberClass s_mc; private static dynamic s_dy; private MyEnum _me = s_dy.Property_MyEnum; static Test() { s_mc = new MemberClass(); s_dy = s_mc; s_dy.Property_MyEnum = MyEnum.Third; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); if (t._me != MyEnum.Third) return 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass026.regclass026 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass026.regclass026; // <Title> Tests regular class regular property used in set only property body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { private MemberClass _mc; private MyEnum? MyProp { set { _mc = new MemberClass(); dynamic dy = _mc; dy.Property_MyEnumNull = value; _mc = dy; // for struct. } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); t.MyProp = MyEnum.Second; if (t._mc.myEnumNull == MyEnum.Second) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass027.regclass027 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass027.regclass027; // <Title> Tests regular class regular property used in read only property body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { private MyEnum MyProp { get { dynamic dy = new MemberClass(); dy.Property_MyEnumArr = new MyEnum[] { MyEnum.Second, default (MyEnum)} ; return dy.myEnumArr[0]; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); if (t.MyProp == MyEnum.Second) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass028.regclass028 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass028.regclass028; // <Title> Tests regular class regular property used in static read only property body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { private static MyEnum? MyProp { get { dynamic dy = new MemberClass(); dy.Property_MyEnumNullArr = new MyEnum?[] { null, MyEnum.Second, default (MyEnum)} ; return dy.myEnumNullArr[0]; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { if (Test.MyProp == null) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass029.regclass029 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass029.regclass029; // <Title> Tests regular class regular property used in static method body.</Title> // <Description> // get only property access. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); mc.myStructNull = new MyStruct() { Number = int.MinValue } ; dynamic dy = mc; MyStruct? result = dy.Property_MyStructNull; if (result.Value.Number == int.MinValue) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass030.regclass030 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass030.regclass030; // <Title> Tests regular class regular property used in method call argument.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); mc.myStructArr = new MyStruct[] { new MyStruct() { Number = 1 } , new MyStruct() { Number = -1 } } ; dynamic dy = mc; bool result = TestMethod(1, string.Empty, (MyStruct[])dy.Property_MyStructArr); if (result) return 0; return 1; } private static bool TestMethod<V, U>(V v, U u, params MyStruct[] ms) { if (v.GetType() != typeof(int)) return false; if (u.GetType() != typeof(string)) return false; if (ms.Length != 2 || ms[0].Number != 1 || ms[1].Number != -1) return false; return true; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass031.regclass031 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass031.regclass031; // <Title> Tests regular class regular property used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); dynamic dy = mc; mc.myStructNullArr = new MyStruct?[] { null, new MyStruct() { Number = -1 } } ; if (((MyStruct?[])dy.Property_MyStructNullArr)[0] == null) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass032.regclass032 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass032.regclass032; // <Title> Tests regular class regular property used in lock expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test : MemberClass { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); dynamic dy = mc; dy.Property_shortNull = (short)-1; try { lock (dy.Property_shortNull) { } } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.BadProtectedAccess, e.Message, "MemberClass.Property_shortNull", "MemberClass", "Test")) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass034.regclass034 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass034.regclass034; // <Title> Tests regular class regular property used in foreach loop.</Title> // <Description> // Negative // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); mc.Property_shortArr = new short[] { 1, 2, 3, 4, 5 } ; dynamic dy = mc; short i = 1; try { foreach (var x in dy.Property_shortArr) //protected { if (i++ != (short)x) return 1; } } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleGetter, e.Message, "MemberClass.Property_shortArr")) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass035.regclass035 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclassregprop.regclassregprop; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.regclass.regclass035.regclass035; // <Title> Tests regular class regular property used in method body.</Title> // <Description> // Negative // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { return Test.TestGetMethod(new MemberClass()) + Test.TestSetMethod(new MemberClass()) == 0 ? 0 : 1; } public static int TestGetMethod(MemberClass mc) { dynamic dy = mc; mc.Property_ulongNullArr = new ulong?[] { null, 1 } ; if (dy.Property_ulongNullArr.Length == 2 && dy.Property_ulongNullArr[0] == null && dy.Property_ulongNullArr[1] == 1) return 0; else return 1; } public static int TestSetMethod(MemberClass mc) { dynamic dy = mc; dy.Property_ulongNullArr = new ulong?[] { null, 1 } ; if (mc.Property_ulongNullArr.Length == 2 && mc.Property_ulongNullArr[0] == null && mc.Property_ulongNullArr[1] == 1) return 0; else return 1; } } //</Code> }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using Orleans.Runtime; using Orleans.Streams; namespace Orleans.Providers.Streams.Common { /// <summary> /// The PooledQueueCache is a cache that is intended to serve as a message cache in an IQueueCache. /// It is capable of storing large numbers of messages (gigs worth of messages) for extended periods /// of time (minutes to indefinite), while incurring a minimal performance hit due to garbage collection. /// This pooled cache allocates memory and never releases it. It keeps freed resources available in pools /// that remain in application use through the life of the service. This means these objects go to gen2, /// are compacted, and then stay there. This is relatively cheap, as the only cost they now incur is /// the cost of checking to see if they should be freed in each collection cycle. Since this cache uses /// small numbers of large objects with relatively simple object graphs, they are less costly to check /// then large numbers of smaller objects with more complex object graphs. /// For performance reasons this cache is designed to more closely align with queue specific data. This is, /// in part, why, unlike the SimpleQueueCache, this cache does not implement IQueueCache. It is intended /// to be used in queue specific implementations of IQueueCache. /// </summary> public class PooledQueueCache: IPurgeObservable { // linked list of message bocks. First is newest. private readonly LinkedList<CachedMessageBlock> messageBlocks; private readonly CachedMessagePool pool; private readonly ICacheDataAdapter cacheDataAdapter; private readonly ILogger logger; private readonly ICacheMonitor cacheMonitor; private readonly TimeSpan purgeMetadataInterval; private readonly PeriodicAction periodicMonitoring; private readonly PeriodicAction periodicMetadaPurging; private readonly Dictionary<StreamId, (DateTime TimeStamp, StreamSequenceToken Token)> lastPurgedToken = new Dictionary<StreamId, (DateTime TimeStamp, StreamSequenceToken Token)>(); /// <summary> /// Gets the cached message most recently added. /// </summary> public CachedMessage? Newest { get { if (IsEmpty) return null; return messageBlocks.First.Value.NewestMessage; } } /// <summary> /// Gets the oldest message in cache. /// </summary> public CachedMessage? Oldest { get { if (IsEmpty) return null; return messageBlocks.Last.Value.OldestMessage; } } /// <summary> /// Gets the cached message count. /// </summary> public int ItemCount { get; private set; } /// <summary> /// Pooled queue cache is a cache of message that obtains resource from a pool /// </summary> /// <param name="cacheDataAdapter">The cache data adapter.</param> /// <param name="logger">The logger.</param> /// <param name="cacheMonitor">The cache monitor.</param> /// <param name="cacheMonitorWriteInterval">The cache monitor write interval. Only triggered for active caches.</param> /// <param name="purgeMetadataInterval">The interval after which to purge cache metadata.</param> public PooledQueueCache( ICacheDataAdapter cacheDataAdapter, ILogger logger, ICacheMonitor cacheMonitor, TimeSpan? cacheMonitorWriteInterval, TimeSpan? purgeMetadataInterval = null) { this.cacheDataAdapter = cacheDataAdapter ?? throw new ArgumentNullException("cacheDataAdapter"); this.logger = logger ?? throw new ArgumentNullException("logger"); this.ItemCount = 0; pool = new CachedMessagePool(cacheDataAdapter); messageBlocks = new LinkedList<CachedMessageBlock>(); this.cacheMonitor = cacheMonitor; if (this.cacheMonitor != null && cacheMonitorWriteInterval.HasValue) { this.periodicMonitoring = new PeriodicAction(cacheMonitorWriteInterval.Value, this.ReportCacheMessageStatistics); } if (purgeMetadataInterval.HasValue) { this.purgeMetadataInterval = purgeMetadataInterval.Value; this.periodicMetadaPurging = new PeriodicAction(purgeMetadataInterval.Value.Divide(5), this.PurgeMetadata); } } /// <summary> /// Indicates whether the cache is empty /// </summary> public bool IsEmpty => messageBlocks.Count == 0 || (messageBlocks.Count == 1 && messageBlocks.First.Value.IsEmpty); /// <summary> /// Acquires a cursor to enumerate through the messages in the cache at the provided sequenceToken, /// filtered on the specified stream. /// </summary> /// <param name="streamId">stream identity</param> /// <param name="sequenceToken"></param> /// <returns></returns> public object GetCursor(StreamId streamId, StreamSequenceToken sequenceToken) { var cursor = new Cursor(streamId); SetCursor(cursor, sequenceToken); return cursor; } private void ReportCacheMessageStatistics() { if (this.IsEmpty) { this.cacheMonitor.ReportMessageStatistics(null, null, null, this.ItemCount); } else { var newestMessage = this.Newest.Value; var oldestMessage = this.Oldest.Value; var newestMessageEnqueueTime = newestMessage.EnqueueTimeUtc; var oldestMessageEnqueueTime = oldestMessage.EnqueueTimeUtc; var oldestMessageDequeueTime = oldestMessage.DequeueTimeUtc; this.cacheMonitor.ReportMessageStatistics(oldestMessageEnqueueTime, oldestMessageDequeueTime, newestMessageEnqueueTime, this.ItemCount); } } private void PurgeMetadata() { var now = DateTime.UtcNow; var keys = new List<StreamId>(); // Get all keys older than this.purgeMetadataInterval foreach (var kvp in this.lastPurgedToken) { if (kvp.Value.TimeStamp + this.purgeMetadataInterval < now) { keys.Add(kvp.Key); } } // Remove the expired entries foreach (var key in keys) { this.lastPurgedToken.Remove(key); } } private void TrackAndPurgeMetadata(CachedMessage messageToRemove) { // If tracking of evicted message metadata is disabled, do nothing if (this.periodicMetadaPurging == null) return; var now = DateTime.UtcNow; var streamId = messageToRemove.StreamId; var token = this.cacheDataAdapter.GetSequenceToken(ref messageToRemove); this.lastPurgedToken[streamId] = (now, token); this.periodicMetadaPurging.TryAction(now); } private void SetCursor(Cursor cursor, StreamSequenceToken sequenceToken) { // If nothing in cache, unset token, and wait for more data. if (messageBlocks.Count == 0) { cursor.State = CursorStates.Unset; cursor.SequenceToken = sequenceToken; return; } LinkedListNode<CachedMessageBlock> newestBlock = messageBlocks.First; // if sequenceToken is null, iterate from newest message in cache if (sequenceToken == null) { cursor.State = CursorStates.Idle; cursor.CurrentBlock = newestBlock; cursor.Index = newestBlock.Value.NewestMessageIndex; cursor.SequenceToken = newestBlock.Value.GetNewestSequenceToken(cacheDataAdapter); return; } // If sequenceToken is too new to be in cache, unset token, and wait for more data. CachedMessage newestMessage = newestBlock.Value.NewestMessage; if (newestMessage.Compare(sequenceToken) < 0) { cursor.State = CursorStates.Unset; cursor.SequenceToken = sequenceToken; return; } // Check to see if sequenceToken is too old to be in cache var oldestBlock = messageBlocks.Last; var oldestMessage = oldestBlock.Value.OldestMessage; if (oldestMessage.Compare(sequenceToken) > 0) { // Check if we missed an event since we last purged the cache if (this.lastPurgedToken.TryGetValue(cursor.StreamId, out var entry) && sequenceToken.CompareTo(entry.Token) >= 0) { // If the token is more recent than the last purged token, then we didn't lose anything. Start from the oldest message in cache cursor.State = CursorStates.Set; cursor.CurrentBlock = oldestBlock; cursor.Index = oldestBlock.Value.OldestMessageIndex; cursor.SequenceToken = oldestBlock.Value.GetOldestSequenceToken(cacheDataAdapter); return; } else { throw new QueueCacheMissException(sequenceToken, messageBlocks.Last.Value.GetOldestSequenceToken(cacheDataAdapter), messageBlocks.First.Value.GetNewestSequenceToken(cacheDataAdapter)); } } // Find block containing sequence number, starting from the newest and working back to oldest LinkedListNode<CachedMessageBlock> node = messageBlocks.First; while (true) { CachedMessage oldestMessageInBlock = node.Value.OldestMessage; if (oldestMessageInBlock.Compare(sequenceToken) <= 0) { break; } node = node.Next; } // return cursor from start. cursor.CurrentBlock = node; cursor.Index = node.Value.GetIndexOfFirstMessageLessThanOrEqualTo(sequenceToken); // if cursor has been idle, move to next message after message specified by sequenceToken if(cursor.State == CursorStates.Idle) { // if there are more messages in this block, move to next message if (!cursor.IsNewestInBlock) { cursor.Index++; } // if this is the newest message in this block, move to oldest message in newer block else if (node.Previous != null) { cursor.CurrentBlock = node.Previous; cursor.Index = cursor.CurrentBlock.Value.OldestMessageIndex; } else { cursor.State = CursorStates.Idle; return; } } cursor.SequenceToken = cursor.CurrentBlock.Value.GetSequenceToken(cursor.Index, cacheDataAdapter); cursor.State = CursorStates.Set; } /// <summary> /// Acquires the next message in the cache at the provided cursor /// </summary> /// <param name="cursorObj"></param> /// <param name="message"></param> /// <returns></returns> public bool TryGetNextMessage(object cursorObj, out IBatchContainer message) { message = null; if (cursorObj == null) { throw new ArgumentNullException("cursorObj"); } var cursor = cursorObj as Cursor; if (cursor == null) { throw new ArgumentOutOfRangeException("cursorObj", "Cursor is bad"); } if (cursor.State != CursorStates.Set) { SetCursor(cursor, cursor.SequenceToken); if (cursor.State != CursorStates.Set) { return false; } } // has this message been purged CachedMessage oldestMessage = messageBlocks.Last.Value.OldestMessage; if (oldestMessage.Compare(cursor.SequenceToken) > 0) { throw new QueueCacheMissException(cursor.SequenceToken, messageBlocks.Last.Value.GetOldestSequenceToken(cacheDataAdapter), messageBlocks.First.Value.GetNewestSequenceToken(cacheDataAdapter)); } // Iterate forward (in time) in the cache until we find a message on the stream or run out of cached messages. // Note that we get the message from the current cursor location, then move it forward. This means that if we return true, the cursor // will point to the next message after the one we're returning. while (cursor.State == CursorStates.Set) { CachedMessage currentMessage = cursor.Message; // Have we caught up to the newest event, if so set cursor to idle. if (cursor.CurrentBlock == messageBlocks.First && cursor.IsNewestInBlock) { cursor.State = CursorStates.Idle; cursor.SequenceToken = messageBlocks.First.Value.GetNewestSequenceToken(cacheDataAdapter); } else // move to next { int index; if (cursor.IsNewestInBlock) { cursor.CurrentBlock = cursor.CurrentBlock.Previous; cursor.CurrentBlock.Value.TryFindFirstMessage(cursor.StreamId, this.cacheDataAdapter, out index); } else { cursor.CurrentBlock.Value.TryFindNextMessage(cursor.Index + 1, cursor.StreamId, this.cacheDataAdapter, out index); } cursor.Index = index; } // check if this message is in the cursor's stream if (currentMessage.CompareStreamId(cursor.StreamId)) { message = cacheDataAdapter.GetBatchContainer(ref currentMessage); cursor.SequenceToken = cursor.CurrentBlock.Value.GetSequenceToken(cursor.Index, cacheDataAdapter); return true; } } return false; } /// <summary> /// Add a list of queue message to the cache /// </summary> /// <param name="messages"></param> /// <param name="dequeueTime"></param> /// <returns></returns> public void Add(List<CachedMessage> messages, DateTime dequeueTime) { foreach (var message in messages) { this.Add(message); } this.cacheMonitor?.TrackMessagesAdded(messages.Count); periodicMonitoring?.TryAction(dequeueTime); } private void Add(CachedMessage message) { // allocate message from pool CachedMessageBlock block = pool.AllocateMessage(message); // If new block, add message block to linked list if (block != messageBlocks.FirstOrDefault()) messageBlocks.AddFirst(block.Node); ItemCount++; } /// <summary> /// Remove oldest message in the cache, remove oldest block too if the block is empty /// </summary> public void RemoveOldestMessage() { TrackAndPurgeMetadata(this.messageBlocks.Last.Value.OldestMessage); this.messageBlocks.Last.Value.Remove(); this.ItemCount--; CachedMessageBlock lastCachedMessageBlock = this.messageBlocks.Last.Value; // if block is currently empty, but all capacity has been exausted, remove if (lastCachedMessageBlock.IsEmpty && !lastCachedMessageBlock.HasCapacity) { lastCachedMessageBlock.Dispose(); this.messageBlocks.RemoveLast(); } } private enum CursorStates { Unset, // Not yet set, or points to some data in the future. Set, // Points to a message in the cache Idle, // Has iterated over all relevant events in the cache and is waiting for more data on the stream. } private class Cursor { public readonly StreamId StreamId; public Cursor(StreamId streamId) { StreamId = streamId; State = CursorStates.Unset; } public CursorStates State; // current sequence token public StreamSequenceToken SequenceToken; // reference into cache public LinkedListNode<CachedMessageBlock> CurrentBlock; public int Index; // utilities public bool IsNewestInBlock => Index == CurrentBlock.Value.NewestMessageIndex; public CachedMessage Message => CurrentBlock.Value[Index]; } } }
using System; using Lucene.Net.Documents; using Lucene.Net.Randomized.Generators; using Lucene.Net.Support; using NUnit.Framework; using Console = Lucene.Net.Support.SystemConsole; namespace Lucene.Net.Search { using DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity; using Directory = Lucene.Net.Store.Directory; using DirectoryReader = Lucene.Net.Index.DirectoryReader; using Document = Documents.Document; using Field = Field; using IndexReader = Lucene.Net.Index.IndexReader; using IOContext = Lucene.Net.Store.IOContext; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* * 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using Similarity = Lucene.Net.Search.Similarities.Similarity; using Term = Lucene.Net.Index.Term; using TestUtil = Lucene.Net.Util.TestUtil; /// <summary> /// Test BooleanQuery2 against BooleanQuery by overriding the standard query parser. /// this also tests the scoring order of BooleanQuery. /// </summary> [TestFixture] public class TestBoolean2 : LuceneTestCase { private static IndexSearcher Searcher; private static IndexSearcher BigSearcher; private static IndexReader Reader; private static IndexReader LittleReader; private static int NUM_EXTRA_DOCS = 6000; public const string field = "field"; private static Directory Directory; private static Directory Dir2; private static int MulFactor; /// <summary> /// LUCENENET specific /// Is non-static because NewIndexWriterConfig is no longer static. /// </summary> [OneTimeSetUp] public override void BeforeClass() { base.BeforeClass(); Directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), Directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy())); for (int i = 0; i < DocFields.Length; i++) { Document doc = new Document(); doc.Add(NewTextField(field, DocFields[i], Field.Store.NO)); writer.AddDocument(doc); } writer.Dispose(); LittleReader = DirectoryReader.Open(Directory); Searcher = NewSearcher(LittleReader); // this is intentionally using the baseline sim, because it compares against bigSearcher (which uses a random one) Searcher.Similarity = new DefaultSimilarity(); // Make big index Dir2 = new MockDirectoryWrapper(Random(), new RAMDirectory(Directory, IOContext.DEFAULT)); // First multiply small test index: MulFactor = 1; int docCount = 0; if (VERBOSE) { Console.WriteLine("\nTEST: now copy index..."); } do { if (VERBOSE) { Console.WriteLine("\nTEST: cycle..."); } Directory copy = new MockDirectoryWrapper(Random(), new RAMDirectory(Dir2, IOContext.DEFAULT)); RandomIndexWriter w = new RandomIndexWriter(Random(), Dir2, Similarity, TimeZone); w.AddIndexes(copy); docCount = w.MaxDoc; w.Dispose(); MulFactor *= 2; } while (docCount < 3000); RandomIndexWriter riw = new RandomIndexWriter(Random(), Dir2, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(TestUtil.NextInt(Random(), 50, 1000))); Document doc_ = new Document(); doc_.Add(NewTextField("field2", "xxx", Field.Store.NO)); for (int i = 0; i < NUM_EXTRA_DOCS / 2; i++) { riw.AddDocument(doc_); } doc_ = new Document(); doc_.Add(NewTextField("field2", "big bad bug", Field.Store.NO)); for (int i = 0; i < NUM_EXTRA_DOCS / 2; i++) { riw.AddDocument(doc_); } Reader = riw.Reader; BigSearcher = NewSearcher(Reader); riw.Dispose(); } [OneTimeTearDown] public override void AfterClass() { Reader.Dispose(); LittleReader.Dispose(); Dir2.Dispose(); Directory.Dispose(); Searcher = null; Reader = null; LittleReader = null; Dir2 = null; Directory = null; BigSearcher = null; base.AfterClass(); } private static string[] DocFields = new string[] { "w1 w2 w3 w4 w5", "w1 w3 w2 w3", "w1 xx w2 yy w3", "w1 w3 xx w2 yy w3" }; public virtual void QueriesTest(Query query, int[] expDocNrs) { TopScoreDocCollector collector = TopScoreDocCollector.Create(1000, false); Searcher.Search(query, null, collector); ScoreDoc[] hits1 = collector.GetTopDocs().ScoreDocs; collector = TopScoreDocCollector.Create(1000, true); Searcher.Search(query, null, collector); ScoreDoc[] hits2 = collector.GetTopDocs().ScoreDocs; Assert.AreEqual(MulFactor * collector.TotalHits, BigSearcher.Search(query, 1).TotalHits); CheckHits.CheckHitsQuery(query, hits1, hits2, expDocNrs); } [Test] public virtual void TestQueries01() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(field, "w3")), Occur.MUST); query.Add(new TermQuery(new Term(field, "xx")), Occur.MUST); int[] expDocNrs = new int[] { 2, 3 }; QueriesTest(query, expDocNrs); } [Test] public virtual void TestQueries02() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(field, "w3")), Occur.MUST); query.Add(new TermQuery(new Term(field, "xx")), Occur.SHOULD); int[] expDocNrs = new int[] { 2, 3, 1, 0 }; QueriesTest(query, expDocNrs); } [Test] public virtual void TestQueries03() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(field, "w3")), Occur.SHOULD); query.Add(new TermQuery(new Term(field, "xx")), Occur.SHOULD); int[] expDocNrs = new int[] { 2, 3, 1, 0 }; QueriesTest(query, expDocNrs); } [Test] public virtual void TestQueries04() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(field, "w3")), Occur.SHOULD); query.Add(new TermQuery(new Term(field, "xx")), Occur.MUST_NOT); int[] expDocNrs = new int[] { 1, 0 }; QueriesTest(query, expDocNrs); } [Test] public virtual void TestQueries05() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(field, "w3")), Occur.MUST); query.Add(new TermQuery(new Term(field, "xx")), Occur.MUST_NOT); int[] expDocNrs = new int[] { 1, 0 }; QueriesTest(query, expDocNrs); } [Test] public virtual void TestQueries06() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(field, "w3")), Occur.MUST); query.Add(new TermQuery(new Term(field, "xx")), Occur.MUST_NOT); query.Add(new TermQuery(new Term(field, "w5")), Occur.MUST_NOT); int[] expDocNrs = new int[] { 1 }; QueriesTest(query, expDocNrs); } [Test] public virtual void TestQueries07() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(field, "w3")), Occur.MUST_NOT); query.Add(new TermQuery(new Term(field, "xx")), Occur.MUST_NOT); query.Add(new TermQuery(new Term(field, "w5")), Occur.MUST_NOT); int[] expDocNrs = new int[] { }; QueriesTest(query, expDocNrs); } [Test] public virtual void TestQueries08() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(field, "w3")), Occur.MUST); query.Add(new TermQuery(new Term(field, "xx")), Occur.SHOULD); query.Add(new TermQuery(new Term(field, "w5")), Occur.MUST_NOT); int[] expDocNrs = new int[] { 2, 3, 1 }; QueriesTest(query, expDocNrs); } [Test] public virtual void TestQueries09() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(field, "w3")), Occur.MUST); query.Add(new TermQuery(new Term(field, "xx")), Occur.MUST); query.Add(new TermQuery(new Term(field, "w2")), Occur.MUST); query.Add(new TermQuery(new Term(field, "zz")), Occur.SHOULD); int[] expDocNrs = new int[] { 2, 3 }; QueriesTest(query, expDocNrs); } [Test] public virtual void TestQueries10() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(field, "w3")), Occur.MUST); query.Add(new TermQuery(new Term(field, "xx")), Occur.MUST); query.Add(new TermQuery(new Term(field, "w2")), Occur.MUST); query.Add(new TermQuery(new Term(field, "zz")), Occur.SHOULD); int[] expDocNrs = new int[] { 2, 3 }; Similarity oldSimilarity = Searcher.Similarity; try { Searcher.Similarity = new DefaultSimilarityAnonymousInnerClassHelper(this); QueriesTest(query, expDocNrs); } finally { Searcher.Similarity = oldSimilarity; } } private class DefaultSimilarityAnonymousInnerClassHelper : DefaultSimilarity { private readonly TestBoolean2 OuterInstance; public DefaultSimilarityAnonymousInnerClassHelper(TestBoolean2 outerInstance) { this.OuterInstance = outerInstance; } public override float Coord(int overlap, int maxOverlap) { return overlap / ((float)maxOverlap - 1); } } [Test] public virtual void TestRandomQueries() { string[] vals = new string[] { "w1", "w2", "w3", "w4", "w5", "xx", "yy", "zzz" }; int tot = 0; BooleanQuery q1 = null; try { // increase number of iterations for more complete testing int num = AtLeast(20); for (int i = 0; i < num; i++) { int level = Random().Next(3); q1 = RandBoolQuery(new Random(Random().Next()), Random().NextBoolean(), level, field, vals, null); // Can't sort by relevance since floating point numbers may not quite // match up. Sort sort = Sort.INDEXORDER; QueryUtils.Check(Random(), q1, Searcher, Similarity); // baseline sim try { // a little hackish, QueryUtils.check is too costly to do on bigSearcher in this loop. Searcher.Similarity = BigSearcher.Similarity; // random sim QueryUtils.Check(Random(), q1, Searcher, Similarity); } finally { Searcher.Similarity = new DefaultSimilarity(); // restore } TopFieldCollector collector = TopFieldCollector.Create(sort, 1000, false, true, true, true); Searcher.Search(q1, null, collector); ScoreDoc[] hits1 = collector.GetTopDocs().ScoreDocs; collector = TopFieldCollector.Create(sort, 1000, false, true, true, false); Searcher.Search(q1, null, collector); ScoreDoc[] hits2 = collector.GetTopDocs().ScoreDocs; tot += hits2.Length; CheckHits.CheckEqual(q1, hits1, hits2); BooleanQuery q3 = new BooleanQuery(); q3.Add(q1, Occur.SHOULD); q3.Add(new PrefixQuery(new Term("field2", "b")), Occur.SHOULD); TopDocs hits4 = BigSearcher.Search(q3, 1); Assert.AreEqual(MulFactor * collector.TotalHits + NUM_EXTRA_DOCS / 2, hits4.TotalHits); } } catch (Exception) { // For easier debugging Console.WriteLine("failed query: " + q1); throw; } // System.out.println("Total hits:"+tot); } // used to set properties or change every BooleanQuery // generated from randBoolQuery. public interface Callback { void PostCreate(BooleanQuery q); } // Random rnd is passed in so that the exact same random query may be created // more than once. public static BooleanQuery RandBoolQuery(Random rnd, bool allowMust, int level, string field, string[] vals, Callback cb) { BooleanQuery current = new BooleanQuery(rnd.Next() < 0); for (int i = 0; i < rnd.Next(vals.Length) + 1; i++) { int qType = 0; // term query if (level > 0) { qType = rnd.Next(10); } Query q; if (qType < 3) { q = new TermQuery(new Term(field, vals[rnd.Next(vals.Length)])); } else if (qType < 4) { Term t1 = new Term(field, vals[rnd.Next(vals.Length)]); Term t2 = new Term(field, vals[rnd.Next(vals.Length)]); PhraseQuery pq = new PhraseQuery(); pq.Add(t1); pq.Add(t2); pq.Slop = 10; // increase possibility of matching q = pq; } else if (qType < 7) { q = new WildcardQuery(new Term(field, "w*")); } else { q = RandBoolQuery(rnd, allowMust, level - 1, field, vals, cb); } int r = rnd.Next(10); Occur occur; if (r < 2) { occur = Occur.MUST_NOT; } else if (r < 5) { if (allowMust) { occur = Occur.MUST; } else { occur = Occur.SHOULD; } } else { occur = Occur.SHOULD; } current.Add(q, occur); } if (cb != null) { cb.PostCreate(current); } return current; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Foundatio.Utility; using Microsoft.Extensions.Logging; namespace Foundatio.Lock { public interface ILockProvider { Task<ILock> AcquireAsync(string resource, TimeSpan? timeUntilExpires = null, bool releaseOnDispose = true, CancellationToken cancellationToken = default); Task<bool> IsLockedAsync(string resource); Task ReleaseAsync(string resource, string lockId); Task RenewAsync(string resource, string lockId, TimeSpan? timeUntilExpires = null); } public interface ILock : IAsyncDisposable { Task RenewAsync(TimeSpan? timeUntilExpires = null); Task ReleaseAsync(); string LockId { get; } string Resource { get; } DateTime AcquiredTimeUtc { get; } TimeSpan TimeWaitedForLock { get; } int RenewalCount { get; } } public static class LockProviderExtensions { public static Task ReleaseAsync(this ILockProvider provider, ILock @lock) { return provider.ReleaseAsync(@lock.Resource, @lock.LockId); } public static Task RenewAsync(this ILockProvider provider, ILock @lock, TimeSpan? timeUntilExpires = null) { return provider.RenewAsync(@lock.Resource, @lock.LockId, timeUntilExpires); } public static Task<ILock> AcquireAsync(this ILockProvider provider, string resource, TimeSpan? timeUntilExpires = null, CancellationToken cancellationToken = default) { return provider.AcquireAsync(resource, timeUntilExpires, true, cancellationToken); } public static async Task<ILock> AcquireAsync(this ILockProvider provider, string resource, TimeSpan? timeUntilExpires = null, TimeSpan? acquireTimeout = null) { using var cancellationTokenSource = acquireTimeout.ToCancellationTokenSource(TimeSpan.FromSeconds(30)); return await provider.AcquireAsync(resource, timeUntilExpires, true, cancellationTokenSource.Token).AnyContext(); } public static async Task<bool> TryUsingAsync(this ILockProvider locker, string resource, Func<CancellationToken, Task> work, TimeSpan? timeUntilExpires = null, CancellationToken cancellationToken = default) { var l = await locker.AcquireAsync(resource, timeUntilExpires, true, cancellationToken).AnyContext(); if (l == null) return false; try { await work(cancellationToken).AnyContext(); } finally { await l.ReleaseAsync().AnyContext(); } return true; } public static async Task<bool> TryUsingAsync(this ILockProvider locker, string resource, Func<Task> work, TimeSpan? timeUntilExpires = null, CancellationToken cancellationToken = default) { var l = await locker.AcquireAsync(resource, timeUntilExpires, true, cancellationToken).AnyContext(); if (l == null) return false; try { await work().AnyContext(); } finally { await l.ReleaseAsync().AnyContext(); } return true; } public static async Task<bool> TryUsingAsync(this ILockProvider locker, string resource, Func<CancellationToken, Task> work, TimeSpan? timeUntilExpires = null, TimeSpan? acquireTimeout = null) { using (var cancellationTokenSource = acquireTimeout.ToCancellationTokenSource()) { var l = await locker.AcquireAsync(resource, timeUntilExpires, true, cancellationTokenSource.Token).AnyContext(); if (l == null) return false; try { await work(cancellationTokenSource.Token).AnyContext(); } finally { await l.ReleaseAsync().AnyContext(); } } return true; } public static async Task<bool> TryUsingAsync(this ILockProvider locker, string resource, Func<Task> work, TimeSpan? timeUntilExpires = null, TimeSpan? acquireTimeout = null) { using (var cancellationTokenSource = acquireTimeout.ToCancellationTokenSource()) { var l = await locker.AcquireAsync(resource, timeUntilExpires, true, cancellationTokenSource.Token).AnyContext(); if (l == null) return false; try { await work().AnyContext(); } finally { await l.ReleaseAsync().AnyContext(); } } return true; } public static Task<bool> TryUsingAsync(this ILockProvider locker, string resource, Action work, TimeSpan? timeUntilExpires = null, TimeSpan? acquireTimeout = null) { return locker.TryUsingAsync(resource, () => { work(); return Task.CompletedTask; }, timeUntilExpires, acquireTimeout); } public static async Task<ILock> AcquireAsync(this ILockProvider provider, IEnumerable<string> resources, TimeSpan? timeUntilExpires = null, bool releaseOnDispose = true, CancellationToken cancellationToken = default) { if (resources == null) throw new ArgumentNullException(nameof(resources)); var resourceList = resources.Distinct().ToArray(); if (resourceList.Length == 0) return new EmptyLock(); var logger = provider.GetLogger(); if (logger.IsEnabled(LogLevel.Trace)) logger.LogTrace("Acquiring {LockCount} locks {Resource}", resourceList.Length, resourceList); var sw = Stopwatch.StartNew(); var locks = await Task.WhenAll(resourceList.Select(r => provider.AcquireAsync(r, timeUntilExpires, releaseOnDispose, cancellationToken))); sw.Stop(); // if any lock is null, release any acquired and return null (all or nothing) var acquiredLocks = locks.Where(l => l != null).ToArray(); var unacquiredResources = resourceList.Except(locks.Select(l => l?.Resource)).ToArray(); if (unacquiredResources.Length > 0) { if (logger.IsEnabled(LogLevel.Trace)) logger.LogTrace("Unable to acquire all {LockCount} locks {Resource} releasing acquired locks", unacquiredResources.Length, unacquiredResources); await Task.WhenAll(acquiredLocks.Select(l => l.ReleaseAsync())).AnyContext(); return null; } if (logger.IsEnabled(LogLevel.Trace)) logger.LogTrace("Acquired {LockCount} locks {Resource} after {Duration:g}", resourceList.Length, resourceList, sw.Elapsed); return new DisposableLockCollection(locks, String.Join("+", locks.Select(l => l.LockId)), sw.Elapsed, logger); } public static async Task<ILock> AcquireAsync(this ILockProvider provider, IEnumerable<string> resources, TimeSpan? timeUntilExpires, TimeSpan? acquireTimeout) { using var cancellationTokenSource = acquireTimeout.ToCancellationTokenSource(TimeSpan.FromSeconds(30)); return await provider.AcquireAsync(resources, timeUntilExpires, true, cancellationTokenSource.Token).AnyContext(); } public static async Task<ILock> AcquireAsync(this ILockProvider provider, IEnumerable<string> resources, TimeSpan? timeUntilExpires, TimeSpan? acquireTimeout, bool releaseOnDispose) { using var cancellationTokenSource = acquireTimeout.ToCancellationTokenSource(TimeSpan.FromSeconds(30)); return await provider.AcquireAsync(resources, timeUntilExpires, releaseOnDispose, cancellationTokenSource.Token).AnyContext(); } public static async Task<bool> TryUsingAsync(this ILockProvider locker, IEnumerable<string> resources, Func<CancellationToken, Task> work, TimeSpan? timeUntilExpires = null, CancellationToken cancellationToken = default) { var l = await locker.AcquireAsync(resources, timeUntilExpires, true, cancellationToken).AnyContext(); if (l == null) return false; try { await work(cancellationToken).AnyContext(); } finally { await l.ReleaseAsync().AnyContext(); } return true; } public static async Task<bool> TryUsingAsync(this ILockProvider locker, IEnumerable<string> resources, Func<Task> work, TimeSpan? timeUntilExpires = null, CancellationToken cancellationToken = default) { var l = await locker.AcquireAsync(resources, timeUntilExpires, true, cancellationToken).AnyContext(); if (l == null) return false; try { await work().AnyContext(); } finally { await l.ReleaseAsync().AnyContext(); } return true; } public static async Task<bool> TryUsingAsync(this ILockProvider locker, IEnumerable<string> resources, Func<CancellationToken, Task> work, TimeSpan? timeUntilExpires, TimeSpan? acquireTimeout) { using (var cancellationTokenSource = acquireTimeout.ToCancellationTokenSource()) { var l = await locker.AcquireAsync(resources, timeUntilExpires, true, cancellationTokenSource.Token).AnyContext(); if (l == null) return false; try { await work(cancellationTokenSource.Token).AnyContext(); } finally { await l.ReleaseAsync().AnyContext(); } } return true; } public static async Task<bool> TryUsingAsync(this ILockProvider locker, IEnumerable<string> resources, Func<Task> work, TimeSpan? timeUntilExpires, TimeSpan? acquireTimeout) { using (var cancellationTokenSource = acquireTimeout.ToCancellationTokenSource()) { var l = await locker.AcquireAsync(resources, timeUntilExpires, true, cancellationTokenSource.Token).AnyContext(); if (l == null) return false; try { await work().AnyContext(); } finally { await l.ReleaseAsync().AnyContext(); } } return true; } public static Task<bool> TryUsingAsync(this ILockProvider locker, IEnumerable<string> resources, Action work, TimeSpan? timeUntilExpires, TimeSpan? acquireTimeout) { return locker.TryUsingAsync(resources, () => { work(); return Task.CompletedTask; }, timeUntilExpires, acquireTimeout); } } }
// 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.Threading; namespace System.Data.SqlClient.SNI { /// <summary> /// MARS handle /// </summary> internal class SNIMarsHandle : SNIHandle { private const uint ACK_THRESHOLD = 2; private readonly SNIMarsConnection _connection; private readonly uint _status = TdsEnums.SNI_UNINITIALIZED; private readonly Queue<SNIPacket> _receivedPacketQueue = new Queue<SNIPacket>(); private readonly Queue<SNIMarsQueuedPacket> _sendPacketQueue = new Queue<SNIMarsQueuedPacket>(); private readonly object _callbackObject; private readonly Guid _connectionId = Guid.NewGuid(); private readonly ushort _sessionId; private readonly ManualResetEventSlim _packetEvent = new ManualResetEventSlim(false); private readonly ManualResetEventSlim _ackEvent = new ManualResetEventSlim(false); private readonly SNISMUXHeader _currentHeader = new SNISMUXHeader(); private uint _sendHighwater = 4; private int _asyncReceives = 0; private uint _receiveHighwater = 4; private uint _receiveHighwaterLastAck = 4; private uint _sequenceNumber; private SNIError _connectionError; /// <summary> /// Connection ID /// </summary> public override Guid ConnectionId { get { return _connectionId; } } /// <summary> /// Handle status /// </summary> public override uint Status { get { return _status; } } /// <summary> /// Dispose object /// </summary> public override void Dispose() { try { SendControlPacket(SNISMUXFlags.SMUX_FIN); } catch (Exception e) { SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, SNICommon.InternalExceptionError, e); throw; } } /// <summary> /// Constructor /// </summary> /// <param name="connection">MARS connection</param> /// <param name="sessionId">MARS session ID</param> /// <param name="callbackObject">Callback object</param> /// <param name="async">true if connection is asynchronous</param> public SNIMarsHandle(SNIMarsConnection connection, ushort sessionId, object callbackObject, bool async) { _sessionId = sessionId; _connection = connection; _callbackObject = callbackObject; SendControlPacket(SNISMUXFlags.SMUX_SYN); _status = TdsEnums.SNI_SUCCESS; } /// <summary> /// Send control packet /// </summary> /// <param name="flags">SMUX header flags</param> private void SendControlPacket(SNISMUXFlags flags) { byte[] headerBytes = null; lock (this) { GetSMUXHeaderBytes(0, (byte)flags, ref headerBytes); } SNIPacket packet = new SNIPacket(); packet.SetData(headerBytes, SNISMUXHeader.HEADER_LENGTH); _connection.Send(packet); } /// <summary> /// Generate SMUX header /// </summary> /// <param name="length">Packet length</param> /// <param name="flags">Packet flags</param> /// <param name="headerBytes">Header in bytes</param> private void GetSMUXHeaderBytes(int length, byte flags, ref byte[] headerBytes) { headerBytes = new byte[SNISMUXHeader.HEADER_LENGTH]; _currentHeader.SMID = 83; _currentHeader.flags = flags; _currentHeader.sessionId = _sessionId; _currentHeader.length = (uint)SNISMUXHeader.HEADER_LENGTH + (uint)length; _currentHeader.sequenceNumber = ((flags == (byte)SNISMUXFlags.SMUX_FIN) || (flags == (byte)SNISMUXFlags.SMUX_ACK)) ? _sequenceNumber - 1 : _sequenceNumber++; _currentHeader.highwater = _receiveHighwater; _receiveHighwaterLastAck = _currentHeader.highwater; BitConverter.GetBytes(_currentHeader.SMID).CopyTo(headerBytes, 0); BitConverter.GetBytes(_currentHeader.flags).CopyTo(headerBytes, 1); BitConverter.GetBytes(_currentHeader.sessionId).CopyTo(headerBytes, 2); BitConverter.GetBytes(_currentHeader.length).CopyTo(headerBytes, 4); BitConverter.GetBytes(_currentHeader.sequenceNumber).CopyTo(headerBytes, 8); BitConverter.GetBytes(_currentHeader.highwater).CopyTo(headerBytes, 12); } /// <summary> /// Generate a packet with SMUX header /// </summary> /// <param name="packet">SNI packet</param> /// <returns>Encapsulated SNI packet</returns> private SNIPacket GetSMUXEncapsulatedPacket(SNIPacket packet) { uint xSequenceNumber = _sequenceNumber; byte[] headerBytes = null; GetSMUXHeaderBytes(packet.Length, (byte)SNISMUXFlags.SMUX_DATA, ref headerBytes); SNIPacket smuxPacket = new SNIPacket(16 + packet.Length); smuxPacket.Description = string.Format("({0}) SMUX packet {1}", packet.Description == null ? "" : packet.Description, xSequenceNumber); smuxPacket.AppendData(headerBytes, 16); smuxPacket.AppendPacket(packet); return smuxPacket; } /// Send a packet synchronously /// </summary> /// <param name="packet">SNI packet</param> /// <returns>SNI error code</returns> public override uint Send(SNIPacket packet) { while (true) { lock (this) { if (_sequenceNumber < _sendHighwater) { break; } } _ackEvent.Wait(); lock (this) { _ackEvent.Reset(); } } return _connection.Send(GetSMUXEncapsulatedPacket(packet)); } /// <summary> /// Send packet asynchronously /// </summary> /// <param name="packet">SNI packet</param> /// <param name="callback">Completion callback</param> /// <returns>SNI error code</returns> private uint InternalSendAsync(SNIPacket packet, SNIAsyncCallback callback) { SNIPacket encapsulatedPacket = null; lock (this) { if (_sequenceNumber >= _sendHighwater) { return TdsEnums.SNI_QUEUE_FULL; } encapsulatedPacket = GetSMUXEncapsulatedPacket(packet); if (callback != null) { encapsulatedPacket.SetCompletionCallback(callback); } else { encapsulatedPacket.SetCompletionCallback(HandleSendComplete); } return _connection.SendAsync(encapsulatedPacket, callback); } } /// <summary> /// Send pending packets /// </summary> /// <returns>SNI error code</returns> private uint SendPendingPackets() { SNIMarsQueuedPacket packet = null; while (true) { lock (this) { if (_sequenceNumber < _sendHighwater) { if (_sendPacketQueue.Count != 0) { packet = _sendPacketQueue.Peek(); uint result = InternalSendAsync(packet.Packet, packet.Callback); if (result != TdsEnums.SNI_SUCCESS && result != TdsEnums.SNI_SUCCESS_IO_PENDING) { return result; } _sendPacketQueue.Dequeue(); continue; } else { _ackEvent.Set(); } } break; } } return TdsEnums.SNI_SUCCESS; } /// <summary> /// Send a packet asynchronously /// </summary> /// <param name="packet">SNI packet</param> /// <param name="callback">Completion callback</param> /// <returns>SNI error code</returns> public override uint SendAsync(SNIPacket packet, bool disposePacketAfterSendAsync, SNIAsyncCallback callback = null) { lock (this) { _sendPacketQueue.Enqueue(new SNIMarsQueuedPacket(packet, callback != null ? callback : HandleSendComplete)); } SendPendingPackets(); return TdsEnums.SNI_SUCCESS_IO_PENDING; } /// <summary> /// Receive a packet asynchronously /// </summary> /// <param name="packet">SNI packet</param> /// <returns>SNI error code</returns> public override uint ReceiveAsync(ref SNIPacket packet) { lock (_receivedPacketQueue) { int queueCount = _receivedPacketQueue.Count; if (_connectionError != null) { return SNICommon.ReportSNIError(_connectionError); } if (queueCount == 0) { _asyncReceives++; return TdsEnums.SNI_SUCCESS_IO_PENDING; } packet = _receivedPacketQueue.Dequeue(); if (queueCount == 1) { _packetEvent.Reset(); } } lock (this) { _receiveHighwater++; } SendAckIfNecessary(); return TdsEnums.SNI_SUCCESS; } /// <summary> /// Handle receive error /// </summary> public void HandleReceiveError(SNIPacket packet) { lock (_receivedPacketQueue) { _connectionError = SNILoadHandle.SingletonInstance.LastError; _packetEvent.Set(); } ((TdsParserStateObject)_callbackObject).ReadAsyncCallback(packet, 1); } /// <summary> /// Handle send completion /// </summary> /// <param name="packet">SNI packet</param> /// <param name="sniErrorCode">SNI error code</param> public void HandleSendComplete(SNIPacket packet, uint sniErrorCode) { lock (this) { Debug.Assert(_callbackObject != null); ((TdsParserStateObject)_callbackObject).WriteAsyncCallback(packet, sniErrorCode); } } /// <summary> /// Handle SMUX acknowledgement /// </summary> /// <param name="highwater">Send highwater mark</param> public void HandleAck(uint highwater) { lock (this) { if (_sendHighwater != highwater) { _sendHighwater = highwater; SendPendingPackets(); } } } /// <summary> /// Handle receive completion /// </summary> /// <param name="packet">SNI packet</param> /// <param name="header">SMUX header</param> public void HandleReceiveComplete(SNIPacket packet, SNISMUXHeader header) { lock (this) { if (_sendHighwater != header.highwater) { HandleAck(header.highwater); } lock (_receivedPacketQueue) { if (_asyncReceives == 0) { _receivedPacketQueue.Enqueue(packet); _packetEvent.Set(); return; } _asyncReceives--; Debug.Assert(_callbackObject != null); ((TdsParserStateObject)_callbackObject).ReadAsyncCallback(packet, 0); } } lock (this) { _receiveHighwater++; } SendAckIfNecessary(); } /// <summary> /// Send ACK if we've hit highwater threshold /// </summary> private void SendAckIfNecessary() { uint receiveHighwater; uint receiveHighwaterLastAck; lock (this) { receiveHighwater = _receiveHighwater; receiveHighwaterLastAck = _receiveHighwaterLastAck; } if (receiveHighwater - receiveHighwaterLastAck > ACK_THRESHOLD) { SendControlPacket(SNISMUXFlags.SMUX_ACK); } } /// <summary> /// Receive a packet synchronously /// </summary> /// <param name="packet">SNI packet</param> /// <param name="timeoutInMilliseconds">Timeout in Milliseconds</param> /// <returns>SNI error code</returns> public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) { packet = null; int queueCount; uint result = TdsEnums.SNI_SUCCESS_IO_PENDING; while (true) { lock (_receivedPacketQueue) { if (_connectionError != null) { return SNICommon.ReportSNIError(_connectionError); } queueCount = _receivedPacketQueue.Count; if (queueCount > 0) { packet = _receivedPacketQueue.Dequeue(); if (queueCount == 1) { _packetEvent.Reset(); } result = TdsEnums.SNI_SUCCESS; } } if (result == TdsEnums.SNI_SUCCESS) { lock (this) { _receiveHighwater++; } SendAckIfNecessary(); return result; } if (!_packetEvent.Wait(timeoutInMilliseconds)) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.SMUX_PROV, 0, SNICommon.ConnTimeoutError, string.Empty); return TdsEnums.SNI_WAIT_TIMEOUT; } } } /// <summary> /// Check SNI handle connection /// </summary> /// <param name="handle"></param> /// <returns>SNI error status</returns> public override uint CheckConnection() { return _connection.CheckConnection(); } /// <summary> /// Set async callbacks /// </summary> /// <param name="receiveCallback">Receive callback</param> /// <param name="sendCallback">Send callback</param> public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback) { } /// <summary> /// Set buffer size /// </summary> /// <param name="bufferSize">Buffer size</param> public override void SetBufferSize(int bufferSize) { } /// <summary> /// Enable SSL /// </summary> public override uint EnableSsl(uint options) { return _connection.EnableSsl(options); } /// <summary> /// Disable SSL /// </summary> public override void DisableSsl() { _connection.DisableSsl(); } #if DEBUG /// <summary> /// Test handle for killing underlying connection /// </summary> public override void KillConnection() { _connection.KillConnection(); } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct01.strct01 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(dynamic x = null, dynamic y = default(dynamic)) { if (x == null && y == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct01a.strct01a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(int? x = 2, int? y = 1) { if (x == 2 && y == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); dynamic d = 1; return p.Foo(y: d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct03.strct03 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(dynamic x, dynamic y = null) { if (x == 2 && y == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(2); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct03a.strct03a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(int? x, int? y = 1) { if (x == 2 && y == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); dynamic d = 2; return p.Foo(d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct05.strct05 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. multiple optional parameters</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(dynamic z, dynamic x = null, dynamic y = null) { if (z == 1 && x == null && y == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(1); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct05a.strct05a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. multiple optional parameters</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(int? z, int? x = 2, int? y = 1) { if (z == 1 && x == 2 && y == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); dynamic d = 1; return p.Foo(d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct06a.strct06a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. Expressions used</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(int? z = 1 + 1) { if (z == 2) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct07a.strct07a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. Max int</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(int? z = 2147483647) { if (z == 2147483647) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct09a.strct09a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(long? z = (long)1) { if (z == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct12.strct12 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description> // <Expects status=success></Expects> // <Code> using System.Runtime.InteropServices; public struct Parent { public int Foo( [Optional] dynamic i) { if (i == System.Type.Missing) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct12a.strct12a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description> // <Expects status=success></Expects> // <Code> using System.Runtime.InteropServices; public struct Parent { public int Foo( [Optional] int ? i) { if (i == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct13.strct13 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description> // <Expects status=success></Expects> // <Code> using System.Runtime.InteropServices; public struct Parent { public int Foo( [Optional] dynamic i, [Optional] long j, [Optional] float f, [Optional] dynamic d) { if (d == System.Type.Missing) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct13a.strct13a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description> // <Expects status=success></Expects> // <Code> using System.Runtime.InteropServices; public struct Parent { public int Foo( [Optional] int ? i, [Optional] long ? j, [Optional] float ? f, [Optional] decimal ? d) { if (d == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct14a.strct14a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public struct Parent { private const int x = 1; public int Foo(long? z = x) { if (z == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct18a.strct18a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public struct Parent { private const string x = "test"; public int Foo(string z = x) { if (z == "test") return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct19a.strct19a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public struct Parent { private const bool x = true; public int Foo(bool? z = x) { if ((bool)z) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct20a.strct20a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(string z = "test", int? y = 3) { if (z == "test" && y == 3) return 1; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); try { p.Foo(3, "test"); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Parent.Foo(string, int?)"); if (ret) return 0; } return 1; } } //</Code> }
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ContainerInstance { 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> /// ContainerLogsOperations operations. /// </summary> internal partial class ContainerLogsOperations : IServiceOperations<ContainerInstanceManagementClient>, IContainerLogsOperations { /// <summary> /// Initializes a new instance of the ContainerLogsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ContainerLogsOperations(ContainerInstanceManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ContainerInstanceManagementClient /// </summary> public ContainerInstanceManagementClient Client { get; private set; } /// <summary> /// Get the logs for this container. /// </summary> /// <param name='resourceGroupName'> /// Azure resource group name /// </param> /// <param name='containerName'> /// Container name /// </param> /// <param name='containerGroupName'> /// Container group name /// </param> /// <param name='tail'> /// Only show this number of log lines. If not provided, all available logs are /// shown. /// </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<Logs>> ListWithHttpMessagesAsync(string resourceGroupName, string containerName, string containerGroupName, int? tail = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (containerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "containerName"); } if (containerGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "containerGroupName"); } // 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("containerName", containerName); tracingParameters.Add("containerGroupName", containerGroupName); tracingParameters.Add("tail", tail); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", 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.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/logs").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName)); _url = _url.Replace("{containerGroupName}", System.Uri.EscapeDataString(containerGroupName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (tail != null) { _queryParameters.Add(string.Format("tail={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(tail, Client.SerializationSettings).Trim('"')))); } 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<Logs>(); _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<Logs>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Storage { using Azure; using Management; using Rest; using 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> /// Operations operations. /// </summary> internal partial class Operations : IServiceOperations<StorageManagementClient>, IOperations { /// <summary> /// Initializes a new instance of the Operations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal Operations(StorageManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the StorageManagementClient /// </summary> public StorageManagementClient Client { get; private set; } /// <summary> /// Lists all of the available Storage Rest API operations. /// </summary> /// <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<IEnumerable<Operation>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Storage/operations").ToString(); 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 System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.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 (Newtonsoft.Json.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<IEnumerable<Operation>>(); _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<Page<Operation>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using mshtml; using OpenLiveWriter.Controls; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Extensibility.ImageEditing; using OpenLiveWriter.Localization; using OpenLiveWriter.PostEditor.PostHtmlEditing.ImageEditing.Decorators; namespace OpenLiveWriter.PostEditor.PostHtmlEditing { internal interface IImagePropertyEditingContext { IHTMLImgElement SelectedImage { get; } event ImagePropertyEventHandler ImagePropertyChanged; ImagePropertiesInfo ImagePropertiesInfo { get; set; } } /// <summary> /// Summary description for ImagePropertiesHandler. /// </summary> internal class ImageEditingPropertyHandler { ImageInsertHandler _imageInsertHandler; IImagePropertyEditingContext _propertyEditingContext; IBlogPostImageEditingContext _editorContext; internal ImageEditingPropertyHandler(IImagePropertyEditingContext propertyEditingContext, CreateFileCallback createFileCallback, IBlogPostImageEditingContext imageEditingContext) { _propertyEditingContext = propertyEditingContext; _imageInsertHandler = new ImageInsertHandler(); _editorContext = imageEditingContext; } public void RefreshView() { _propertyEditingContext.ImagePropertyChanged -= new ImagePropertyEventHandler(imageProperties_ImagePropertyChanged); IHTMLImgElement imgElement = ImgElement as IHTMLImgElement; if (imgElement != null) _propertyEditingContext.ImagePropertiesInfo = GetImagePropertiesInfo(imgElement, _editorContext); else _propertyEditingContext.ImagePropertiesInfo = null; _propertyEditingContext.ImagePropertyChanged += new ImagePropertyEventHandler(imageProperties_ImagePropertyChanged); } public static ImagePropertiesInfo GetImagePropertiesInfo(IHTMLImgElement imgElement, IBlogPostImageEditingContext editorContext) { IHTMLElement imgHtmlElement = (IHTMLElement)imgElement; string imgSrc = imgHtmlElement.getAttribute("src", 2) as string; BlogPostImageData imageData = null; try { imageData = BlogPostImageDataList.LookupImageDataByInlineUri(editorContext.ImageList, new Uri(imgSrc)); } catch (UriFormatException) { //this URI is probably relative web URL, so extract the image src letting the //DOM fill in the full URL for us based on the base URL. imgSrc = imgHtmlElement.getAttribute("src", 0) as string; } ImagePropertiesInfo info; if (imageData != null && imageData.GetImageSourceFile() != null) { //clone the image data to the sidebar doesn't change it (required for preserving image undo/redo state) imageData = (BlogPostImageData)imageData.Clone(); //this is an attached local image info = new BlogPostImagePropertiesInfo(imageData, new ImageDecoratorsList(editorContext.DecoratorsManager, imageData.ImageDecoratorSettings)); info.ImgElement = imgHtmlElement; } else { //this is not an attached local image, so treat as a web image ImageDecoratorsList remoteImageDecoratorsList = new ImageDecoratorsList(editorContext.DecoratorsManager, new BlogPostSettingsBag()); remoteImageDecoratorsList.AddDecorator(editorContext.DecoratorsManager.GetDefaultRemoteImageDecorators()); //The source image size is unknown, so calculate the actual image size by removing //the size attributes, checking the size, and then placing the size attributes back string oldHeight = imgHtmlElement.getAttribute("height", 2) as string; string oldWidth = imgHtmlElement.getAttribute("width", 2) as string; imgHtmlElement.removeAttribute("width", 0); imgHtmlElement.removeAttribute("height", 0); int width = imgElement.width; int height = imgElement.height; if (!String.IsNullOrEmpty(oldHeight)) imgHtmlElement.setAttribute("height", oldHeight, 0); if (!String.IsNullOrEmpty(oldWidth)) imgHtmlElement.setAttribute("width", oldWidth, 0); Uri infoUri; if (Uri.TryCreate(imgSrc, UriKind.Absolute, out infoUri)) { info = new ImagePropertiesInfo(infoUri, new Size(width, height), remoteImageDecoratorsList); } else { info = new ImagePropertiesInfo(new Uri("http://www.example.com"), new Size(width, height), remoteImageDecoratorsList); } info.ImgElement = imgHtmlElement; // Sets the correct inline image size and image size name for the remote image. if (!String.IsNullOrEmpty(oldWidth) && !String.IsNullOrEmpty(oldHeight)) { int inlineWidth, inlineHeight; if (Int32.TryParse(oldWidth, NumberStyles.Integer, CultureInfo.InvariantCulture, out inlineWidth) && Int32.TryParse(oldHeight, NumberStyles.Integer, CultureInfo.InvariantCulture, out inlineHeight)) { info.InlineImageSize = new Size(inlineWidth, inlineHeight); } } // Sets the correct border style for the remote image. if (new HtmlBorderDecoratorSettings(imgHtmlElement).InheritBorder) { if (!info.ImageDecorators.ContainsDecorator(HtmlBorderDecorator.Id)) info.ImageDecorators.AddDecorator(HtmlBorderDecorator.Id); } else if (new NoBorderDecoratorSettings(imgHtmlElement).NoBorder) { if (!info.ImageDecorators.ContainsDecorator(NoBorderDecorator.Id)) info.ImageDecorators.AddDecorator(NoBorderDecorator.Id); } } //transfer image data properties if (imageData != null) { info.UploadSettings = imageData.UploadInfo.Settings; info.UploadServiceId = imageData.UploadInfo.ImageServiceId; if (info.UploadServiceId == null) { info.UploadServiceId = editorContext.ImageServiceId; } } return info; } private IHTMLElement ImgElement { get { return _propertyEditingContext.SelectedImage as IHTMLElement; } } private void imageProperties_ImagePropertyChanged(object source, ImagePropertyEvent evt) { if (ImgElement != null) { switch (evt.PropertyType) { case ImagePropertyType.Source: case ImagePropertyType.InlineSize: case ImagePropertyType.Decorators: UpdateImageSource(evt.ImageProperties, evt.InvocationSource); break; default: Debug.Fail("Unsupported image property type update: " + evt.PropertyType); break; } } } private void UpdateImageSource(ImagePropertiesInfo imgProperties, ImageDecoratorInvocationSource invocationSource) { UpdateImageSource(imgProperties, ImgElement, _editorContext, _imageInsertHandler, invocationSource); } internal static void UpdateImageSource(ImagePropertiesInfo imgProperties, IHTMLElement imgElement, IBlogPostImageEditingContext editorContext, ImageInsertHandler imageInsertHandler, ImageDecoratorInvocationSource invocationSource) { ISupportingFile oldImageFile = null; try { oldImageFile = editorContext.SupportingFileService.GetFileByUri(new Uri((string)imgElement.getAttribute("src", 2))); } catch (UriFormatException) { } if (oldImageFile != null) //then this is a known supporting image file { using (new WaitCursor()) { BlogPostImageData imageData = BlogPostImageDataList.LookupImageDataByInlineUri(editorContext.ImageList, oldImageFile.FileUri); if (imageData != null) { //Create a new ImageData object based on the image data attached to the current image src file. BlogPostImageData newImageData = (BlogPostImageData)imageData.Clone(); //initialize some handlers for creating files based on the image's existing ISupportingFile objects //This is necessary so that the new image files are recognized as being updates to an existing image //which allows the updates to be re-uploaded back to the same location. CreateImageFileHandler inlineFileCreator = new CreateImageFileHandler(editorContext.SupportingFileService, newImageData.InlineImageFile != null ? newImageData.InlineImageFile.SupportingFile : null); CreateImageFileHandler linkedFileCreator = new CreateImageFileHandler(editorContext.SupportingFileService, newImageData.LinkedImageFile != null ? newImageData.LinkedImageFile.SupportingFile : null); //re-write the image files on disk using the latest settings imageInsertHandler.WriteImages(imgProperties, true, invocationSource, new CreateFileCallback(inlineFileCreator.CreateFileCallback), new CreateFileCallback(linkedFileCreator.CreateFileCallback), editorContext.EditorOptions); //update the ImageData file references Size imageSizeWithBorder = imgProperties.InlineImageSizeWithBorder; //force a refresh of the image size values in the DOM by setting the new size attributes imgElement.setAttribute("width", imageSizeWithBorder.Width, 0); imgElement.setAttribute("height", imageSizeWithBorder.Height, 0); newImageData.InlineImageFile.SupportingFile = inlineFileCreator.ImageSupportingFile; newImageData.InlineImageFile.Height = imageSizeWithBorder.Height; newImageData.InlineImageFile.Width = imageSizeWithBorder.Width; if (imgProperties.LinkTarget == LinkTargetType.IMAGE) { newImageData.LinkedImageFile = new ImageFileData(linkedFileCreator.ImageSupportingFile, imgProperties.LinkTargetImageSize.Width, imgProperties.LinkTargetImageSize.Height, ImageFileRelationship.Linked); } else newImageData.LinkedImageFile = null; //assign the image decorators applied during WriteImages //Note: this is a clone so the sidebar doesn't affect the decorator values for the newImageData image src file newImageData.ImageDecoratorSettings = (BlogPostSettingsBag)imgProperties.ImageDecorators.SettingsBag.Clone(); //update the upload settings newImageData.UploadInfo.ImageServiceId = imgProperties.UploadServiceId; //save the new image data in the image list editorContext.ImageList.AddImage(newImageData); } else Debug.Fail("imageData could not be located"); } } if (imgProperties.LinkTarget == LinkTargetType.NONE) { imgProperties.RemoveLinkTarget(); } } //Utility for an updating image file based on a particular ISupportingFile. private class CreateImageFileHandler { public ISupportingFile ImageSupportingFile; ISupportingFileService _fileService; public CreateImageFileHandler(ISupportingFileService fileService, ISupportingFile supportingFile) { _fileService = fileService; ImageSupportingFile = supportingFile; } public string CreateFileCallback(string requestedFileName) { if (ImageSupportingFile == null) ImageSupportingFile = _fileService.CreateSupportingFile(requestedFileName, new MemoryStream(new byte[0])); else ImageSupportingFile = ImageSupportingFile.UpdateFile(new MemoryStream(new byte[0]), requestedFileName); return ImageSupportingFile.FileUri.LocalPath; } } } public delegate void ImagePropertyEventHandler(object source, ImagePropertyEvent evt); public enum ImagePropertyType { Source, InlineSize, Decorators }; public class ImagePropertyEvent : EventArgs { public ImagePropertiesInfo ImageProperties { get { return _imageProperties; } } private readonly ImagePropertiesInfo _imageProperties; public readonly ImagePropertyType PropertyType; public readonly ImageDecoratorInvocationSource InvocationSource; public ImagePropertyEvent(ImagePropertyType propertyType, ImagePropertiesInfo imgProperties, ImageDecoratorInvocationSource invocationSource) { PropertyType = propertyType; _imageProperties = imgProperties; InvocationSource = invocationSource; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedAutoscalersClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<Autoscalers.AutoscalersClient> mockGrpcClient = new moq::Mock<Autoscalers.AutoscalersClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAutoscalerRequest request = new GetAutoscalerRequest { Zone = "zone255f4ea8", Project = "projectaa6ff846", Autoscaler = "autoscaleradfcda44", }; Autoscaler expectedResponse = new Autoscaler { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", Region = "regionedb20d96", Status = Autoscaler.Types.Status.Pending, Target = "targetaefbae42", AutoscalingPolicy = new AutoscalingPolicy(), RecommendedSize = 213286470, StatusDetails = { new AutoscalerStatusDetails(), }, Description = "description2cf9da67", SelfLink = "self_link7e87f12d", ScalingScheduleStatus = { { "key8a0b6e3c", new ScalingScheduleStatus() }, }, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AutoscalersClient client = new AutoscalersClientImpl(mockGrpcClient.Object, null); Autoscaler response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<Autoscalers.AutoscalersClient> mockGrpcClient = new moq::Mock<Autoscalers.AutoscalersClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAutoscalerRequest request = new GetAutoscalerRequest { Zone = "zone255f4ea8", Project = "projectaa6ff846", Autoscaler = "autoscaleradfcda44", }; Autoscaler expectedResponse = new Autoscaler { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", Region = "regionedb20d96", Status = Autoscaler.Types.Status.Pending, Target = "targetaefbae42", AutoscalingPolicy = new AutoscalingPolicy(), RecommendedSize = 213286470, StatusDetails = { new AutoscalerStatusDetails(), }, Description = "description2cf9da67", SelfLink = "self_link7e87f12d", ScalingScheduleStatus = { { "key8a0b6e3c", new ScalingScheduleStatus() }, }, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Autoscaler>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AutoscalersClient client = new AutoscalersClientImpl(mockGrpcClient.Object, null); Autoscaler responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Autoscaler responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<Autoscalers.AutoscalersClient> mockGrpcClient = new moq::Mock<Autoscalers.AutoscalersClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAutoscalerRequest request = new GetAutoscalerRequest { Zone = "zone255f4ea8", Project = "projectaa6ff846", Autoscaler = "autoscaleradfcda44", }; Autoscaler expectedResponse = new Autoscaler { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", Region = "regionedb20d96", Status = Autoscaler.Types.Status.Pending, Target = "targetaefbae42", AutoscalingPolicy = new AutoscalingPolicy(), RecommendedSize = 213286470, StatusDetails = { new AutoscalerStatusDetails(), }, Description = "description2cf9da67", SelfLink = "self_link7e87f12d", ScalingScheduleStatus = { { "key8a0b6e3c", new ScalingScheduleStatus() }, }, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AutoscalersClient client = new AutoscalersClientImpl(mockGrpcClient.Object, null); Autoscaler response = client.Get(request.Project, request.Zone, request.Autoscaler); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<Autoscalers.AutoscalersClient> mockGrpcClient = new moq::Mock<Autoscalers.AutoscalersClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAutoscalerRequest request = new GetAutoscalerRequest { Zone = "zone255f4ea8", Project = "projectaa6ff846", Autoscaler = "autoscaleradfcda44", }; Autoscaler expectedResponse = new Autoscaler { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", Region = "regionedb20d96", Status = Autoscaler.Types.Status.Pending, Target = "targetaefbae42", AutoscalingPolicy = new AutoscalingPolicy(), RecommendedSize = 213286470, StatusDetails = { new AutoscalerStatusDetails(), }, Description = "description2cf9da67", SelfLink = "self_link7e87f12d", ScalingScheduleStatus = { { "key8a0b6e3c", new ScalingScheduleStatus() }, }, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Autoscaler>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AutoscalersClient client = new AutoscalersClientImpl(mockGrpcClient.Object, null); Autoscaler responseCallSettings = await client.GetAsync(request.Project, request.Zone, request.Autoscaler, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Autoscaler responseCancellationToken = await client.GetAsync(request.Project, request.Zone, request.Autoscaler, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.Generic; /// <summary> /// System.Collections.ICollection.CopyTo(System.Array,System.Int32) /// </summary> public class DictionaryICollectionCopyTo2 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; // // TODO: Add your negative test cases here // // TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method ICollection.CopyTo(System.Array,System.Int32) ."); try { ICollection<KeyValuePair<String, String>> dictionary = new Dictionary<String, String>(); KeyValuePair<string, string> kvp1 = new KeyValuePair<String, String>("txt", "notepad.exe"); KeyValuePair<string, string> kvp2 = new KeyValuePair<String, String>("bmp", "paint.exe"); KeyValuePair<string, string> kvp3 = new KeyValuePair<String, String>("dib", "paint.exe"); KeyValuePair<string, string> kvp4 = new KeyValuePair<String, String>("rtf", "wordpad.exe"); dictionary.Add(kvp1); dictionary.Add(kvp2); dictionary.Add(kvp3); dictionary.Add(kvp4); KeyValuePair<string, string>[] kvpArray = new KeyValuePair<string, string>[dictionary.Count]; dictionary.CopyTo(kvpArray, 0); bool actual = (kvpArray[0].Equals(kvp1)) && (kvpArray[1].Equals(kvp2)) && (kvpArray[2].Equals(kvp3)) && (kvpArray[3].Equals(kvp4)); bool expected = true; if (actual != expected) { TestLibrary.TestFramework.LogError("001.1", "Method ICollectionCopyTo Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException is not thrown when array is null ref."); try { ICollection<KeyValuePair<String, String>> dictionary = new Dictionary<String, String>(); KeyValuePair<string, string> kvp1 = new KeyValuePair<String, String>("txt", "notepad.exe"); KeyValuePair<string, string> kvp2 = new KeyValuePair<String, String>("bmp", "paint.exe"); KeyValuePair<string, string> kvp3 = new KeyValuePair<String, String>("dib", "paint.exe"); KeyValuePair<string, string> kvp4 = new KeyValuePair<String, String>("rtf", "wordpad.exe"); dictionary.Add(kvp1); dictionary.Add(kvp2); dictionary.Add(kvp3); dictionary.Add(kvp4); KeyValuePair<string, string>[] kvpArray = null; dictionary.CopyTo(kvpArray, 0); TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown."); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentOutOfRangeException is not thrown ."); try { ICollection<KeyValuePair<String, String>> dictionary = new Dictionary<String, String>(); KeyValuePair<string, string> kvp1 = new KeyValuePair<String, String>("txt", "notepad.exe"); KeyValuePair<string, string> kvp2 = new KeyValuePair<String, String>("bmp", "paint.exe"); KeyValuePair<string, string> kvp3 = new KeyValuePair<String, String>("dib", "paint.exe"); KeyValuePair<string, string> kvp4 = new KeyValuePair<String, String>("rtf", "wordpad.exe"); dictionary.Add(kvp1); dictionary.Add(kvp2); dictionary.Add(kvp3); dictionary.Add(kvp4); KeyValuePair<string, string>[] kvpArray = new KeyValuePair<string, string>[dictionary.Count]; dictionary.CopyTo(kvpArray, -1); TestLibrary.TestFramework.LogError("102.1", "ArgumentOutOfRangeException is not thrown."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentException is not thrown ."); try { ICollection<KeyValuePair<String, String>> dictionary = new Dictionary<String, String>(); KeyValuePair<string, string> kvp1 = new KeyValuePair<String, String>("txt", "notepad.exe"); KeyValuePair<string, string> kvp2 = new KeyValuePair<String, String>("bmp", "paint.exe"); KeyValuePair<string, string> kvp3 = new KeyValuePair<String, String>("dib", "paint.exe"); KeyValuePair<string, string> kvp4 = new KeyValuePair<String, String>("rtf", "wordpad.exe"); dictionary.Add(kvp1); dictionary.Add(kvp2); dictionary.Add(kvp3); dictionary.Add(kvp4); KeyValuePair<string, string>[] kvpArray = new KeyValuePair<string, string>[dictionary.Count]; dictionary.CopyTo(kvpArray, 4); TestLibrary.TestFramework.LogError("103.1", "ArgumentException is not thrown."); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("103.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: ArgumentException is not thrown ."); try { ICollection<KeyValuePair<String, String>> dictionary = new Dictionary<String, String>(); KeyValuePair<string, string> kvp1 = new KeyValuePair<String, String>("txt", "notepad.exe"); KeyValuePair<string, string> kvp2 = new KeyValuePair<String, String>("bmp", "paint.exe"); KeyValuePair<string, string> kvp3 = new KeyValuePair<String, String>("dib", "paint.exe"); KeyValuePair<string, string> kvp4 = new KeyValuePair<String, String>("rtf", "wordpad.exe"); dictionary.Add(kvp1); dictionary.Add(kvp2); dictionary.Add(kvp3); dictionary.Add(kvp4); KeyValuePair<string, string>[] kvpArray = new KeyValuePair<string, string>[dictionary.Count - 1]; dictionary.CopyTo(kvpArray, 0); TestLibrary.TestFramework.LogError("104.1", "ArgumentException is not thrown."); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { DictionaryICollectionCopyTo2 test = new DictionaryICollectionCopyTo2(); TestLibrary.TestFramework.BeginTestCase("DictionaryICollectionCopyTo2"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
// 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.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { /// <summary> /// An IVisualStudioDocument which represents the secondary buffer to the workspace API. /// </summary> internal sealed class ContainedDocument : ForegroundThreadAffinitizedObject, IVisualStudioHostDocument { private const string ReturnReplacementString = @"{|r|}"; private const string NewLineReplacementString = @"{|n|}"; private const string HTML = "HTML"; private const string Razor = "Razor"; private const char RazorExplicit = '@'; private const string CSharpRazorBlock = "{"; private const string VBRazorBlock = "code"; private const string HelperRazor = "helper"; private const string FunctionsRazor = "functions"; private static readonly EditOptions s_venusEditOptions = new EditOptions(new StringDifferenceOptions { DifferenceType = StringDifferenceTypes.Character, IgnoreTrimWhiteSpace = false }); private readonly AbstractContainedLanguage _containedLanguage; private readonly SourceCodeKind _sourceCodeKind; private readonly IComponentModel _componentModel; private readonly Workspace _workspace; private readonly ITextDifferencingSelectorService _differenceSelectorService; private readonly IOptionService _optionService; private readonly HostType _hostType; private readonly ReiteratedVersionSnapshotTracker _snapshotTracker; private readonly IFormattingRule _vbHelperFormattingRule; private readonly string _itemMoniker; public AbstractProject Project { get { return _containedLanguage.Project; } } public DocumentId Id { get; private set; } public IReadOnlyList<string> Folders { get; private set; } public TextLoader Loader { get; private set; } public DocumentKey Key { get; private set; } public bool SupportsRename { get { return _hostType == HostType.Razor; } } public ContainedDocument( AbstractContainedLanguage containedLanguage, SourceCodeKind sourceCodeKind, Workspace workspace, IVsHierarchy hierarchy, uint itemId, IComponentModel componentModel, IFormattingRule vbHelperFormattingRule) { Contract.ThrowIfNull(containedLanguage); _containedLanguage = containedLanguage; _sourceCodeKind = sourceCodeKind; _componentModel = componentModel; _workspace = workspace; _optionService = _workspace.Services.GetService<IOptionService>(); _hostType = GetHostType(); var rdt = (IVsRunningDocumentTable)componentModel.GetService<SVsServiceProvider>().GetService(typeof(SVsRunningDocumentTable)); var filePath = rdt.GetMonikerForHierarchyAndItemId(hierarchy, itemId); if (Project.Hierarchy != null) { string moniker; Project.Hierarchy.GetCanonicalName(itemId, out moniker); _itemMoniker = moniker; } this.Key = new DocumentKey(Project, filePath); this.Id = DocumentId.CreateNewId(Project.Id, filePath); this.Folders = containedLanguage.Project.GetFolderNames(itemId); this.Loader = TextLoader.From(containedLanguage.SubjectBuffer.AsTextContainer(), VersionStamp.Create(), filePath); _differenceSelectorService = componentModel.GetService<ITextDifferencingSelectorService>(); _snapshotTracker = new ReiteratedVersionSnapshotTracker(_containedLanguage.SubjectBuffer); _vbHelperFormattingRule = vbHelperFormattingRule; } private HostType GetHostType() { if (_containedLanguage.DataBuffer.SourceBuffers.Any(b => b.ContentType.IsOfType(HTML))) { return HostType.HTML; } if (_containedLanguage.DataBuffer.SourceBuffers.Any(b => b.ContentType.IsOfType(Razor))) { return HostType.Razor; } throw ExceptionUtilities.Unreachable; } public DocumentInfo GetInitialState() { return DocumentInfo.Create( this.Id, this.Name, folders: this.Folders, sourceCodeKind: _sourceCodeKind, loader: this.Loader, filePath: this.Key.Moniker); } public bool IsOpen { get { return true; } } #pragma warning disable 67 public event EventHandler UpdatedOnDisk; public event EventHandler<bool> Opened; public event EventHandler<bool> Closing; #pragma warning restore 67 IVisualStudioHostProject IVisualStudioHostDocument.Project { get { return this.Project; } } public ITextBuffer GetOpenTextBuffer() { return _containedLanguage.SubjectBuffer; } public SourceTextContainer GetOpenTextContainer() { return this.GetOpenTextBuffer().AsTextContainer(); } public IContentType ContentType { get { return _containedLanguage.SubjectBuffer.ContentType; } } public string Name { get { try { return Path.GetFileName(this.FilePath); } catch (ArgumentException) { return this.FilePath; } } } public SourceCodeKind SourceCodeKind { get { return _sourceCodeKind; } } public string FilePath { get { return Key.Moniker; } } public AbstractContainedLanguage ContainedLanguage { get { return _containedLanguage; } } public void Dispose() { _snapshotTracker.StopTracking(_containedLanguage.SubjectBuffer); this.ContainedLanguage.Dispose(); } public DocumentId FindProjectDocumentIdWithItemId(uint itemidInsertionPoint) { return Project.GetCurrentDocuments().SingleOrDefault(d => d.GetItemId() == itemidInsertionPoint).Id; } public uint FindItemIdOfDocument(Document document) { return Project.GetDocumentOrAdditionalDocument(document.Id).GetItemId(); } public void UpdateText(SourceText newText) { var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer(); var originalSnapshot = subjectBuffer.CurrentSnapshot; var originalText = originalSnapshot.AsText(); var changes = newText.GetTextChanges(originalText); IEnumerable<int> affectedVisibleSpanIndices = null; var editorVisibleSpansInOriginal = SharedPools.Default<List<TextSpan>>().AllocateAndClear(); try { var originalDocument = _workspace.CurrentSolution.GetDocument(this.Id); editorVisibleSpansInOriginal.AddRange(GetEditorVisibleSpans()); var newChanges = FilterTextChanges(originalText, editorVisibleSpansInOriginal, changes).ToList(); if (newChanges.Count == 0) { // no change to apply return; } ApplyChanges(subjectBuffer, newChanges, editorVisibleSpansInOriginal, out affectedVisibleSpanIndices); AdjustIndentation(subjectBuffer, affectedVisibleSpanIndices); } finally { SharedPools.Default<HashSet<int>>().ClearAndFree((HashSet<int>)affectedVisibleSpanIndices); SharedPools.Default<List<TextSpan>>().ClearAndFree(editorVisibleSpansInOriginal); } } private IEnumerable<TextChange> FilterTextChanges(SourceText originalText, List<TextSpan> editorVisibleSpansInOriginal, IReadOnlyList<TextChange> changes) { // no visible spans or changes if (editorVisibleSpansInOriginal.Count == 0 || changes.Count == 0) { // return empty one yield break; } using (var pooledObject = SharedPools.Default<List<TextChange>>().GetPooledObject()) { var changeQueue = pooledObject.Object; changeQueue.AddRange(changes); var spanIndex = 0; var changeIndex = 0; for (; spanIndex < editorVisibleSpansInOriginal.Count; spanIndex++) { var visibleSpan = editorVisibleSpansInOriginal[spanIndex]; var visibleTextSpan = GetVisibleTextSpan(originalText, visibleSpan, uptoFirstAndLastLine: true); for (; changeIndex < changeQueue.Count; changeIndex++) { var change = changeQueue[changeIndex]; // easy case first if (change.Span.End < visibleSpan.Start) { // move to next change continue; } if (visibleSpan.End < change.Span.Start) { // move to next visible span break; } // make sure we are not replacing whitespace around start and at the end of visible span if (WhitespaceOnEdges(originalText, visibleTextSpan, change)) { continue; } if (visibleSpan.Contains(change.Span)) { yield return change; continue; } // now it is complex case where things are intersecting each other var subChanges = GetSubTextChanges(originalText, change, visibleSpan).ToList(); if (subChanges.Count > 0) { if (subChanges.Count == 1 && subChanges[0] == change) { // we can't break it. not much we can do here. just don't touch and ignore this change continue; } changeQueue.InsertRange(changeIndex + 1, subChanges); continue; } } } } } private bool WhitespaceOnEdges(SourceText text, TextSpan visibleTextSpan, TextChange change) { if (!string.IsNullOrWhiteSpace(change.NewText)) { return false; } if (change.Span.End <= visibleTextSpan.Start) { return true; } if (visibleTextSpan.End <= change.Span.Start) { return true; } return false; } private IEnumerable<TextChange> GetSubTextChanges(SourceText originalText, TextChange changeInOriginalText, TextSpan visibleSpanInOriginalText) { using (var changes = SharedPools.Default<List<TextChange>>().GetPooledObject()) { var leftText = originalText.ToString(changeInOriginalText.Span); var rightText = changeInOriginalText.NewText; var offsetInOriginalText = changeInOriginalText.Span.Start; if (TryGetSubTextChanges(originalText, visibleSpanInOriginalText, leftText, rightText, offsetInOriginalText, changes.Object)) { return changes.Object.ToList(); } return GetSubTextChanges(originalText, visibleSpanInOriginalText, leftText, rightText, offsetInOriginalText); } } private bool TryGetSubTextChanges( SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText, List<TextChange> changes) { // these are expensive. but hopely, we don't hit this as much except the boundary cases. using (var leftPool = SharedPools.Default<List<TextSpan>>().GetPooledObject()) using (var rightPool = SharedPools.Default<List<TextSpan>>().GetPooledObject()) { var spansInLeftText = leftPool.Object; var spansInRightText = rightPool.Object; if (TryGetWhitespaceOnlyChanges(leftText, rightText, spansInLeftText, spansInRightText)) { for (var i = 0; i < spansInLeftText.Count; i++) { var spanInLeftText = spansInLeftText[i]; var spanInRightText = spansInRightText[i]; if (spanInLeftText.IsEmpty && spanInRightText.IsEmpty) { continue; } var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length); TextChange textChange; if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText, out textChange)) { changes.Add(textChange); } } return true; } return false; } } private IEnumerable<TextChange> GetSubTextChanges( SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText) { // these are expensive. but hopely, we don't hit this as much except the boundary cases. using (var leftPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject()) using (var rightPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject()) { var leftReplacementMap = leftPool.Object; var rightReplacementMap = rightPool.Object; string leftTextWithReplacement, rightTextWithReplacement; GetTextWithReplacements(leftText, rightText, leftReplacementMap, rightReplacementMap, out leftTextWithReplacement, out rightTextWithReplacement); var diffResult = DiffStrings(leftTextWithReplacement, rightTextWithReplacement); foreach (var difference in diffResult) { var spanInLeftText = AdjustSpan(diffResult.LeftDecomposition.GetSpanInOriginal(difference.Left), leftReplacementMap); var spanInRightText = AdjustSpan(diffResult.RightDecomposition.GetSpanInOriginal(difference.Right), rightReplacementMap); var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length); TextChange textChange; if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText.ToTextSpan(), out textChange)) { yield return textChange; } } } } private bool TryGetWhitespaceOnlyChanges(string leftText, string rightText, List<TextSpan> spansInLeftText, List<TextSpan> spansInRightText) { return TryGetWhitespaceGroup(leftText, spansInLeftText) && TryGetWhitespaceGroup(rightText, spansInRightText) && spansInLeftText.Count == spansInRightText.Count; } private bool TryGetWhitespaceGroup(string text, List<TextSpan> groups) { if (text.Length == 0) { groups.Add(new TextSpan(0, 0)); return true; } var start = 0; for (var i = 0; i < text.Length; i++) { var ch = text[i]; switch (ch) { case ' ': if (!TextAt(text, i - 1, ' ')) { start = i; } break; case '\r': case '\n': if (i == 0) { groups.Add(TextSpan.FromBounds(0, 0)); } else if (TextAt(text, i - 1, ' ')) { groups.Add(TextSpan.FromBounds(start, i)); } else if (TextAt(text, i - 1, '\n')) { groups.Add(TextSpan.FromBounds(start, i)); } start = i + 1; break; default: return false; } } if (start <= text.Length) { groups.Add(TextSpan.FromBounds(start, text.Length)); } return true; } private bool TextAt(string text, int index, char ch) { if (index < 0 || text.Length <= index) { return false; } return text[index] == ch; } private bool TryGetSubTextChange( SourceText originalText, TextSpan visibleSpanInOriginalText, string rightText, TextSpan spanInOriginalText, TextSpan spanInRightText, out TextChange textChange) { textChange = default(TextChange); var visibleFirstLineInOriginalText = originalText.Lines.GetLineFromPosition(visibleSpanInOriginalText.Start); var visibleLastLineInOriginalText = originalText.Lines.GetLineFromPosition(visibleSpanInOriginalText.End); // skip easy case // 1. things are out of visible span if (!visibleSpanInOriginalText.IntersectsWith(spanInOriginalText)) { return false; } // 2. there are no intersects var snippetInRightText = rightText.Substring(spanInRightText.Start, spanInRightText.Length); if (visibleSpanInOriginalText.Contains(spanInOriginalText) && visibleSpanInOriginalText.End != spanInOriginalText.End) { textChange = new TextChange(spanInOriginalText, snippetInRightText); return true; } // okay, more complex case. things are intersecting boundaries. var firstLineOfRightTextSnippet = snippetInRightText.GetFirstLineText(); var lastLineOfRightTextSnippet = snippetInRightText.GetLastLineText(); // there are 4 complex cases - these are all heuristic. not sure what better way I have. and the heristic is heavily based on // text differ's behavior. // 1. it is a single line if (visibleFirstLineInOriginalText.LineNumber == visibleLastLineInOriginalText.LineNumber) { // don't do anything return false; } // 2. replacement contains visible spans if (spanInOriginalText.Contains(visibleSpanInOriginalText)) { // header // don't do anything // body textChange = new TextChange( TextSpan.FromBounds(visibleFirstLineInOriginalText.EndIncludingLineBreak, visibleLastLineInOriginalText.Start), snippetInRightText.Substring(firstLineOfRightTextSnippet.Length, snippetInRightText.Length - firstLineOfRightTextSnippet.Length - lastLineOfRightTextSnippet.Length)); // footer // don't do anything return true; } // 3. replacement intersects with start if (spanInOriginalText.Start < visibleSpanInOriginalText.Start && visibleSpanInOriginalText.Start <= spanInOriginalText.End && spanInOriginalText.End < visibleSpanInOriginalText.End) { // header // don't do anything // body if (visibleFirstLineInOriginalText.EndIncludingLineBreak <= spanInOriginalText.End) { textChange = new TextChange( TextSpan.FromBounds(visibleFirstLineInOriginalText.EndIncludingLineBreak, spanInOriginalText.End), snippetInRightText.Substring(firstLineOfRightTextSnippet.Length)); return true; } return false; } // 4. replacement intersects with end if (visibleSpanInOriginalText.Start < spanInOriginalText.Start && spanInOriginalText.Start <= visibleSpanInOriginalText.End && visibleSpanInOriginalText.End <= spanInOriginalText.End) { // body if (spanInOriginalText.Start <= visibleLastLineInOriginalText.Start) { textChange = new TextChange( TextSpan.FromBounds(spanInOriginalText.Start, visibleLastLineInOriginalText.Start), snippetInRightText.Substring(0, snippetInRightText.Length - lastLineOfRightTextSnippet.Length)); return true; } // footer // don't do anything return false; } // if it got hit, then it means there is a missing case throw ExceptionUtilities.Unreachable; } private IHierarchicalDifferenceCollection DiffStrings(string leftTextWithReplacement, string rightTextWithReplacement) { var diffService = _differenceSelectorService.GetTextDifferencingService( _workspace.Services.GetLanguageServices(this.Project.Language).GetService<IContentTypeLanguageService>().GetDefaultContentType()); diffService = diffService ?? _differenceSelectorService.DefaultTextDifferencingService; return diffService.DiffStrings(leftTextWithReplacement, rightTextWithReplacement, s_venusEditOptions.DifferenceOptions); } private void GetTextWithReplacements( string leftText, string rightText, List<ValueTuple<int, int>> leftReplacementMap, List<ValueTuple<int, int>> rightReplacementMap, out string leftTextWithReplacement, out string rightTextWithReplacement) { // to make diff works better, we choose replacement strings that don't appear in both texts. var returnReplacement = GetReplacementStrings(leftText, rightText, ReturnReplacementString); var newLineReplacement = GetReplacementStrings(leftText, rightText, NewLineReplacementString); leftTextWithReplacement = GetTextWithReplacementMap(leftText, returnReplacement, newLineReplacement, leftReplacementMap); rightTextWithReplacement = GetTextWithReplacementMap(rightText, returnReplacement, newLineReplacement, rightReplacementMap); } private static string GetReplacementStrings(string leftText, string rightText, string initialReplacement) { if (leftText.IndexOf(initialReplacement, StringComparison.Ordinal) < 0 && rightText.IndexOf(initialReplacement, StringComparison.Ordinal) < 0) { return initialReplacement; } // okay, there is already one in the given text. const string format = "{{|{0}|{1}|{0}|}}"; for (var i = 0; true; i++) { var replacement = string.Format(format, i.ToString(), initialReplacement); if (leftText.IndexOf(replacement, StringComparison.Ordinal) < 0 && rightText.IndexOf(replacement, StringComparison.Ordinal) < 0) { return replacement; } } } private string GetTextWithReplacementMap(string text, string returnReplacement, string newLineReplacement, List<ValueTuple<int, int>> replacementMap) { var delta = 0; var returnLength = returnReplacement.Length; var newLineLength = newLineReplacement.Length; var sb = StringBuilderPool.Allocate(); for (var i = 0; i < text.Length; i++) { var ch = text[i]; if (ch == '\r') { sb.Append(returnReplacement); delta += returnLength - 1; replacementMap.Add(ValueTuple.Create(i + delta, delta)); continue; } else if (ch == '\n') { sb.Append(newLineReplacement); delta += newLineLength - 1; replacementMap.Add(ValueTuple.Create(i + delta, delta)); continue; } sb.Append(ch); } return StringBuilderPool.ReturnAndFree(sb); } private Span AdjustSpan(Span span, List<ValueTuple<int, int>> replacementMap) { var start = span.Start; var end = span.End; for (var i = 0; i < replacementMap.Count; i++) { var positionAndDelta = replacementMap[i]; if (positionAndDelta.Item1 <= span.Start) { start = span.Start - positionAndDelta.Item2; } if (positionAndDelta.Item1 <= span.End) { end = span.End - positionAndDelta.Item2; } if (positionAndDelta.Item1 > span.End) { break; } } return Span.FromBounds(start, end); } public IEnumerable<TextSpan> GetEditorVisibleSpans() { var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer(); return _containedLanguage.DataBuffer.CurrentSnapshot .GetSourceSpans() .Where(ss => ss.Snapshot.TextBuffer == subjectBuffer) .Select(s => s.Span.ToTextSpan()) .OrderBy(s => s.Start); } private static void ApplyChanges( IProjectionBuffer subjectBuffer, IEnumerable<TextChange> changes, IList<TextSpan> visibleSpansInOriginal, out IEnumerable<int> affectedVisibleSpansInNew) { using (var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null)) { var affectedSpans = SharedPools.Default<HashSet<int>>().AllocateAndClear(); affectedVisibleSpansInNew = affectedSpans; var currentVisibleSpanIndex = 0; foreach (var change in changes) { // Find the next visible span that either overlaps or intersects with while (currentVisibleSpanIndex < visibleSpansInOriginal.Count && visibleSpansInOriginal[currentVisibleSpanIndex].End < change.Span.Start) { currentVisibleSpanIndex++; } // no more place to apply text changes if (currentVisibleSpanIndex >= visibleSpansInOriginal.Count) { break; } var newText = change.NewText; var span = change.Span.ToSpan(); edit.Replace(span, newText); affectedSpans.Add(currentVisibleSpanIndex); } edit.Apply(); } } private void AdjustIndentation(IProjectionBuffer subjectBuffer, IEnumerable<int> visibleSpanIndex) { if (!visibleSpanIndex.Any()) { return; } var snapshot = subjectBuffer.CurrentSnapshot; var document = _workspace.CurrentSolution.GetDocument(this.Id); var originalText = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); Contract.Requires(object.ReferenceEquals(originalText, snapshot.AsText())); var root = document.GetSyntaxRootAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var editorOptionsFactory = _componentModel.GetService<IEditorOptionsFactoryService>(); var editorOptions = editorOptionsFactory.GetOptions(_containedLanguage.DataBuffer); var options = _workspace.Options .WithChangedOption(FormattingOptions.UseTabs, root.Language, !editorOptions.IsConvertTabsToSpacesEnabled()) .WithChangedOption(FormattingOptions.TabSize, root.Language, editorOptions.GetTabSize()) .WithChangedOption(FormattingOptions.IndentationSize, root.Language, editorOptions.GetIndentSize()); using (var pooledObject = SharedPools.Default<List<TextSpan>>().GetPooledObject()) { var spans = pooledObject.Object; spans.AddRange(this.GetEditorVisibleSpans()); using (var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null)) { foreach (var spanIndex in visibleSpanIndex) { var rule = GetBaseIndentationRule(root, originalText, spans, spanIndex); var visibleSpan = spans[spanIndex]; AdjustIndentationForSpan(document, edit, visibleSpan, rule, options); } edit.Apply(); } } } private void AdjustIndentationForSpan( Document document, ITextEdit edit, TextSpan visibleSpan, IFormattingRule baseIndentationRule, OptionSet options) { var root = document.GetSyntaxRootAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); using (var rulePool = SharedPools.Default<List<IFormattingRule>>().GetPooledObject()) using (var spanPool = SharedPools.Default<List<TextSpan>>().GetPooledObject()) { var venusFormattingRules = rulePool.Object; var visibleSpans = spanPool.Object; venusFormattingRules.Add(baseIndentationRule); venusFormattingRules.Add(ContainedDocumentPreserveFormattingRule.Instance); var formattingRules = venusFormattingRules.Concat(Formatter.GetDefaultFormattingRules(document)); var workspace = document.Project.Solution.Workspace; var changes = Formatter.GetFormattedTextChanges( root, new TextSpan[] { CommonFormattingHelpers.GetFormattingSpan(root, visibleSpan) }, workspace, options, formattingRules, CancellationToken.None); visibleSpans.Add(visibleSpan); var newChanges = FilterTextChanges(document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None), visibleSpans, changes.ToReadOnlyCollection()).Where(t => visibleSpan.Contains(t.Span)); foreach (var change in newChanges) { edit.Replace(change.Span.ToSpan(), change.NewText); } } } public BaseIndentationFormattingRule GetBaseIndentationRule(SyntaxNode root, SourceText text, List<TextSpan> spans, int spanIndex) { if (_hostType == HostType.Razor) { var currentSpanIndex = spanIndex; TextSpan visibleSpan; TextSpan visibleTextSpan; GetVisibleAndTextSpan(text, spans, currentSpanIndex, out visibleSpan, out visibleTextSpan); var end = visibleSpan.End; var current = root.FindToken(visibleTextSpan.Start).Parent; while (current != null) { if (current.Span.Start == visibleTextSpan.Start) { var blockType = GetRazorCodeBlockType(visibleSpan.Start); if (blockType == RazorCodeBlockType.Explicit) { var baseIndentation = GetBaseIndentation(root, text, visibleSpan); return new BaseIndentationFormattingRule(root, TextSpan.FromBounds(visibleSpan.Start, end), baseIndentation, _vbHelperFormattingRule); } } if (current.Span.Start < visibleSpan.Start) { var blockType = GetRazorCodeBlockType(visibleSpan.Start); if (blockType == RazorCodeBlockType.Block || blockType == RazorCodeBlockType.Helper) { var baseIndentation = GetBaseIndentation(root, text, visibleSpan); return new BaseIndentationFormattingRule(root, TextSpan.FromBounds(visibleSpan.Start, end), baseIndentation, _vbHelperFormattingRule); } if (currentSpanIndex == 0) { break; } GetVisibleAndTextSpan(text, spans, --currentSpanIndex, out visibleSpan, out visibleTextSpan); continue; } current = current.Parent; } } var span = spans[spanIndex]; var indentation = GetBaseIndentation(root, text, span); return new BaseIndentationFormattingRule(root, span, indentation, _vbHelperFormattingRule); } private void GetVisibleAndTextSpan(SourceText text, List<TextSpan> spans, int spanIndex, out TextSpan visibleSpan, out TextSpan visibleTextSpan) { visibleSpan = spans[spanIndex]; visibleTextSpan = GetVisibleTextSpan(text, visibleSpan); if (visibleTextSpan.IsEmpty) { // span has no text in them visibleTextSpan = visibleSpan; } } private int GetBaseIndentation(SyntaxNode root, SourceText text, TextSpan span) { // Is this right? We should probably get this from the IVsContainedLanguageHost instead. var editorOptionsFactory = _componentModel.GetService<IEditorOptionsFactoryService>(); var editorOptions = editorOptionsFactory.GetOptions(_containedLanguage.DataBuffer); var additionalIndentation = GetAdditionalIndentation(root, text, span); string baseIndentationString; int parent, indentSize, useTabs = 0, tabSize = 0; // Skip over the first line, since it's in "Venus space" anyway. var startingLine = text.Lines.GetLineFromPosition(span.Start); for (var line = startingLine; line.Start < span.End; line = text.Lines[line.LineNumber + 1]) { Marshal.ThrowExceptionForHR( this.ContainedLanguage.ContainedLanguageHost.GetLineIndent( line.LineNumber, out baseIndentationString, out parent, out indentSize, out useTabs, out tabSize)); if (!string.IsNullOrEmpty(baseIndentationString)) { return baseIndentationString.GetColumnFromLineOffset(baseIndentationString.Length, editorOptions.GetTabSize()) + additionalIndentation; } } return additionalIndentation; } private TextSpan GetVisibleTextSpan(SourceText text, TextSpan visibleSpan, bool uptoFirstAndLastLine = false) { var start = visibleSpan.Start; for (; start < visibleSpan.End; start++) { if (!char.IsWhiteSpace(text[start])) { break; } } var end = visibleSpan.End - 1; if (start <= end) { for (; start <= end; end--) { if (!char.IsWhiteSpace(text[end])) { break; } } } if (uptoFirstAndLastLine) { var firstLine = text.Lines.GetLineFromPosition(visibleSpan.Start); var lastLine = text.Lines.GetLineFromPosition(visibleSpan.End); if (firstLine.LineNumber < lastLine.LineNumber) { start = (start < firstLine.End) ? start : firstLine.End; end = (lastLine.Start < end + 1) ? end : lastLine.Start - 1; } } return (start <= end) ? TextSpan.FromBounds(start, end + 1) : default(TextSpan); } private int GetAdditionalIndentation(SyntaxNode root, SourceText text, TextSpan span) { if (_hostType == HostType.HTML) { return _optionService.GetOption(FormattingOptions.IndentationSize, this.Project.Language); } if (_hostType == HostType.Razor) { var type = GetRazorCodeBlockType(span.Start); // razor block if (type == RazorCodeBlockType.Block) { // more workaround for csharp razor case. when } for csharp razor code block is just typed, "}" exist // in both subject and surface buffer and there is no easy way to figure out who owns } just typed. // in this case, we let razor owns it. later razor will remove } from subject buffer if it is something // razor owns. if (this.Project.Language == LanguageNames.CSharp) { var textSpan = GetVisibleTextSpan(text, span); var end = textSpan.End - 1; if (end >= 0 && text[end] == '}') { var token = root.FindToken(end); var syntaxFact = _workspace.Services.GetLanguageServices(Project.Language).GetService<ISyntaxFactsService>(); if (token.Span.Start == end && syntaxFact != null) { SyntaxToken openBrace; if (syntaxFact.TryGetCorrespondingOpenBrace(token, out openBrace) && !textSpan.Contains(openBrace.Span)) { return 0; } } } } // same as C#, but different text is in the buffer if (this.Project.Language == LanguageNames.VisualBasic) { var textSpan = GetVisibleTextSpan(text, span); var subjectSnapshot = _containedLanguage.SubjectBuffer.CurrentSnapshot; var end = textSpan.End - 1; if (end >= 0) { var ch = subjectSnapshot[end]; if (CheckCode(subjectSnapshot, textSpan.End, ch, VBRazorBlock, checkAt: false) || CheckCode(subjectSnapshot, textSpan.End, ch, FunctionsRazor, checkAt: false)) { var token = root.FindToken(end, findInsideTrivia: true); var syntaxFact = _workspace.Services.GetLanguageServices(Project.Language).GetService<ISyntaxFactsService>(); if (token.Span.End == textSpan.End && syntaxFact != null) { if (syntaxFact.IsSkippedTokensTrivia(token.Parent)) { return 0; } } } } } return _optionService.GetOption(FormattingOptions.IndentationSize, this.Project.Language); } } return 0; } private RazorCodeBlockType GetRazorCodeBlockType(int position) { var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer(); var subjectSnapshot = subjectBuffer.CurrentSnapshot; var surfaceSnapshot = _containedLanguage.DataBuffer.CurrentSnapshot; var surfacePoint = surfaceSnapshot.MapFromSourceSnapshot(new SnapshotPoint(subjectSnapshot, position), PositionAffinity.Predecessor); if (!surfacePoint.HasValue) { // how this can happen? return RazorCodeBlockType.Implicit; } var ch = char.ToLower(surfaceSnapshot[Math.Max(surfacePoint.Value - 1, 0)]); // razor block if (IsCodeBlock(surfaceSnapshot, surfacePoint.Value, ch)) { return RazorCodeBlockType.Block; } if (ch == RazorExplicit) { return RazorCodeBlockType.Explicit; } if (CheckCode(surfaceSnapshot, surfacePoint.Value, HelperRazor)) { return RazorCodeBlockType.Helper; } return RazorCodeBlockType.Implicit; } private bool IsCodeBlock(ITextSnapshot surfaceSnapshot, int position, char ch) { if (this.Project.Language == LanguageNames.CSharp) { return CheckCode(surfaceSnapshot, position, ch, CSharpRazorBlock) || CheckCode(surfaceSnapshot, position, ch, FunctionsRazor, CSharpRazorBlock); } if (this.Project.Language == LanguageNames.VisualBasic) { return CheckCode(surfaceSnapshot, position, ch, VBRazorBlock) || CheckCode(surfaceSnapshot, position, ch, FunctionsRazor); } return false; } private bool CheckCode(ITextSnapshot snapshot, int position, char ch, string tag, bool checkAt = true) { if (ch != tag[tag.Length - 1] || position < tag.Length) { return false; } var start = position - tag.Length; var razorTag = snapshot.GetText(start, tag.Length); return string.Equals(razorTag, tag, StringComparison.OrdinalIgnoreCase) && (!checkAt || snapshot[start - 1] == RazorExplicit); } private bool CheckCode(ITextSnapshot snapshot, int position, string tag) { int i = position - 1; if (i < 0) { return false; } for (; i >= 0; i--) { if (!char.IsWhiteSpace(snapshot[i])) { break; } } var ch = snapshot[i]; position = i + 1; return CheckCode(snapshot, position, ch, tag); } private bool CheckCode(ITextSnapshot snapshot, int position, char ch, string tag1, string tag2) { if (!CheckCode(snapshot, position, ch, tag2, checkAt: false)) { return false; } return CheckCode(snapshot, position - tag2.Length, tag1); } public ITextUndoHistory GetTextUndoHistory() { // In Venus scenarios, the undo history is associated with the data buffer return _componentModel.GetService<ITextUndoHistoryRegistry>().GetHistory(_containedLanguage.DataBuffer); } public uint GetItemId() { AssertIsForeground(); if (_itemMoniker == null) { return (uint)VSConstants.VSITEMID.Nil; } uint itemId; Project.Hierarchy.ParseCanonicalName(_itemMoniker, out itemId); return itemId; } private enum RazorCodeBlockType { Block, Explicit, Implicit, Helper } private enum HostType { HTML, Razor } } }
using System.Collections; using System.Collections.Generic; using NUnit.Framework; using SIL.Text; namespace SIL.Tests.Text { [TestFixture] public class ApproximateMatcherTests { private IList<string> _forms; [SetUp] public void Setup() { _forms = new List<string>(); } private void AddEntry(string form) { _forms.Add(form); } [Test] public void Equal() { AddEntry("distance"); AddEntry("distances"); AddEntry("distane"); AddEntry("destance"); AddEntry("distence"); IList closest = (IList) ApproximateMatcher.FindClosestForms(_forms, "distance"); Assert.AreEqual(1, closest.Count); Assert.Contains("distance", closest); } [Test] public void Prefixes() { AddEntry("distance"); AddEntry("distances"); AddEntry("distane"); AddEntry("destance"); AddEntry("distence"); IList closest = (IList) ApproximateMatcher.FindClosestForms(_forms, "dist", ApproximateMatcherOptions. IncludePrefixedForms); Assert.AreEqual(4, closest.Count); Assert.Contains("distance", closest); Assert.Contains("distances", closest); Assert.Contains("distane", closest); Assert.Contains("distence", closest); } [Test] public void FindClosestAndNextClosestAndPrefixedForms() { AddEntry("bad"); //2 AddEntry("goad"); //1 AddEntry("godo"); //1 AddEntry("good"); //0 AddEntry("good-bye"); //0 IList closest = (IList) ApproximateMatcher.FindClosestForms(_forms, "good", ApproximateMatcherOptions. IncludePrefixedAndNextClosestForms); Assert.AreEqual(4, closest.Count); Assert.Contains("goad", closest); Assert.Contains("godo", closest); Assert.Contains("good", closest); Assert.Contains("good-bye", closest); } [Test] public void FindClosestAndNextClosestAndPrefixedForms_TwoBestOneSecondBest() { // This test is here because we found that we had made it so // that when the best edit distance and the second best // edit distance are one apart and the edit distance for an // entry that is the same as the best is found, // it clears the second best and makes the second best edit // distance the same as the best edit distance! Oooops! AddEntry("past"); //2 AddEntry("dest"); //1 AddEntry("dits"); //1 AddEntry("noise"); //3 IList closest = (IList) ApproximateMatcher.FindClosestForms(_forms, "dist", ApproximateMatcherOptions. IncludePrefixedAndNextClosestForms); Assert.AreEqual(3, closest.Count); Assert.Contains("past", closest); Assert.Contains("dest", closest); Assert.Contains("dits", closest); } [Test] public void Closest_EditDistance1() { AddEntry("a1234567890"); // insertion at beginning AddEntry("1a234567890"); // insertion in middle AddEntry("1234567890a"); // insertion at end AddEntry("234567890"); // deletion at beginning AddEntry("123457890"); // deletion in middle AddEntry("123456789"); // deletion at end AddEntry("a234567890"); //substitution at beginning AddEntry("1234a67890"); //substitution in middle AddEntry("123456789a"); //substitution at end AddEntry("2134567890"); //transposition at beginning AddEntry("1234657890"); //transposition in middle AddEntry("1234567809"); //transposition at end AddEntry("aa1234567890"); // noise AddEntry("1a23456789a0"); AddEntry("1a2a34567890"); AddEntry("1a23a4567890"); AddEntry("1a234a567890"); AddEntry("1a2345a67890"); AddEntry("ab34567890"); AddEntry("1234ab7890"); AddEntry("12345678ab"); AddEntry("2134567809"); AddEntry("1235467980"); IList closest = (IList) ApproximateMatcher.FindClosestForms(_forms, "1234567890"); Assert.AreEqual(12, closest.Count); Assert.Contains("a1234567890", closest); Assert.Contains("1a234567890", closest); Assert.Contains("1234567890a", closest); Assert.Contains("234567890", closest); Assert.Contains("123457890", closest); Assert.Contains("123456789", closest); Assert.Contains("a234567890", closest); Assert.Contains("1234a67890", closest); Assert.Contains("123456789a", closest); Assert.Contains("2134567890", closest); Assert.Contains("1234657890", closest); Assert.Contains("1234567809", closest); } [Test] public void ClosestAndNextClosest_EditDistance0and1() { AddEntry("a1234567890"); // insertion at beginning AddEntry("1a234567890"); // insertion in middle AddEntry("1234567890a"); // insertion at end AddEntry("234567890"); // deletion at beginning AddEntry("123457890"); // deletion in middle AddEntry("123456789"); // deletion at end AddEntry("a234567890"); //substitution at beginning AddEntry("1234a67890"); //substitution in middle AddEntry("123456789a"); //substitution at end AddEntry("2134567890"); //transposition at beginning AddEntry("1234657890"); //transposition in middle AddEntry("1234567809"); //transposition at end AddEntry("1234567890"); // identity AddEntry("aa1234567890"); // noise AddEntry("1a23456789a0"); AddEntry("1a2a34567890"); AddEntry("1a23a4567890"); AddEntry("1a234a567890"); AddEntry("1a2345a67890"); AddEntry("ab34567890"); AddEntry("1234ab7890"); AddEntry("12345678ab"); AddEntry("2134567809"); AddEntry("1235467980"); IList closest = (IList) ApproximateMatcher.FindClosestForms(_forms, "1234567890", ApproximateMatcherOptions. IncludeNextClosestForms); Assert.AreEqual(13, closest.Count); Assert.Contains("1234567890", closest); Assert.Contains("a1234567890", closest); Assert.Contains("1a234567890", closest); Assert.Contains("1234567890a", closest); Assert.Contains("234567890", closest); Assert.Contains("123457890", closest); Assert.Contains("123456789", closest); Assert.Contains("a234567890", closest); Assert.Contains("1234a67890", closest); Assert.Contains("123456789a", closest); Assert.Contains("2134567890", closest); Assert.Contains("1234657890", closest); Assert.Contains("1234567809", closest); } [Test] public void ClosestAndNextClosest_EditDistance1and3() { AddEntry("a1234567890"); AddEntry("aaa1234567890"); AddEntry("aaa1234567890a"); // noise IList closest = (IList) ApproximateMatcher.FindClosestForms(_forms, "1234567890", ApproximateMatcherOptions. IncludeNextClosestForms); Assert.AreEqual(2, closest.Count); Assert.Contains("a1234567890", closest); Assert.Contains("aaa1234567890", closest); } [Test] public void EditDistance_Same_0() { int editDistance = ApproximateMatcher.EditDistance("abo", "abo", 0, false); Assert.AreEqual(0, editDistance); } [Test] public void EditDistance_SingleInsertionAtStart_1() { int editDistance = ApproximateMatcher.EditDistance("abo", "habo", 1, false); Assert.AreEqual(1, editDistance); } [Test] public void EditDistance_SingleInsertionAtStart_0Max_EditDistanceLargerThanMax() { int editDistance = ApproximateMatcher.EditDistance("abo", "habo", 0, false); Assert.AreEqual(ApproximateMatcher.EditDistanceLargerThanMax, editDistance); } [Test] public void EditDistance_SingleInsertionAtMiddle_1() { int editDistance = ApproximateMatcher.EditDistance("abo", "abho", 1, false); Assert.AreEqual(1, editDistance); } [Test] public void EditDistance_SingleInsertionAtMiddle_0Max_EditDistanceLargerThanMax() { int editDistance = ApproximateMatcher.EditDistance("abo", "abho", 0, false); Assert.AreEqual(ApproximateMatcher.EditDistanceLargerThanMax, editDistance); } [Test] public void EditDistance_SingleInsertionAtEnd_1() { int editDistance = ApproximateMatcher.EditDistance("abo", "aboh", 1, false); Assert.AreEqual(1, editDistance); } [Test] public void EditDistance_SingleInsertionAtStartAndMiddle_2() { int editDistance = ApproximateMatcher.EditDistance("abo", "habho", 2, false); Assert.AreEqual(2, editDistance); } [Test] public void EditDistance_SingleInsertionAtStartAndMiddle_1Max_EditDistanceLargerThanMax() { int editDistance = ApproximateMatcher.EditDistance("abo", "habho", 1, false); Assert.AreEqual(ApproximateMatcher.EditDistanceLargerThanMax, editDistance); } [Test] public void EditDistance_SingleInsertionAtMiddleAndEnd_2() { int editDistance = ApproximateMatcher.EditDistance("abo", "abhoh", 2, false); Assert.AreEqual(2, editDistance); } [Test] public void EditDistance_SingleInsertionAtMiddleAndEnd_1Max_EditDistanceLargerThanMax() { int editDistance = ApproximateMatcher.EditDistance("abo", "abhoh", 1, false); Assert.AreEqual(ApproximateMatcher.EditDistanceLargerThanMax, editDistance); } [Test] public void EditDistance_SingleInsertionAtStartAndEnd_2() { int editDistance = ApproximateMatcher.EditDistance("abo", "haboh", 2, false); Assert.AreEqual(2, editDistance); } [Test] public void EditDistance_SingleInsertionAtStartAndEnd_1Max_EditDistanceLargerThanMax() { int editDistance = ApproximateMatcher.EditDistance("abo", "haboh", 1, false); Assert.AreEqual(ApproximateMatcher.EditDistanceLargerThanMax, editDistance); } [Test] public void EditDistance_SingleDeletionAtStart_1() { int editDistance = ApproximateMatcher.EditDistance("abo", "bo", 1, false); Assert.AreEqual(1, editDistance); } [Test] public void EditDistance_SingleDeletionAtMiddle_1() { int editDistance = ApproximateMatcher.EditDistance("abo", "ao", 1, false); Assert.AreEqual(1, editDistance); } [Test] public void EditDistance_SingleDeletionAtEnd_1() { int editDistance = ApproximateMatcher.EditDistance("abo", "ab", 1, false); Assert.AreEqual(1, editDistance); } [Test] public void EditDistance_SingleDeletionAtStartAndMiddle_2() { int editDistance = ApproximateMatcher.EditDistance("aboh", "bh", 2, false); Assert.AreEqual(2, editDistance); } [Test] public void EditDistance_SingleDeletionAtMiddleAndEnd_2() { int editDistance = ApproximateMatcher.EditDistance("aboh", "ao", 2, false); Assert.AreEqual(2, editDistance); } [Test] public void EditDistance_SingleDeletionAtStartAndEnd_2() { int editDistance = ApproximateMatcher.EditDistance("aboh", "bo", 2, false); Assert.AreEqual(2, editDistance); } [Test] public void EditDistance_SingleSubstitutionAtStart_1() { int editDistance = ApproximateMatcher.EditDistance("abo", "sbo", 1, false); Assert.AreEqual(1, editDistance); } [Test] public void EditDistance_SingleSubstitutionAtMiddle_1() { int editDistance = ApproximateMatcher.EditDistance("abo", "aso", 1, false); Assert.AreEqual(1, editDistance); } [Test] public void EditDistance_SingleSubstitutionAtEnd_1() { int editDistance = ApproximateMatcher.EditDistance("abo", "abs", 1, false); Assert.AreEqual(1, editDistance); } [Test] public void EditDistance_SingleSubstitutionAtStartAndMiddle_2() { int editDistance = ApproximateMatcher.EditDistance("aboh", "sbsh", 2, false); Assert.AreEqual(2, editDistance); } [Test] public void EditDistance_SingleSubstitutionAtMiddleAndEnd_2() { int editDistance = ApproximateMatcher.EditDistance("aboh", "asos", 2, false); Assert.AreEqual(2, editDistance); } [Test] public void EditDistance_SingleSubstitutionAtStartAndEnd_2() { int editDistance = ApproximateMatcher.EditDistance("aboh", "sbos", 2, false); Assert.AreEqual(2, editDistance); } [Test] public void EditDistance_SingleTranspositionAtStart_1() { int editDistance = ApproximateMatcher.EditDistance("abo", "bao", 1, false); Assert.AreEqual(1, editDistance); } [Test] public void EditDistance_SingleTranspositionAtMiddle_1() { int editDistance = ApproximateMatcher.EditDistance("aboh", "aobh", 1, false); Assert.AreEqual(1, editDistance); } [Test] public void EditDistance_SingleTranspositionAtEnd_1() { int editDistance = ApproximateMatcher.EditDistance("abo", "aob", 1, false); Assert.AreEqual(1, editDistance); } [Test] public void EditDistance_SingleTranspositionAtStartAndMiddle_2() { int editDistance = ApproximateMatcher.EditDistance("abohor", "baoohr", 2, false); Assert.AreEqual(2, editDistance); } [Test] public void EditDistance_SingleTranspositionAtMiddleAndEnd_2() { int editDistance = ApproximateMatcher.EditDistance("abohor", "aobhro", 2, false); Assert.AreEqual(2, editDistance); } [Test] public void EditDistance_SingleTranspositionAtStartAndEnd_2() { int editDistance = ApproximateMatcher.EditDistance("abohor", "baohro", 2, false); Assert.AreEqual(2, editDistance); } [Test] public void EditDistance_SingleDeletionAtStartAndSingleInsertionAtEnd_2() { int editDistance = ApproximateMatcher.EditDistance("abo", "boh", 2, false); Assert.AreEqual(2, editDistance); } [Test] public void EditDistance_SingleDeletionAtStartAndSingleInsertionAtEnd_1Max_EditDistanceLargerThanMax () { int editDistance = ApproximateMatcher.EditDistance("abo", "boh", 1, false); Assert.AreEqual(ApproximateMatcher.EditDistanceLargerThanMax, editDistance); } [Test] public void EditDistance_SingleDeletionAtStartAndDoubleInsertionAtEnd_3() { int editDistance = ApproximateMatcher.EditDistance("abo", "boha", 3, false); Assert.AreEqual(3, editDistance); } [Test] public void EditDistance_SingleDeletionAtStartAndDoubleInsertionAtEnd_2Max_EditDistanceLargerThanMax () { int editDistance = ApproximateMatcher.EditDistance("abo", "boha", 2, false); Assert.AreEqual(ApproximateMatcher.EditDistanceLargerThanMax, editDistance); } [Test] public void EditDistance_SingleDeletionAtStartAndSingleTranspositionAtEnd_2() { int editDistance = ApproximateMatcher.EditDistance("aboh", "bho", 2, false); Assert.AreEqual(2, editDistance); } [Test] public void EditDistance_SingleDeletionAtStartAndSingleTranspositionAtEnd_1Max_EditDistanceLargerThanMax () { int editDistance = ApproximateMatcher.EditDistance("aboh", "bho", 1, false); Assert.AreEqual(ApproximateMatcher.EditDistanceLargerThanMax, editDistance); } [Test] public void EditDistance_SingleDeletionAtStartAndSingleSubstitutionAtEnd_2() { int editDistance = ApproximateMatcher.EditDistance("abo", "bi", 2, false); Assert.AreEqual(2, editDistance); } [Test] public void EditDistance_SingleDeletionAtStartAndSingleSubstitutionAtEnd_1Max_EditDistanceLargerThanMax () { int editDistance = ApproximateMatcher.EditDistance("abo", "bi", 1, false); Assert.AreEqual(ApproximateMatcher.EditDistanceLargerThanMax, editDistance); } [Test] public void EditDistance_SingleInsertionAtStartAndSingleDeletionAtEnd_2() { int editDistance = ApproximateMatcher.EditDistance("abo", "rab", 2, false); Assert.AreEqual(2, editDistance); } [Test] public void EditDistance_SingleInsertionAtStartAndSingleTranspositionAtEnd_2() { int editDistance = ApproximateMatcher.EditDistance("abo", "raob", 2, false); Assert.AreEqual(2, editDistance); } [Test] public void EditDistance_SingleInsertionAtStartAndSingleSubstitutionAtEnd_2() { int editDistance = ApproximateMatcher.EditDistance("abo", "rabi", 2, false); Assert.AreEqual(2, editDistance); } [Test] public void EditDistance_SingleInsertionAtEndWithSuffixTreatedAsZeroDistance_1() { Assert.AreEqual(1, ApproximateMatcher.EditDistance("cased", "case", 1, true)); } [Test] public void EditDistance_SingleInsertionAtEndWithSuffixTreatedAsZeroDistance_0() { Assert.AreEqual(0, ApproximateMatcher.EditDistance("case", "cased", 1, true)); } [Test] public void EditDistance_SingleInsertionAtBeginningWithSuffixTreatedAsZeroDistance_1() { // has suffix to ignore on the second word Assert.AreEqual(1, ApproximateMatcher.EditDistance("case", "acaseinfact", 1, true)); } [Test] public void EditDistance_SingleDeletionAtBeginningWithSixInsertionsAtEndAndSuffixTreatedAsZeroDistance_7 () { // no suffix to ignore on the second word Assert.AreEqual(7, ApproximateMatcher.EditDistance("acaseinfact", "case", int.MaxValue, true)); } [Test] public void EditDistance_SingleInsertionSingleSubstitutionAtBeginningSingleSubstitutionAtEndWithSuffixTreatedAsZeroDistance_3 () { // has suffix to ignore on the second word Assert.AreEqual(3, ApproximateMatcher.EditDistance("dist", "noise", 4, true)); } [Test] public void EditDistance_SingleDeletionSingleSubstitutionAtBeginningSingleSubstitutionAtEndWithSuffixTreatedAsZeroDistance_3 () { // no suffix to ignore on the second word Assert.AreEqual(3, ApproximateMatcher.EditDistance("noise", "dist", 4, true)); } [Test] public void EditDistance_SingleInsertionSingleSubstitutionAtBeginningSingleSubstitutionAtEndWithSuffixTreatedAsZeroDistance_2Cutoff_EditDistanceLargerThanMax () { Assert.AreEqual(ApproximateMatcher.EditDistanceLargerThanMax, ApproximateMatcher.EditDistance("noise", "dist", 2, true)); Assert.AreEqual(ApproximateMatcher.EditDistanceLargerThanMax, ApproximateMatcher.EditDistance("dist", "noise", 2, true)); } [Test] public void EditDistance_MajorDifference() { Assert.AreEqual(2, ApproximateMatcher.EditDistance("ab", "\"look busy do nothing\"", int.MaxValue, true)); } /// <summary> /// This test was created after we found that LexEntries did not /// cascade on their delete and so lexical forms could be found even when /// their entry was deleted, causing a crash. /// </summary> [Test] public void Find_AfterDeleted_NotFound() // move to sorted Cache Tests { //LexEntry test = AddEntry("test"); //AddEntry("test1"); //this._records.Remove(test); //IList<LexEntry> closest = ApproximateMatcher.FindEntriesWithClosestLexemeForms("test", _forms); //Assert.AreEqual(1, closest.Count); //Assert.Contains("test1", closest); } //[Test] //public void Time() //{ // Stopwatch stopwatch = new Stopwatch(); // stopwatch.Start(); // Random random = new Random(); // for (int i = 0; i < 5000; i++) // { // string LexicalForm = string.Empty; // for (int j = 0; j < 10; j++) //average word length of 10 characters // { // LexicalForm += Convert.ToChar(random.Next(Convert.ToInt16('a'), Convert.ToInt16('z'))); // } // AddEntry(LexicalForm); // } // // stopwatch.Stop(); // Console.WriteLine("Time to initialize " + stopwatch.Elapsed.ToString()); // // stopwatch.Reset(); // stopwatch.Start(); // Db4oLexQueryHelper.FindClosest("something"); // stopwatch.Stop(); // Console.WriteLine("Time to find " + stopwatch.Elapsed.ToString()); //} } }
using System; namespace Wc3o.Pages.Game { public partial class Details_aspx : System.Web.UI.Page { Player player; protected void Page_Load(object sender, EventArgs e) { player = Wc3o.Game.CurrentPlayer; if (RemoteScripting.InvokeMethod(Page)) return; } #region " GetUnits " public string GetUnits(string div, string s, string t, string isOverview) { Sector sector = Wc3o.Game.GameData.Sectors[new Coordinate(s)]; Player p = player; //if name is empty, it is the current player if (t == "-") //if name is "-", it is the creeps p = null; else if (t.Length > 0) //otherwise, it's another player p = Wc3o.Game.GameData.Players[t]; string unitOwner = ""; string isUnitOwnerAlly = "1"; string canAttack = ""; if (isOverview != "1") { //it is always the current player when it is an overview if (p == null) unitOwner = "-"; else if (p != player) unitOwner = p.Name; if (!player.IsAlly(p)) isUnitOwnerAlly = ""; bool enemyUnits = false; bool alliedUnits = false; if (player.CanAttack(p)) foreach (Unit u in sector.Units) if (u.IsAvailable || u.IsWorking) if (u.Owner == p) enemyUnits = true; else if (u.Owner != player && player.IsAlly(u.Owner)) alliedUnits = true; if (enemyUnits && alliedUnits) canAttack = "2"; else if (enemyUnits) canAttack = "1"; } string sectorOwner = ""; if (sector.Owner != player) if (sector.Owner == null) sectorOwner = "-"; else sectorOwner = sector.Owner.Name; string isSectorOwnerAlly = ""; if (player.IsAlly(sector.Owner)) isSectorOwnerAlly = "1"; string result = div + "@" + s + "@" + isOverview + "@" + unitOwner + "@" + isUnitOwnerAlly + "@" + sectorOwner + "@" + isSectorOwnerAlly + "@" + canAttack + "@" + Wc3o.Game.Gfx + "@"; bool hasView = player.HasView(sector); foreach (Unit u in sector.Units) //You see the units when a) it is a unit of the selected player and b) it is a allied unit or you have view on the sector if (u.Owner == p && ((player.IsAlly(u.Owner)) || (hasView && (u.IsAvailable || u.IsInTraining || u.IsWorking || (u.IsReturning && u.IsVisible) || (u.IsMoving && u.IsVisible && ((TimeSpan)(u.Date - DateTime.Now)).TotalMinutes <= Configuration.Minutes_To_See_Arriving_Units))))) { string action = ""; if (u.IsInTraining) action = "1"; else if (u.IsWorking && u.Action == UnitAction.WorkForGold) action = "2"; else if (u.IsWorking && u.Action == UnitAction.WorkForLumber) action = "3"; else if (u.IsMoving) action = "4"; else if (u.IsReturning) action = "5"; string sourceSector = ""; if (u.SourceSector != null) sourceSector = u.SourceSector.Coordinate.ToString(); string source = ""; if (u.SourceSector != null) source = u.SourceSector.ToString(); int damage = 0; if (u.Hitpoints != u.Info.Hitpoints) damage = 100 - (int)(100 / ((double)u.Info.Hitpoints) * ((double)u.Hitpoints)); string gold = ""; if (u.UnitInfo.ForGold) gold = "1"; string lumber = ""; if (u.UnitInfo.ForLumber) lumber = "1"; #region " Morph units " string morph = "$"; UnitInfo morphTo = null; if (action.Length <= 0) { switch (u.Type) { case UnitType.DruidOfTheClawBearForm: morphTo = UnitInfo.Get(UnitType.DruidOfTheClawDruidForm); break; case UnitType.DruidOfTheClawDruidForm: morphTo = UnitInfo.Get(UnitType.DruidOfTheClawBearForm); break; case UnitType.DruidOfTheTalonCrowForm: morphTo = UnitInfo.Get(UnitType.DruidOfTheTalonDruidForm); break; case UnitType.DruidOfTheTalonDruidForm: morphTo = UnitInfo.Get(UnitType.DruidOfTheTalonCrowForm); break; case UnitType.Peasant: morphTo = UnitInfo.Get(UnitType.Militia); break; case UnitType.Militia: morphTo = UnitInfo.Get(UnitType.Peasant); break; case UnitType.Hippogryph: morphTo = UnitInfo.Get(UnitType.HippogryphRider); break; case UnitType.HippogryphRider: morphTo = UnitInfo.Get(UnitType.Hippogryph); break; case UnitType.Acolyte: morphTo = UnitInfo.Get(UnitType.Shade); break; case UnitType.ObsidianStatue: morphTo = UnitInfo.Get(UnitType.Destroyer); break; } } if (morphTo != null) morph = "$" + morphTo.Name; #endregion result += u.UnitInfo.Name + "$" + u.Type.ToString() + "$" + Wc3o.Game.Format(u.Number) + "$" + u.Info.Image + "$" + Wc3o.Game.TimeSpan(u.Date) + "$" + action + "$" + sourceSector + "$" + source + "$" + u.GetHashCode().ToString() + "$" + Wc3o.Game.Format(damage) + "$" + gold + "$" + lumber + morph + "@"; } return result; } #endregion #region " GetBuildings " public string GetBuildings(string div, string s, string t, string isOverview) { Sector sector = Wc3o.Game.GameData.Sectors[new Coordinate(s)]; Player p = player; //if name is empty, it is the current player if (t == "-") //if name is "-", it is the creeps p = null; else if (t.Length > 0) //otherwise, it's another player p = Wc3o.Game.GameData.Players[t]; string sectorOwner = ""; if (sector.Owner != player) { if (sector.Owner == null) sectorOwner = "-"; else sectorOwner = sector.Owner.Name; } string isSectorOwnerAlly = ""; if (player.IsAlly(p)) isSectorOwnerAlly = "1"; string canAttack = ""; bool alliedUnits = false; if (player.CanAttack(p)) foreach (Unit u in sector.Units) if (u.IsAvailable || u.IsWorking && u.Owner != player && player.IsAlly(u.Owner)) alliedUnits = true; if (player.CanAttack(p)) if (alliedUnits) canAttack = "2"; else canAttack = "1"; string result = div + "@" + s + "@" + isOverview + "@" + sectorOwner + "@" + isSectorOwnerAlly + "@" + canAttack + "@" + Wc3o.Game.Gfx + "@"; bool hasView = player.HasView(sector); if (sector.Owner == p && hasView) { foreach (Building b in sector.Buildings) { string action = ""; if (b.IsInConstruction) { if (b.UpgradingFrom == BuildingType.None) action = "1"; else action = "2"; } int damage = 100 - (int)(100 / ((double)b.BuildingInfo.Hitpoints) * ((double)b.Hitpoints)); result += b.Info.Name + "$" + b.Type.ToString() + "$" + Wc3o.Game.Format(b.Number) + "$" + b.Info.Image + "$" + Wc3o.Game.TimeSpan(b.Date) + "$" + action + "$" + b.GetHashCode() + "$" + Wc3o.Game.Format(damage); foreach (BuildingType type in b.BuildingInfo.UpgradesTo) { //upgrade buildings BuildingInfo i = BuildingInfo.Get(type); result += "$" + i.Name + "$" + i.Type; } result += "@"; } } return result; } #endregion #region " GetTraining " public string GetTraining(string div, string s) { Sector sector = Wc3o.Game.GameData.Sectors[new Coordinate(s)]; string result = div + "@" + s + "@" + player.Gfx + "@"; if (sector.Owner != player) return result; foreach (UnitType t in Enum.GetValues(typeof(UnitType))) { UnitInfo i = UnitInfo.Get(t); if (Wc3o.Game.IsAvailable(player, sector, i)) result += i.Name + "$" + i.CreateImage + "$" + i.Gold + "$" + i.Lumber + "$" + i.Food + "$" + i.Type + "@"; } return result; } #endregion #region " GetConstructing " public string GetConstructing(string div, string s) { Sector sector = Wc3o.Game.GameData.Sectors[new Coordinate(s)]; string result = div + "@" + s + "@"; if (sector.Owner != player) return result; foreach (BuildingType t in Enum.GetValues(typeof(BuildingType))) { BuildingInfo i = BuildingInfo.Get(t); if (Wc3o.Game.IsAvailable(player, sector, i)) { int finished = 0; int constructing = 0; foreach (Building b in sector.Buildings) //counts the finished and constructing buildings on this sector if (b.Type == t && b.IsInConstruction) constructing += b.Number; else if (b.Type == t) finished += b.Number; result += i.Name + "$" + player.Gfx + i.CreateImage + "$" + Wc3o.Game.Format(finished) + "$" + Wc3o.Game.Format(constructing) + "$" + Wc3o.Game.Format(i.Gold) + "$" + player.Gfx + "/Game/Gold.gif" + "$" + Wc3o.Game.Format(i.Lumber) + "$" + player.Gfx + "/Game/Lumber.gif" + "$" + i.Type + "@"; } } return result; } #endregion #region " GetNavigation " public string GetNavigation() { string underSiege = ""; foreach (Sector s in player.Sectors) { foreach (Unit u in s.Units) if (!player.IsAlly(u.Owner) && (u.IsAvailable || u.IsWorking || u.IsReturning || (u.IsMoving && u.Date.AddMinutes(Configuration.Minutes_To_See_Arriving_Units) >= DateTime.Now))) { underSiege = "<a href='Sector.aspx?Sector=" + s.Coordinate.ToString() + "'><img src='" + player.Gfx + "/Game/UnderSiege.gif' title='You are under siege' /></a>"; break; } } string message = ""; foreach (Message m in player.Messages) if (m.Unread) { message = "<a href='Mail.aspx'><img src='" + player.Gfx + "/Game/Message.gif' title='New message' /></a>"; break; } return Wc3o.Game.Format(player.Gold) + "@" + Wc3o.Game.Format(player.Lumber) + "@" + Wc3o.Game.Format(player.Upkeep) + "@" + Wc3o.Game.Format(player.Food) + "@" + Wc3o.Game.TimeSpan(Wc3o.Game.GameData.Ticks.RessourceTick) + "@" + message + "@" + underSiege + "@"; } #endregion } }
/********************************************************************************* = Author: Michael Parsons = = Date: Mar 08/2013 = Assembly: LRWarehouse.Business = Description: = Notes: = = = Copyright 2013, Isle All rights reserved. ********************************************************************************/ using System; using System.Collections.Generic; namespace ILPathways.Business { ///<summary> ///Represents an object that describes a LibrarySection ///</summary> [Serializable] public class LibrarySection : BaseBusinessDataEntity, IBaseObject { ///<summary> ///Initializes a new instance of the LRWarehouse.Business.LibrarySection class. ///</summary> public LibrarySection() { ParentLibrary = new Library(); } #region Properties created from dictionary for LibrarySection private int _libraryId; /// <summary> /// Gets/Sets LibraryId /// </summary> public int LibraryId { get { return this._libraryId; } set { if (this._libraryId == value) { //Ignore set } else { this._libraryId = value; HasChanged = true; } } } private string _libraryTitle = ""; /// <summary> /// Gets/Sets LibraryTitle /// </summary> public string LibraryTitle { get { return this._libraryTitle; } set { this._libraryTitle = value.Trim(); } } private int _sectionTypeId; /// <summary> /// Gets/Sets SectionTypeId /// </summary> public int SectionTypeId { get { return this._sectionTypeId; } set { if (this._sectionTypeId == value) { //Ignore set } else { this._sectionTypeId = value; HasChanged = true; } } } private string _sectionType = ""; /// <summary> /// Gets/Sets SectionType /// </summary> public string SectionType { get { return this._sectionType; } set { if ( this._sectionType == value ) { //Ignore set } else { this._sectionType = value.Trim(); HasChanged = true; } } } private string _title = ""; /// <summary> /// Gets/Sets Title /// </summary> public string Title { get { return this._title; } set { if ( this._title == value ) { //Ignore set } else { this._title = value.Trim(); HasChanged = true; } } } private string _description = ""; /// <summary> /// Gets/Sets Description /// </summary> public string Description { get { return this._description; } set { if (this._description == value) { //Ignore set } else { this._description = value.Trim(); HasChanged = true; } } } private int _parentId; /// <summary> /// Gets/Sets ParentId /// </summary> public int ParentId { get { return this._parentId; } set { if (this._parentId == value) { //Ignore set } else { this._parentId = value; HasChanged = true; } } } private bool _isDefaultSection; /// <summary>IsDefaultSection /// </summary> public bool IsDefaultSection { get { return this._isDefaultSection; } set { if ( this._isDefaultSection == value ) { //Ignore set } else { this._isDefaultSection = value; HasChanged = true; } } } /// <summary> /// Get/Set the Public access level /// </summary> public EObjectAccessLevel PublicAccessLevel { get; set; } /// <summary> /// Get/Set the access level for members of the same org /// </summary> public EObjectAccessLevel OrgAccessLevel { get; set; } private bool _isPublic; /// <summary> /// Gets/Sets IsPublic /// </summary> public bool IsPublic { get { //TODO - transition to use of PublicAccessLevel if ( ( int )PublicAccessLevel > 0 ) return true; else return false; //return this._isPublic; } set { if ( this._isPublic == value ) { //Ignore set } else { this._isPublic = value; HasChanged = true; } } } private bool _areContentsReadOnly; /// <summary> /// Gets/Sets AreContentsReadOnly /// </summary> public bool AreContentsReadOnly { get { return this._areContentsReadOnly; } set { if (this._areContentsReadOnly == value) { //Ignore set } else { this._areContentsReadOnly = value; HasChanged = true; } } } private string _imageUrl = ""; /// <summary> /// Gets/Sets ImageUrl /// </summary> public string ImageUrl { get { return this._imageUrl; } set { if ( this._imageUrl == value ) { //Ignore set } else { this._imageUrl = value.Trim(); HasChanged = true; } } } public string AvatarURL { get { return ImageUrl; } set { ImageUrl = value.Trim(); } } /// <summary> /// Return a url friendly title /// ==> this is no longer set in this object, it needs to be set from external methods like: /// ILPathways.Utilities.UtilityManager.UrlFriendlyTitle() /// </summary> public string FriendlyTitle { get { //return UrlFriendlyTitle( this._title ); if ( string.IsNullOrWhiteSpace( _friendlyTitle ) ) _friendlyTitle = "Collection"; return this._friendlyTitle; } set { if ( this._friendlyTitle != value ) { this._friendlyTitle = value.Trim(); } } } // private string _friendlyTitle = "Collection"; public string FriendlyUrl { get { if ( Id == 0 ) return ""; else return string.Format( "/Library/Collection/{0}/{1}/{2}", LibraryId, Id, this.FriendlyTitle ); } } #endregion #region Helper Methods public Library ParentLibrary { get; set; } public string SectionSummary() { return SectionSummary( "h1"); } // public string SectionSummary( string h1Style) { string summary = ""; summary = FormatLabelDataRow( "Collection: ", Title ); if ( this.Description.Length > 0 ) summary += FormatLabelDataRow( "Description: ", Description ); summary += FormatLabelDataRow( "SectionType: ", SectionType ); summary += FormatLabelDataRow( "Is DefaultSection: ", IsDefaultSection ); summary += FormatLabelDataRow( "Is Public: ", IsPublic ); //construct table summary = string.Format( "<h1 class='{0}'>{1}</h1>", h1Style, LibraryTitle ) + "<table>" + summary + "</table>"; return summary; } // public string SectionSummaryFormatted() { return SectionSummaryFormatted( "" ); } // public string SectionSummaryFormatted( string h1Style ) { string summary = string.Format( "<h1 class='{0}'>{1}</h1>", h1Style, LibraryTitle ); summary += FormatLabelData( "Collection:", Title ); if ( this.Description.Length > 0 ) summary += FormatLabelData( "Description:", Description ); summary += FormatLabelData( "Section Type:", SectionType ); summary += FormatLabelData( "Is DefaultSection: ", IsDefaultSection ); summary += FormatLabelData( "Is Public:", IsPublic ); summary += FormatLabelData( "Are Contents Read Only:", AreContentsReadOnly ); return summary; } // #endregion } // end class } // end Namespace
using YAF.Lucene.Net.Index; using YAF.Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; namespace YAF.Lucene.Net.Codecs.Lucene40 { /* * 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 IBits = YAF.Lucene.Net.Util.IBits; using BytesRef = YAF.Lucene.Net.Util.BytesRef; using Directory = YAF.Lucene.Net.Store.Directory; using DocsAndPositionsEnum = YAF.Lucene.Net.Index.DocsAndPositionsEnum; using DocsEnum = YAF.Lucene.Net.Index.DocsEnum; using FieldInfo = YAF.Lucene.Net.Index.FieldInfo; using FieldInfos = YAF.Lucene.Net.Index.FieldInfos; using Fields = YAF.Lucene.Net.Index.Fields; using IndexFileNames = YAF.Lucene.Net.Index.IndexFileNames; using IndexInput = YAF.Lucene.Net.Store.IndexInput; using IOContext = YAF.Lucene.Net.Store.IOContext; using IOUtils = YAF.Lucene.Net.Util.IOUtils; using SegmentInfo = YAF.Lucene.Net.Index.SegmentInfo; using Terms = YAF.Lucene.Net.Index.Terms; using TermsEnum = YAF.Lucene.Net.Index.TermsEnum; /// <summary> /// Lucene 4.0 Term Vectors reader. /// <para/> /// It reads .tvd, .tvf, and .tvx files. /// </summary> /// <seealso cref="Lucene40TermVectorsFormat"/> public class Lucene40TermVectorsReader : TermVectorsReader, IDisposable { internal const sbyte STORE_POSITIONS_WITH_TERMVECTOR = 0x1; internal const sbyte STORE_OFFSET_WITH_TERMVECTOR = 0x2; internal const sbyte STORE_PAYLOAD_WITH_TERMVECTOR = 0x4; /// <summary> /// Extension of vectors fields file. </summary> internal const string VECTORS_FIELDS_EXTENSION = "tvf"; /// <summary> /// Extension of vectors documents file. </summary> internal const string VECTORS_DOCUMENTS_EXTENSION = "tvd"; /// <summary> /// Extension of vectors index file. </summary> internal const string VECTORS_INDEX_EXTENSION = "tvx"; internal const string CODEC_NAME_FIELDS = "Lucene40TermVectorsFields"; internal const string CODEC_NAME_DOCS = "Lucene40TermVectorsDocs"; internal const string CODEC_NAME_INDEX = "Lucene40TermVectorsIndex"; internal const int VERSION_NO_PAYLOADS = 0; internal const int VERSION_PAYLOADS = 1; internal const int VERSION_START = VERSION_NO_PAYLOADS; internal const int VERSION_CURRENT = VERSION_PAYLOADS; internal static readonly long HEADER_LENGTH_FIELDS = CodecUtil.HeaderLength(CODEC_NAME_FIELDS); internal static readonly long HEADER_LENGTH_DOCS = CodecUtil.HeaderLength(CODEC_NAME_DOCS); internal static readonly long HEADER_LENGTH_INDEX = CodecUtil.HeaderLength(CODEC_NAME_INDEX); private FieldInfos fieldInfos; private IndexInput tvx; private IndexInput tvd; private IndexInput tvf; private int size; private int numTotalDocs; /// <summary> /// Used by clone. </summary> internal Lucene40TermVectorsReader(FieldInfos fieldInfos, IndexInput tvx, IndexInput tvd, IndexInput tvf, int size, int numTotalDocs) { this.fieldInfos = fieldInfos; this.tvx = tvx; this.tvd = tvd; this.tvf = tvf; this.size = size; this.numTotalDocs = numTotalDocs; } /// <summary> /// Sole constructor. </summary> public Lucene40TermVectorsReader(Directory d, SegmentInfo si, FieldInfos fieldInfos, IOContext context) { string segment = si.Name; int size = si.DocCount; bool success = false; try { string idxName = IndexFileNames.SegmentFileName(segment, "", VECTORS_INDEX_EXTENSION); tvx = d.OpenInput(idxName, context); int tvxVersion = CodecUtil.CheckHeader(tvx, CODEC_NAME_INDEX, VERSION_START, VERSION_CURRENT); string fn = IndexFileNames.SegmentFileName(segment, "", VECTORS_DOCUMENTS_EXTENSION); tvd = d.OpenInput(fn, context); int tvdVersion = CodecUtil.CheckHeader(tvd, CODEC_NAME_DOCS, VERSION_START, VERSION_CURRENT); fn = IndexFileNames.SegmentFileName(segment, "", VECTORS_FIELDS_EXTENSION); tvf = d.OpenInput(fn, context); int tvfVersion = CodecUtil.CheckHeader(tvf, CODEC_NAME_FIELDS, VERSION_START, VERSION_CURRENT); Debug.Assert(HEADER_LENGTH_INDEX == tvx.GetFilePointer()); Debug.Assert(HEADER_LENGTH_DOCS == tvd.GetFilePointer()); Debug.Assert(HEADER_LENGTH_FIELDS == tvf.GetFilePointer()); Debug.Assert(tvxVersion == tvdVersion); Debug.Assert(tvxVersion == tvfVersion); numTotalDocs = (int)(tvx.Length - HEADER_LENGTH_INDEX >> 4); this.size = numTotalDocs; Debug.Assert(size == 0 || numTotalDocs == size); this.fieldInfos = fieldInfos; success = true; } finally { // With lock-less commits, it's entirely possible (and // fine) to hit a FileNotFound exception above. In // this case, we want to explicitly close any subset // of things that were opened so that we don't have to // wait for a GC to do so. if (!success) { try { Dispose(); } // ensure we throw our original exception #pragma warning disable 168 catch (Exception t) #pragma warning restore 168 { } } } } // Used for bulk copy when merging internal virtual IndexInput TvdStream { get { return tvd; } } // Used for bulk copy when merging internal virtual IndexInput TvfStream { get { return tvf; } } // Not private to avoid synthetic access$NNN methods internal virtual void SeekTvx(int docNum) { tvx.Seek(docNum * 16L + HEADER_LENGTH_INDEX); } /// <summary> /// Retrieve the length (in bytes) of the tvd and tvf /// entries for the next <paramref name="numDocs"/> starting with /// <paramref name="startDocID"/>. This is used for bulk copying when /// merging segments, if the field numbers are /// congruent. Once this returns, the tvf &amp; tvd streams /// are seeked to the <paramref name="startDocID"/>. /// </summary> internal void RawDocs(int[] tvdLengths, int[] tvfLengths, int startDocID, int numDocs) { if (tvx == null) { Arrays.Fill(tvdLengths, 0); Arrays.Fill(tvfLengths, 0); return; } SeekTvx(startDocID); long tvdPosition = tvx.ReadInt64(); tvd.Seek(tvdPosition); long tvfPosition = tvx.ReadInt64(); tvf.Seek(tvfPosition); long lastTvdPosition = tvdPosition; long lastTvfPosition = tvfPosition; int count = 0; while (count < numDocs) { int docID = startDocID + count + 1; Debug.Assert(docID <= numTotalDocs); if (docID < numTotalDocs) { tvdPosition = tvx.ReadInt64(); tvfPosition = tvx.ReadInt64(); } else { tvdPosition = tvd.Length; tvfPosition = tvf.Length; Debug.Assert(count == numDocs - 1); } tvdLengths[count] = (int)(tvdPosition - lastTvdPosition); tvfLengths[count] = (int)(tvfPosition - lastTvfPosition); count++; lastTvdPosition = tvdPosition; lastTvfPosition = tvfPosition; } } protected override void Dispose(bool disposing) { if (disposing) IOUtils.Dispose(tvx, tvd, tvf); } /// <summary> /// The number of documents in the reader. /// <para/> /// NOTE: This was size() in Lucene. /// </summary> internal virtual int Count { get { return size; } } private class TVFields : Fields { private readonly Lucene40TermVectorsReader outerInstance; private readonly int[] fieldNumbers; private readonly long[] fieldFPs; private readonly IDictionary<int, int> fieldNumberToIndex = new Dictionary<int, int>(); public TVFields(Lucene40TermVectorsReader outerInstance, int docID) { this.outerInstance = outerInstance; outerInstance.SeekTvx(docID); outerInstance.tvd.Seek(outerInstance.tvx.ReadInt64()); int fieldCount = outerInstance.tvd.ReadVInt32(); Debug.Assert(fieldCount >= 0); if (fieldCount != 0) { fieldNumbers = new int[fieldCount]; fieldFPs = new long[fieldCount]; for (int fieldUpto = 0; fieldUpto < fieldCount; fieldUpto++) { int fieldNumber = outerInstance.tvd.ReadVInt32(); fieldNumbers[fieldUpto] = fieldNumber; fieldNumberToIndex[fieldNumber] = fieldUpto; } long position = outerInstance.tvx.ReadInt64(); fieldFPs[0] = position; for (int fieldUpto = 1; fieldUpto < fieldCount; fieldUpto++) { position += outerInstance.tvd.ReadVInt64(); fieldFPs[fieldUpto] = position; } } else { // TODO: we can improve writer here, eg write 0 into // tvx file, so we know on first read from tvx that // this doc has no TVs fieldNumbers = null; fieldFPs = null; } } public override IEnumerator<string> GetEnumerator() { return GetFieldInfoEnumerable().GetEnumerator(); } private IEnumerable<string> GetFieldInfoEnumerable() { int fieldUpto = 0; while (fieldNumbers != null && fieldUpto < fieldNumbers.Length) { yield return outerInstance.fieldInfos.FieldInfo(fieldNumbers[fieldUpto++]).Name; } } public override Terms GetTerms(string field) { FieldInfo fieldInfo = outerInstance.fieldInfos.FieldInfo(field); if (fieldInfo == null) { // No such field return null; } int fieldIndex; if (!fieldNumberToIndex.TryGetValue(fieldInfo.Number, out fieldIndex)) { // Term vectors were not indexed for this field return null; } return new TVTerms(outerInstance, fieldFPs[fieldIndex]); } public override int Count { get { if (fieldNumbers == null) { return 0; } else { return fieldNumbers.Length; } } } } private class TVTerms : Terms { private readonly Lucene40TermVectorsReader outerInstance; private readonly int numTerms; private readonly long tvfFPStart; private readonly bool storePositions; private readonly bool storeOffsets; private readonly bool storePayloads; public TVTerms(Lucene40TermVectorsReader outerInstance, long tvfFP) { this.outerInstance = outerInstance; outerInstance.tvf.Seek(tvfFP); numTerms = outerInstance.tvf.ReadVInt32(); byte bits = outerInstance.tvf.ReadByte(); storePositions = (bits & STORE_POSITIONS_WITH_TERMVECTOR) != 0; storeOffsets = (bits & STORE_OFFSET_WITH_TERMVECTOR) != 0; storePayloads = (bits & STORE_PAYLOAD_WITH_TERMVECTOR) != 0; tvfFPStart = outerInstance.tvf.GetFilePointer(); } public override TermsEnum GetIterator(TermsEnum reuse) { TVTermsEnum termsEnum; if (reuse is TVTermsEnum) { termsEnum = (TVTermsEnum)reuse; if (!termsEnum.CanReuse(outerInstance.tvf)) { termsEnum = new TVTermsEnum(outerInstance); } } else { termsEnum = new TVTermsEnum(outerInstance); } termsEnum.Reset(numTerms, tvfFPStart, storePositions, storeOffsets, storePayloads); return termsEnum; } public override long Count { get { return numTerms; } } public override long SumTotalTermFreq { get { return -1; } } public override long SumDocFreq { get { // Every term occurs in just one doc: return numTerms; } } public override int DocCount { get { return 1; } } public override IComparer<BytesRef> Comparer { get { // TODO: really indexer hardwires // this...? I guess codec could buffer and re-sort... return BytesRef.UTF8SortedAsUnicodeComparer; } } public override bool HasFreqs { get { return true; } } public override bool HasOffsets { get { return storeOffsets; } } public override bool HasPositions { get { return storePositions; } } public override bool HasPayloads { get { return storePayloads; } } } private class TVTermsEnum : TermsEnum { private readonly Lucene40TermVectorsReader outerInstance; private readonly IndexInput origTVF; private readonly IndexInput tvf; private int numTerms; private int nextTerm; private int freq; private readonly BytesRef lastTerm = new BytesRef(); private readonly BytesRef term = new BytesRef(); private bool storePositions; private bool storeOffsets; private bool storePayloads; private long tvfFP; private int[] positions; private int[] startOffsets; private int[] endOffsets; // one shared byte[] for any term's payloads private int[] payloadOffsets; private int lastPayloadLength; private byte[] payloadData; // NOTE: tvf is pre-positioned by caller public TVTermsEnum(Lucene40TermVectorsReader outerInstance) { this.outerInstance = outerInstance; this.origTVF = outerInstance.tvf; tvf = (IndexInput)origTVF.Clone(); } public virtual bool CanReuse(IndexInput tvf) { return tvf == origTVF; } public virtual void Reset(int numTerms, long tvfFPStart, bool storePositions, bool storeOffsets, bool storePayloads) { this.numTerms = numTerms; this.storePositions = storePositions; this.storeOffsets = storeOffsets; this.storePayloads = storePayloads; nextTerm = 0; tvf.Seek(tvfFPStart); tvfFP = tvfFPStart; positions = null; startOffsets = null; endOffsets = null; payloadOffsets = null; payloadData = null; lastPayloadLength = -1; } // NOTE: slow! (linear scan) public override SeekStatus SeekCeil(BytesRef text) { if (nextTerm != 0) { int cmp = text.CompareTo(term); if (cmp < 0) { nextTerm = 0; tvf.Seek(tvfFP); } else if (cmp == 0) { return SeekStatus.FOUND; } } while (Next() != null) { int cmp = text.CompareTo(term); if (cmp < 0) { return SeekStatus.NOT_FOUND; } else if (cmp == 0) { return SeekStatus.FOUND; } } return SeekStatus.END; } public override void SeekExact(long ord) { throw new System.NotSupportedException(); } public override BytesRef Next() { if (nextTerm >= numTerms) { return null; } term.CopyBytes(lastTerm); int start = tvf.ReadVInt32(); int deltaLen = tvf.ReadVInt32(); term.Length = start + deltaLen; term.Grow(term.Length); tvf.ReadBytes(term.Bytes, start, deltaLen); freq = tvf.ReadVInt32(); if (storePayloads) { positions = new int[freq]; payloadOffsets = new int[freq]; int totalPayloadLength = 0; int pos = 0; for (int posUpto = 0; posUpto < freq; posUpto++) { int code = tvf.ReadVInt32(); pos += (int)((uint)code >> 1); positions[posUpto] = pos; if ((code & 1) != 0) { // length change lastPayloadLength = tvf.ReadVInt32(); } payloadOffsets[posUpto] = totalPayloadLength; totalPayloadLength += lastPayloadLength; Debug.Assert(totalPayloadLength >= 0); } payloadData = new byte[totalPayloadLength]; tvf.ReadBytes(payloadData, 0, payloadData.Length); } // no payloads else if (storePositions) { // TODO: we could maybe reuse last array, if we can // somehow be careful about consumer never using two // D&PEnums at once... positions = new int[freq]; int pos = 0; for (int posUpto = 0; posUpto < freq; posUpto++) { pos += tvf.ReadVInt32(); positions[posUpto] = pos; } } if (storeOffsets) { startOffsets = new int[freq]; endOffsets = new int[freq]; int offset = 0; for (int posUpto = 0; posUpto < freq; posUpto++) { startOffsets[posUpto] = offset + tvf.ReadVInt32(); offset = endOffsets[posUpto] = startOffsets[posUpto] + tvf.ReadVInt32(); } } lastTerm.CopyBytes(term); nextTerm++; return term; } public override BytesRef Term { get { return term; } } public override long Ord { get { throw new System.NotSupportedException(); } } public override int DocFreq { get { return 1; } } public override long TotalTermFreq { get { return freq; } } public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags) // ignored { TVDocsEnum docsEnum; if (reuse != null && reuse is TVDocsEnum) { docsEnum = (TVDocsEnum)reuse; } else { docsEnum = new TVDocsEnum(); } docsEnum.Reset(liveDocs, freq); return docsEnum; } public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { if (!storePositions && !storeOffsets) { return null; } TVDocsAndPositionsEnum docsAndPositionsEnum; if (reuse != null && reuse is TVDocsAndPositionsEnum) { docsAndPositionsEnum = (TVDocsAndPositionsEnum)reuse; } else { docsAndPositionsEnum = new TVDocsAndPositionsEnum(); } docsAndPositionsEnum.Reset(liveDocs, positions, startOffsets, endOffsets, payloadOffsets, payloadData); return docsAndPositionsEnum; } public override IComparer<BytesRef> Comparer { get { return BytesRef.UTF8SortedAsUnicodeComparer; } } } // NOTE: sort of a silly class, since you can get the // freq() already by TermsEnum.totalTermFreq private class TVDocsEnum : DocsEnum { private bool didNext; private int doc = -1; private int freq; private IBits liveDocs; public override int Freq { get { return freq; } } public override int DocID { get { return doc; } } public override int NextDoc() { if (!didNext && (liveDocs == null || liveDocs.Get(0))) { didNext = true; return (doc = 0); } else { return (doc = NO_MORE_DOCS); } } public override int Advance(int target) { return SlowAdvance(target); } public virtual void Reset(IBits liveDocs, int freq) { this.liveDocs = liveDocs; this.freq = freq; this.doc = -1; didNext = false; } public override long GetCost() { return 1; } } private sealed class TVDocsAndPositionsEnum : DocsAndPositionsEnum { private bool didNext; private int doc = -1; private int nextPos; private IBits liveDocs; private int[] positions; private int[] startOffsets; private int[] endOffsets; private int[] payloadOffsets; private readonly BytesRef payload = new BytesRef(); private byte[] payloadBytes; public override int Freq { get { if (positions != null) { return positions.Length; } else { Debug.Assert(startOffsets != null); return startOffsets.Length; } } } public override int DocID { get { return doc; } } public override int NextDoc() { if (!didNext && (liveDocs == null || liveDocs.Get(0))) { didNext = true; return (doc = 0); } else { return (doc = NO_MORE_DOCS); } } public override int Advance(int target) { return SlowAdvance(target); } public void Reset(IBits liveDocs, int[] positions, int[] startOffsets, int[] endOffsets, int[] payloadLengths, byte[] payloadBytes) { this.liveDocs = liveDocs; this.positions = positions; this.startOffsets = startOffsets; this.endOffsets = endOffsets; this.payloadOffsets = payloadLengths; this.payloadBytes = payloadBytes; this.doc = -1; didNext = false; nextPos = 0; } public override BytesRef GetPayload() { if (payloadOffsets == null) { return null; } else { int off = payloadOffsets[nextPos - 1]; int end = nextPos == payloadOffsets.Length ? payloadBytes.Length : payloadOffsets[nextPos]; if (end - off == 0) { return null; } payload.Bytes = payloadBytes; payload.Offset = off; payload.Length = end - off; return payload; } } public override int NextPosition() { // LUCENENET TODO: BUG - Need to investigate why this assert sometimes fails // which will cause the test runner to crash on .NET Core 2.0 #if !NETSTANDARD2_0 && !NETSTANDARD2_1 Debug.Assert((positions != null && nextPos < positions.Length) || startOffsets != null && nextPos < startOffsets.Length); #endif if (positions != null) { return positions[nextPos++]; } else { nextPos++; return -1; } } public override int StartOffset { get { if (startOffsets == null) { return -1; } else { return startOffsets[nextPos - 1]; } } } public override int EndOffset { get { if (endOffsets == null) { return -1; } else { return endOffsets[nextPos - 1]; } } } public override long GetCost() { return 1; } } public override Fields Get(int docID) { if (tvx != null) { Fields fields = new TVFields(this, docID); if (fields.Count == 0) { // TODO: we can improve writer here, eg write 0 into // tvx file, so we know on first read from tvx that // this doc has no TVs return null; } else { return fields; } } else { return null; } } public override object Clone() { IndexInput cloneTvx = null; IndexInput cloneTvd = null; IndexInput cloneTvf = null; // These are null when a TermVectorsReader was created // on a segment that did not have term vectors saved if (tvx != null && tvd != null && tvf != null) { cloneTvx = (IndexInput)tvx.Clone(); cloneTvd = (IndexInput)tvd.Clone(); cloneTvf = (IndexInput)tvf.Clone(); } return new Lucene40TermVectorsReader(fieldInfos, cloneTvx, cloneTvd, cloneTvf, size, numTotalDocs); } public override long RamBytesUsed() { return 0; } public override void CheckIntegrity() { } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Linq; using System.Collections; using System.IO; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class CollectionTests { [Fact] public static void X509Certificate2CollectionEnumerator() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); X509Certificate2Enumerator e = cc.GetEnumerator(); object ignored; // Not started Assert.Throws<InvalidOperationException>(() => ignored = e.Current); Assert.True(e.MoveNext()); Assert.Same(c1, e.Current); Assert.True(e.MoveNext()); Assert.Same(c2, e.Current); Assert.True(e.MoveNext()); Assert.Same(c3, e.Current); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); // ended. Assert.Throws<InvalidOperationException>(() => ignored = e.Current); } } [Fact] public static void X509CertificateCollectionEnumerator() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); X509CertificateCollection.X509CertificateEnumerator e = cc.GetEnumerator(); object ignored; // Not started Assert.Throws<InvalidOperationException>(() => ignored = e.Current); Assert.True(e.MoveNext()); Assert.Same(c1, e.Current); Assert.True(e.MoveNext()); Assert.Same(c2, e.Current); Assert.True(e.MoveNext()); Assert.Same(c3, e.Current); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); // ended. Assert.Throws<InvalidOperationException>(() => ignored = e.Current); } } [Fact] public static void X509Certificate2CollectionEnumeratorModification() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); X509Certificate2Collection.X509CertificateEnumerator e = cc.GetEnumerator(); cc.Add(c1); // Collection changed. Assert.Throws<InvalidOperationException>(() => e.MoveNext()); } } [Fact] public static void X509CertificateCollectionAdd() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) { X509CertificateCollection cc = new X509CertificateCollection(); int idx = cc.Add(c1); Assert.Equal(0, idx); idx = cc.Add(c2); Assert.Equal(1, idx); Assert.Throws<ArgumentNullException>(() => cc.Add(null)); } } [Fact] public static void X509CertificateCollectionAsIList() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) { X509CertificateCollection cc = new X509CertificateCollection(); cc.Add(c1); cc.Add(c2); IList il = cc; Assert.Throws<ArgumentNullException>(() => il[0] = null); il[0] = "Bogus"; Assert.Equal("Bogus", il[0]); object ignored; Assert.Throws<InvalidCastException>(() => ignored = cc[0]); } } [Fact] public static void AddDoesNotClone() { using (X509Certificate2 c1 = new X509Certificate2()) { X509Certificate2Collection coll = new X509Certificate2Collection(); coll.Add(c1); Assert.Same(c1, coll[0]); } } [Fact] public static void ImportNull() { X509Certificate2Collection cc2 = new X509Certificate2Collection(); Assert.Throws<ArgumentNullException>(() => cc2.Import((byte[])null)); Assert.Throws<ArgumentNullException>(() => cc2.Import((String)null)); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void ImportPfx() { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection cc2 = new X509Certificate2Collection(); cc2.Import(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.DefaultKeySet); int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { // pfxCer was loaded directly, cc2[0] was Imported, two distinct copies. Assert.NotSame(pfxCer, c); Assert.Equal(pfxCer, c); Assert.Equal(pfxCer.Thumbprint, c.Thumbprint); } } } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void ImportStoreSavedAsCerData() { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection cc2 = new X509Certificate2Collection(); cc2.Import(TestData.StoreSavedAsCerData); int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { // pfxCer was loaded directly, cc2[0] was Imported, two distinct copies. Assert.NotSame(pfxCer, c); Assert.Equal(pfxCer, c); Assert.Equal(pfxCer.Thumbprint, c.Thumbprint); } } } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void ImportStoreSavedAsSerializedCerData() { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection cc2 = new X509Certificate2Collection(); cc2.Import(TestData.StoreSavedAsSerializedCerData); int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { // pfxCer was loaded directly, cc2[0] was Imported, two distinct copies. Assert.NotSame(pfxCer, c); Assert.Equal(pfxCer, c); Assert.Equal(pfxCer.Thumbprint, c.Thumbprint); } } } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void ImportStoreSavedAsSerializedStoreData() { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection cc2 = new X509Certificate2Collection(); cc2.Import(TestData.StoreSavedAsSerializedStoreData); int count = cc2.Count; Assert.Equal(2, count); X509Certificate2[] cs = cc2.ToArray().OrderBy(c => c.Subject).ToArray(); Assert.NotSame(msCer, cs[0]); Assert.Equal(msCer, cs[0]); Assert.Equal(msCer.Thumbprint, cs[0].Thumbprint); Assert.NotSame(pfxCer, cs[1]); Assert.Equal(pfxCer, cs[1]); Assert.Equal(pfxCer.Thumbprint, cs[1].Thumbprint); } } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void ImportStoreSavedAsPfxData() { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection cc2 = new X509Certificate2Collection(); cc2.Import(TestData.StoreSavedAsPfxData); int count = cc2.Count; Assert.Equal(2, count); X509Certificate2[] cs = cc2.ToArray().OrderBy(c => c.Subject).ToArray(); Assert.NotSame(msCer, cs[0]); Assert.Equal(msCer, cs[0]); Assert.Equal(msCer.Thumbprint, cs[0].Thumbprint); Assert.NotSame(pfxCer, cs[1]); Assert.Equal(pfxCer, cs[1]); Assert.Equal(pfxCer.Thumbprint, cs[1].Thumbprint); } } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void ImportFromFileTests() { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection cc2 = new X509Certificate2Collection(); cc2.Import(Path.Combine("TestData" ,"My.pfx"), TestData.PfxDataPassword, X509KeyStorageFlags.DefaultKeySet); int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { // pfxCer was loaded directly, cc2[0] was Imported, two distinct copies. Assert.NotSame(pfxCer, c); Assert.Equal(pfxCer, c); Assert.Equal(pfxCer.Thumbprint, c.Thumbprint); } } } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void ExportCert() { TestExportSingleCert(X509ContentType.Cert); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void ExportSerializedCert() { TestExportSingleCert(X509ContentType.SerializedCert); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void ExportSerializedStore() { TestExportStore(X509ContentType.SerializedStore); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void ExportPkcs7() { TestExportStore(X509ContentType.Pkcs7); } [Fact] public static void X509CertificateCollectionSyncRoot() { var cc = new X509CertificateCollection(); Assert.NotNull(((ICollection)cc).SyncRoot); Assert.Same(((ICollection)cc).SyncRoot, ((ICollection)cc).SyncRoot); } private static void TestExportSingleCert(X509ContentType ct) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { msCer, pfxCer }); byte[] blob = cc.Export(ct); Assert.Equal(ct, X509Certificate2.GetCertContentType(blob)); X509Certificate2Collection cc2 = new X509Certificate2Collection(); cc2.Import(blob); int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { Assert.NotSame(msCer, c); Assert.NotSame(pfxCer, c); Assert.True(msCer.Equals(c) || pfxCer.Equals(c)); } } } private static void TestExportStore(X509ContentType ct) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { msCer, pfxCer }); byte[] blob = cc.Export(ct); Assert.Equal(ct, X509Certificate2.GetCertContentType(blob)); X509Certificate2Collection cc2 = new X509Certificate2Collection(); cc2.Import(blob); int count = cc2.Count; Assert.Equal(2, count); X509Certificate2[] cs = cc2.ToArray().OrderBy(c => c.Subject).ToArray(); using (X509Certificate2 first = cs[0]) { Assert.NotSame(msCer, first); Assert.Equal(msCer, first); } using (X509Certificate2 second = cs[1]) { Assert.NotSame(pfxCer, second); Assert.Equal(pfxCer, second); } } } private static X509Certificate2[] ToArray(this X509Certificate2Collection col) { X509Certificate2[] array = new X509Certificate2[col.Count]; for (int i = 0; i < col.Count; i++) { array[i] = col[i]; } return array; } } }
// // 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; using System.Text; using System.Text.RegularExpressions; namespace Microsoft.Azure.Commands.Compute.Automation { public abstract class ComputeAutomationBaseCmdlet : Microsoft.Azure.Commands.Compute.ComputeClientBaseCmdlet { public override void ExecuteCmdlet() { base.ExecuteCmdlet(); } 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 IContainerServicesOperations ContainerServicesClient { get { return ComputeClient.ComputeManagementClient.ContainerServices; } } public IDisksOperations DisksClient { get { return ComputeClient.ComputeManagementClient.Disks; } } public IImagesOperations ImagesClient { get { return ComputeClient.ComputeManagementClient.Images; } } public ILogAnalyticsOperations LogAnalyticsClient { get { return ComputeClient.ComputeManagementClient.LogAnalytics; } } 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 IVirtualMachineScaleSetRollingUpgradesOperations VirtualMachineScaleSetRollingUpgradesClient { get { return ComputeClient.ComputeManagementClient.VirtualMachineScaleSetRollingUpgrades; } } 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 || propType.Equals(typeof(Newtonsoft.Json.Linq.JObject))) { 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); } public static string GetResourceGroupName(string resourceId) { if (string.IsNullOrEmpty(resourceId)) { return null; } Regex r = new Regex(@"(.*?)/resourcegroups/(?<rgname>\S+)/providers/(.*?)", RegexOptions.IgnoreCase); Match m = r.Match(resourceId); return m.Success ? m.Groups["rgname"].Value : null; } public static string GetResourceName(string resourceId, string resourceName, string instanceName = null) { if (string.IsNullOrEmpty(resourceId)) { return null; } Regex r = (instanceName == null) ? new Regex(@"(.*?)/" + resourceName + @"/(?<rgname>\S+)", RegexOptions.IgnoreCase) : new Regex(@"(.*?)/" + resourceName + @"/(?<rgname>\S+)/" + instanceName + @"/(?<instanceId>\S+)", RegexOptions.IgnoreCase); Match m = r.Match(resourceId); return m.Success ? m.Groups["rgname"].Value : null; } public static string GetInstanceId(string resourceId, string resourceName, string instanceName) { if (string.IsNullOrEmpty(resourceId)) { return null; } Regex r = new Regex(@"(.*?)/" + resourceName + @"/(?<rgname>\S+)/" + instanceName + @"/(?<instanceId>\S+)", RegexOptions.IgnoreCase); Match m = r.Match(resourceId); return m.Success ? m.Groups["instanceId"].Value : null; } } public static class LocationStringExtensions { public static string Canonicalize(this string location) { if (!string.IsNullOrEmpty(location)) { StringBuilder sb = new StringBuilder(); foreach (char ch in location) { if (!char.IsWhiteSpace(ch)) { sb.Append(ch); } } location = sb.ToString().ToLower(); } return location; } } }
/* Bullet for XNA Copyright (c) 2003-2007 Vsevolod Klementjev http://www.codeplex.com/xnadevru Bullet original C++ version Copyright (c) 2003-2007 Erwin Coumans http://bulletphysics.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; namespace XnaDevRu.BulletX.Dynamics { /// <summary> /// DiscreteDynamicsWorld provides discrete rigid body simulation /// those classes replace the obsolete CcdPhysicsEnvironment/CcdPhysicsController /// </summary> public class DiscreteDynamicsWorld : DynamicsWorld { private static bool _reportMe = true; private IConstraintSolver _constraintSolver; private SimulationIslandManager _islandManager; private List<TypedConstraint> _constraints = new List<TypedConstraint>(); private IDebugDraw _debugDrawer; private ContactSolverInfo _solverInfo = new ContactSolverInfo(); private Vector3 _gravity; //for variable timesteps private float _localTime; //for variable timesteps private bool _ownsIslandManager; private bool _ownsConstraintSolver; private List<RaycastVehicle> _vehicles = new List<RaycastVehicle>(); private int _profileTimings; public DiscreteDynamicsWorld(IDispatcher dispatcher, OverlappingPairCache pairCache) : this(dispatcher, pairCache, null) { } //this btDiscreteDynamicsWorld constructor gets created objects from the user, and will not delete those public DiscreteDynamicsWorld(IDispatcher dispatcher, OverlappingPairCache pairCache, IConstraintSolver constraintSolver) : base(dispatcher, pairCache) { _constraintSolver = constraintSolver != null ? constraintSolver : new SequentialImpulseConstraintSolver(); _debugDrawer = null; _gravity = new Vector3(0, -10, 0); _localTime = 1f / 60f; _profileTimings = 0; _islandManager = new SimulationIslandManager(); _ownsIslandManager = true; _ownsConstraintSolver = constraintSolver == null; } public ContactSolverInfo SolverInfo { get { return _solverInfo; } } public SimulationIslandManager SimulationIslandManager { get { return _islandManager; } } public CollisionWorld CollisionWorld { get { return this; } } public override IDebugDraw DebugDrawer { get { return _debugDrawer; } set { _debugDrawer = value; } } public override Vector3 Gravity { set { _gravity = value; for (int i = 0; i < CollisionObjects.Count; i++) { CollisionObject colObj = CollisionObjects[i]; RigidBody body = RigidBody.Upcast(colObj); if (body != null) { body.Gravity = value; } } } } public override IConstraintSolver ConstraintSolver { set { _ownsConstraintSolver = false; _constraintSolver = value; } } public override int ConstraintsCount { get { return _constraints.Count; } } //if maxSubSteps > 0, it will interpolate motion between fixedTimeStep's public override void StepSimulation(float timeStep, int maxSubSteps, float fixedTimeStep) { int numSimulationSubSteps = 0; if (maxSubSteps != 0) { //fixed timestep with interpolation _localTime += timeStep; if (_localTime >= fixedTimeStep) { numSimulationSubSteps = (int)(_localTime / fixedTimeStep); _localTime -= numSimulationSubSteps * fixedTimeStep; } } else { //variable timestep fixedTimeStep = timeStep; _localTime = timeStep; if (Math.Abs(timeStep) < float.Epsilon) { numSimulationSubSteps = 0; maxSubSteps = 0; } else { numSimulationSubSteps = 1; maxSubSteps = 1; } } //process some debugging flags if (DebugDrawer != null) { RigidBody.DisableDeactivation = (DebugDrawer.DebugMode & DebugDrawModes.NoDeactivation) != 0; } if (numSimulationSubSteps != 0) { SaveKinematicState(fixedTimeStep); //clamp the number of substeps, to prevent simulation grinding spiralling down to a halt int clampedSimulationSteps = (numSimulationSubSteps > maxSubSteps) ? maxSubSteps : numSimulationSubSteps; for (int i = 0; i < clampedSimulationSteps; i++) { InternalSingleStepSimulation(fixedTimeStep); SynchronizeMotionStates(); } } SynchronizeMotionStates(); //return numSimulationSubSteps; } public void StepSimulation(float timeStep, int maxSubSteps) { StepSimulation(timeStep, maxSubSteps, 1f / 60f); } public override void UpdateAabbs() { Vector3 colorvec = new Vector3(1, 0, 0); for (int i = 0; i < CollisionObjects.Count; i++) { CollisionObject colObj = CollisionObjects[i]; RigidBody body = RigidBody.Upcast(colObj); if (body != null) { // if (body->IsActive() && (!body->IsStatic())) { Vector3 minAabb, maxAabb; colObj.CollisionShape.GetAabb(colObj.WorldTransform, out minAabb, out maxAabb); OverlappingPairCache bp = BroadphasePairCache; //moving objects should be moderately sized, probably something wrong if not if (colObj.IsStaticObject || ((maxAabb - minAabb).LengthSquared() < 1e12f)) { bp.SetAabb(body.Broadphase, minAabb, maxAabb); } else { //something went wrong, investigate //this assert is unwanted in 3D modelers (danger of loosing work) BulletDebug.Assert(false); body.ActivationState = ActivationState.DisableSimulation; if (_reportMe) { _reportMe = false; Console.WriteLine("Overflow in AABB, object removed from simulation \n"); Console.WriteLine("If you can reproduce this, please email bugs@continuousphysics.com\n"); Console.WriteLine("Please include above information, your Platform, version of OS.\n"); Console.WriteLine("Thanks.\n"); } } if (_debugDrawer != null && (_debugDrawer.DebugMode & DebugDrawModes.DrawAabb) != 0) DrawAabb(_debugDrawer, minAabb, maxAabb, colorvec); } } } } public override void AddConstraint(TypedConstraint constraint) { _constraints.Add(constraint); } public override void RemoveConstraint(TypedConstraint constraint) { _constraints.Remove(constraint); } public void AddVehicle(RaycastVehicle vehicle) { _vehicles.Add(vehicle); } public void RemoveVehicle(RaycastVehicle vehicle) { _vehicles.Remove(vehicle); } public override void AddRigidBody(RigidBody body) { if (!body.IsStaticOrKinematicObject) { body.Gravity = _gravity; } if (body.CollisionShape != null) { bool isDynamic = !(body.IsStaticObject || body.IsKinematicObject); BroadphaseProxy.CollisionFilterGroups collisionFilterGroup = isDynamic ? BroadphaseProxy.CollisionFilterGroups.Default : BroadphaseProxy.CollisionFilterGroups.Static; BroadphaseProxy.CollisionFilterGroups collisionFilterMask = isDynamic ? BroadphaseProxy.CollisionFilterGroups.All : (BroadphaseProxy.CollisionFilterGroups.All ^ BroadphaseProxy.CollisionFilterGroups.Static); AddCollisionObject(body, collisionFilterGroup, collisionFilterMask); } } public override void RemoveRigidBody(RigidBody body) { RemoveCollisionObject(body); } public void DebugDrawObject(Matrix worldTransform, CollisionShape shape, Vector3 color) { if (shape.ShapeType == BroadphaseNativeTypes.Compound) { CompoundShape compoundShape = shape as CompoundShape; for (int i = compoundShape.ChildShapeCount - 1; i >= 0; i--) { Matrix childTrans = compoundShape.GetChildTransform(i); CollisionShape colShape = compoundShape.GetChildShape(i); DebugDrawObject(worldTransform * childTrans, colShape, color); } } else { switch (shape.ShapeType) { case BroadphaseNativeTypes.Sphere: { SphereShape sphereShape = shape as SphereShape; float radius = sphereShape.Margin;//radius doesn't include the margin, so draw with margin Vector3 start = worldTransform.Translation; DebugDrawer.DrawLine(start, start + Vector3.TransformNormal(new Vector3(radius, 0, 0), worldTransform), color); DebugDrawer.DrawLine(start, start + Vector3.TransformNormal(new Vector3(0, radius, 0), worldTransform), color); DebugDrawer.DrawLine(start, start + Vector3.TransformNormal(new Vector3(0, 0, radius), worldTransform), color); //drawSphere break; } case BroadphaseNativeTypes.MultiSphere: case BroadphaseNativeTypes.Cone: { ConeShape coneShape = shape as ConeShape; float radius = coneShape.Radius;//+coneShape->getMargin(); float height = coneShape.Height;//+coneShape->getMargin(); Vector3 start = worldTransform.Translation; DebugDrawer.DrawLine(start + Vector3.TransformNormal(new Vector3(0f, 0f, 0.5f * height), worldTransform), start + Vector3.TransformNormal(new Vector3(radius, 0f, -0.5f * height), worldTransform), color); DebugDrawer.DrawLine(start + Vector3.TransformNormal(new Vector3(0f, 0f, 0.5f * height), worldTransform), start + Vector3.TransformNormal(new Vector3(-radius, 0f, -0.5f * height), worldTransform), color); DebugDrawer.DrawLine(start + Vector3.TransformNormal(new Vector3(0f, 0f, 0.5f * height), worldTransform), start + Vector3.TransformNormal(new Vector3(0f, radius, -0.5f * height), worldTransform), color); DebugDrawer.DrawLine(start + Vector3.TransformNormal(new Vector3(0f, 0f, 0.5f * height), worldTransform), start + Vector3.TransformNormal(new Vector3(0f, -radius, -0.5f * height), worldTransform), color); break; } case BroadphaseNativeTypes.Cylinder: { CylinderShape cylinder = shape as CylinderShape; int upAxis = cylinder.UpAxis; float radius = cylinder.Radius; float halfHeight = MathHelper.GetElement(cylinder.HalfExtents, upAxis); Vector3 start = worldTransform.Translation; Vector3 offsetHeight = new Vector3(); MathHelper.SetElement(ref offsetHeight, upAxis, halfHeight); Vector3 offsetRadius = new Vector3(); MathHelper.SetElement(ref offsetRadius, (upAxis + 1) % 3, radius); DebugDrawer.DrawLine(start + Vector3.TransformNormal(offsetHeight + offsetRadius, worldTransform), start + Vector3.TransformNormal(-offsetHeight + offsetRadius, worldTransform), color); DebugDrawer.DrawLine(start + Vector3.TransformNormal(offsetHeight - offsetRadius, worldTransform), start + Vector3.TransformNormal(-offsetHeight - offsetRadius, worldTransform), color); break; } default: { if (shape.ShapeType == BroadphaseNativeTypes.TriangleMesh) { TriangleMeshShape concaveMesh = shape as TriangleMeshShape; //btVector3 aabbMax(1e30f,1e30f,1e30f); //btVector3 aabbMax(100,100,100);//1e30f,1e30f,1e30f); //todo pass camera, for some culling Vector3 aabbMax = new Vector3(1e30f, 1e30f, 1e30f); Vector3 aabbMin = new Vector3(-1e30f, -1e30f, -1e30f); DebugDrawCallback drawCallback = new DebugDrawCallback(DebugDrawer, worldTransform, color); concaveMesh.ProcessAllTriangles(drawCallback, aabbMin, aabbMax); } if (shape.ShapeType == BroadphaseNativeTypes.ConvexTriangleMesh) { ConvexTriangleMeshShape convexMesh = shape as ConvexTriangleMeshShape; //todo: pass camera for some culling Vector3 aabbMax = new Vector3(1e30f, 1e30f, 1e30f); Vector3 aabbMin = new Vector3(-1e30f, -1e30f, -1e30f); //DebugDrawcallback drawCallback; DebugDrawCallback drawCallback = new DebugDrawCallback(DebugDrawer, worldTransform, color); convexMesh.getStridingMesh().InternalProcessAllTriangles(drawCallback, aabbMin, aabbMax); } // for polyhedral shapes if (shape.IsPolyhedral) { PolyhedralConvexShape polyshape = shape as PolyhedralConvexShape; for (int i = 0; i < polyshape.EdgeCount; i++) { Vector3 a, b; polyshape.GetEdge(i, out a, out b); a = Vector3.TransformNormal(a, worldTransform); b = Vector3.TransformNormal(b, worldTransform); DebugDrawer.DrawLine(a, b, color); } } break; } } } } public override TypedConstraint GetConstraint(int index) { return _constraints[index]; } public static void DrawAabb(IDebugDraw debugDrawer, Vector3 from, Vector3 to, Vector3 color) { Vector3 halfExtents = (to - from) * 0.5f; Vector3 center = (to + from) * 0.5f; Vector3 edgecoord = new Vector3(1f, 1f, 1f), pa, pb; for (int i = 0; i < 4; i++) { for (int j = 0; j < 3; j++) { pa = new Vector3(edgecoord.X * halfExtents.X, edgecoord.Y * halfExtents.Y, edgecoord.Z * halfExtents.Z); pa += center; int othercoord = j % 3; MathHelper.SetElement(ref edgecoord, othercoord, MathHelper.GetElement(edgecoord, othercoord) * -1f); pb = new Vector3(edgecoord.X * halfExtents.X, edgecoord.Y * halfExtents.Y, edgecoord.Z * halfExtents.Z); pb += center; debugDrawer.DrawLine(pa, pb, color); } edgecoord = new Vector3(-1f, -1f, -1f); if (i < 3) MathHelper.SetElement(ref edgecoord, i, MathHelper.GetElement(edgecoord, i) * -1f); } } protected void PredictUnconstraintMotion(float timeStep) { for (int i = 0; i < CollisionObjects.Count; i++) { CollisionObject colObj = CollisionObjects[i]; RigidBody body = RigidBody.Upcast(colObj); if (body != null) { if (!body.IsStaticOrKinematicObject) { if (body.IsActive) { body.ApplyForces(timeStep); body.IntegrateVelocities(timeStep); Matrix temp = body.InterpolationWorldTransform; body.PredictIntegratedTransform(timeStep, ref temp); body.InterpolationWorldTransform = temp; } } } } } protected void IntegrateTransforms(float timeStep) { Matrix predictedTrans = new Matrix(); for (int i = 0; i < CollisionObjects.Count; i++) { CollisionObject colObj = CollisionObjects[i]; RigidBody body = RigidBody.Upcast(colObj); if (body != null) { if (body.IsActive && (!body.IsStaticOrKinematicObject)) { body.PredictIntegratedTransform(timeStep, ref predictedTrans); body.ProceedToTransform(predictedTrans); } } } } protected void CalculateSimulationIslands() { SimulationIslandManager.UpdateActivationState(this, Dispatcher); for (int i = 0; i < _constraints.Count; i++) { TypedConstraint constraint = _constraints[i]; RigidBody colObj0 = constraint.RigidBodyA; RigidBody colObj1 = constraint.RigidBodyB; if (((colObj0 != null) && (colObj0.MergesSimulationIslands)) && ((colObj1 != null) && (colObj1.MergesSimulationIslands))) { if (colObj0.IsActive || colObj1.IsActive) { SimulationIslandManager.UnionFind.Unite((colObj0).IslandTag, (colObj1).IslandTag); } } } //Store the island id in each body SimulationIslandManager.StoreIslandActivationState(this); } //protected void SolveNonContactConstraints(ContactSolverInfo solverInfo) //{ // //constraint preparation: building jacobians // for (int i = 0; i < _constraints.Count; i++) // { // TypedConstraint constraint = _constraints[i]; // constraint.BuildJacobian(); // } // //solve the regular non-contact constraints (point 2 point, hinge, generic d6) // for (int g = 0; g < solverInfo.IterationsCount; g++) // { // for (int i = 0; i < _constraints.Count; i++) // { // TypedConstraint constraint = _constraints[i]; // constraint.SolveConstraint(solverInfo.TimeStep); // } // } //} //protected void SolveContactConstraints(ContactSolverInfo solverInfo) //{ // InplaceSolverIslandCallback solverCallback = new InplaceSolverIslandCallback(solverInfo, _constraintSolver, _debugDrawer); // // solve all the contact points and contact friction // _islandManager.BuildAndProcessIslands(Dispatcher, CollisionObjects, solverCallback); //} protected void SolveConstraints(ContactSolverInfo solverInfo) { //sorted version of all btTypedConstraint, based on islandId List<TypedConstraint> sortedConstraints = new List<TypedConstraint>(ConstraintsCount); for (int i = 0; i < ConstraintsCount; i++) { sortedConstraints.Add(_constraints[i]); } sortedConstraints.Sort(new Comparison<TypedConstraint>(TypedConstraint.SortConstraintOnIslandPredicate)); List<TypedConstraint> constraintsPtr = ConstraintsCount != 0 ? sortedConstraints : new List<TypedConstraint>(); InplaceSolverIslandCallback solverCallback = new InplaceSolverIslandCallback(solverInfo, _constraintSolver, constraintsPtr, _debugDrawer); // solve all the constraints for this island _islandManager.BuildAndProcessIslands(CollisionWorld.Dispatcher, CollisionWorld.CollisionObjects, solverCallback); } protected void UpdateActivationState(float timeStep) { for (int i = 0; i < CollisionObjects.Count; i++) { CollisionObject colObj = CollisionObjects[i]; RigidBody body = RigidBody.Upcast(colObj); if (body != null) { body.UpdateDeactivation(timeStep); if (body.WantsSleeping()) { if (body.IsStaticOrKinematicObject) { body.ActivationState = ActivationState.IslandSleeping; } else { if (body.ActivationState == ActivationState.Active) body.ActivationState = ActivationState.WantsDeactivation; } } else { if (body.ActivationState != ActivationState.DisableDeactivation) body.ActivationState = ActivationState.Active; } } } } protected void UpdateVehicles(float timeStep) { for (int i = 0; i < _vehicles.Count; i++) { RaycastVehicle vehicle = _vehicles[i]; vehicle.updateVehicle(timeStep); } } protected void StartProfiling(float timeStep) { } protected virtual void InternalSingleStepSimulation(float timeStep) { StartProfiling(timeStep); //update aabbs information UpdateAabbs(); //apply gravity, predict motion PredictUnconstraintMotion(timeStep); DispatcherInfo dispatchInfo = DispatchInfo; dispatchInfo.TimeStep = timeStep; dispatchInfo.StepCount = 0; dispatchInfo.DebugDraw = DebugDrawer; //perform collision detection PerformDiscreteCollisionDetection(); CalculateSimulationIslands(); SolverInfo.TimeStep = timeStep; //solve contact and other joint constraints SolveConstraints(SolverInfo); //CallbackTriggers(); //integrate transforms IntegrateTransforms(timeStep); //update vehicle simulation UpdateVehicles(timeStep); UpdateActivationState(timeStep); } protected void SynchronizeMotionStates() { //debug vehicle wheels { //todo: iterate over awake simulation islands! for (int i = 0; i < CollisionObjects.Count; i++) { CollisionObject colObj = CollisionObjects[i]; if (DebugDrawer != null && (DebugDrawer.DebugMode & DebugDrawModes.DrawWireframe) != 0) { Vector3 color = new Vector3(255f, 255f, 255f); switch (colObj.ActivationState) { case ActivationState.Active: color = new Vector3(255f, 255f, 255f); break; case ActivationState.IslandSleeping: color = new Vector3(0f, 255f, 0f); break; case ActivationState.WantsDeactivation: color = new Vector3(0f, 255f, 255f); break; case ActivationState.DisableDeactivation: color = new Vector3(255f, 0f, 0f); break; case ActivationState.DisableSimulation: color = new Vector3(255f, 255f, 0f); break; default: color = new Vector3(255f, 0f, 0f); break; } DebugDrawObject(colObj.WorldTransform, colObj.CollisionShape, color); } RigidBody body = RigidBody.Upcast(colObj); if (body != null && body.MotionState != null && !body.IsStaticOrKinematicObject) { //if (body.ActivationState != ActivationState.IslandSleeping) { Matrix interpolatedTransform = new Matrix(); TransformUtil.IntegrateTransform(body.InterpolationWorldTransform, body.InterpolationLinearVelocity, body.InterpolationAngularVelocity, _localTime, ref interpolatedTransform); body.MotionState.SetWorldTransform(interpolatedTransform); } } } } if (DebugDrawer != null && (DebugDrawer.DebugMode & DebugDrawModes.DrawWireframe) != 0) { for (int i = 0; i < _vehicles.Count; i++) { for (int v = 0; v < _vehicles[i].getNumWheels(); v++) { Vector3 wheelColor = new Vector3(0, 255, 255); if (_vehicles[i].getWheelInfo(v).RaycastInfo.IsInContact) { wheelColor = new Vector3(0, 0, 255); } else { wheelColor = new Vector3(255, 0, 255); } //synchronize the wheels with the (interpolated) chassis worldtransform _vehicles[i].updateWheelTransform(v, true); Vector3 wheelPosWS = _vehicles[i].getWheelInfo(v).WorldTransform.Translation; Vector3 axle = new Vector3( MathHelper.GetElement(_vehicles[i].getWheelInfo(v).WorldTransform, 0, _vehicles[i].getRightAxis()), MathHelper.GetElement(_vehicles[i].getWheelInfo(v).WorldTransform, 1, _vehicles[i].getRightAxis()), MathHelper.GetElement(_vehicles[i].getWheelInfo(v).WorldTransform, 2, _vehicles[i].getRightAxis())); //m_vehicles[i]->getWheelInfo(v).m_raycastInfo.m_wheelAxleWS //debug wheels (cylinders) _debugDrawer.DrawLine(wheelPosWS, wheelPosWS + axle, wheelColor); _debugDrawer.DrawLine(wheelPosWS, _vehicles[i].getWheelInfo(v).RaycastInfo.ContactPointWS, wheelColor); } } } } protected void SaveKinematicState(float timeStep) { for (int i = 0; i < CollisionObjects.Count; i++) { CollisionObject colObj = CollisionObjects[i]; RigidBody body = RigidBody.Upcast(colObj); if (body != null) { if (body.ActivationState != ActivationState.IslandSleeping) { if (body.IsKinematicObject) { //to calculate velocities next frame body.SaveKinematicState(timeStep); } } } } } internal class InplaceSolverIslandCallback : SimulationIslandManager.IIslandCallback { private ContactSolverInfo _solverInfo; private IConstraintSolver _solver; private IDebugDraw _debugDrawer; private List<TypedConstraint> _sortedConstraints; public InplaceSolverIslandCallback( ContactSolverInfo solverInfo, IConstraintSolver solver, List<TypedConstraint> sortedConstraints, IDebugDraw debugDrawer) { _solverInfo = solverInfo; _solver = solver; _sortedConstraints = sortedConstraints; _debugDrawer = debugDrawer; } public ContactSolverInfo SolverInfo { get { return _solverInfo; } set { _solverInfo = value; } } public IConstraintSolver Solver { get { return _solver; } set { _solver = value; } } public List<TypedConstraint> Constraints { get { return _sortedConstraints; } set { _sortedConstraints = value; } } public IDebugDraw DebugDrawer { get { return _debugDrawer; } set { _debugDrawer = value; } } public void ProcessIsland(List<CollisionObject> bodies, List<PersistentManifold> manifolds, int numManifolds, int islandID) { //also add all non-contact constraints/joints for this island List<TypedConstraint> startConstraint = new List<TypedConstraint>(); int numCurConstraints = 0; int startIndex = 0; int i; //find the first constraint for this island for (i = 0; i < _sortedConstraints.Count; i++) { if (TypedConstraint.GetConstraintIslandId(_sortedConstraints[i]) == islandID) { //startConstraint = &m_sortedConstraints[i]; startIndex = i; break; } } //count the number of constraints in this island for (; i < _sortedConstraints.Count; i++) { if (TypedConstraint.GetConstraintIslandId(_sortedConstraints[i]) == islandID) { numCurConstraints++; } } for (i = startIndex; i < startIndex + numCurConstraints; i++) { startConstraint.Add(_sortedConstraints[i]); } _solver.SolveGroup(bodies, manifolds, numManifolds, startConstraint, _solverInfo, _debugDrawer); } } } internal class DebugDrawCallback : ITriangleIndexCallback, ITriangleCallback { private IDebugDraw _debugDrawer; private Vector3 _color; private Matrix _worldTrans; public DebugDrawCallback(IDebugDraw debugDrawer, Matrix worldTrans, Vector3 color) { _debugDrawer = debugDrawer; _worldTrans = worldTrans; _color = color; } public void ProcessTriangleIndex(Vector3[] triangle, int partId, int triangleIndex) { ProcessTriangle(triangle, partId, triangleIndex); } #region ITriangleCallback Members public void ProcessTriangle(Vector3[] triangle, int partID, int triangleIndex) { Vector3 wv0, wv1, wv2; wv0 = Vector3.TransformNormal(triangle[0], _worldTrans); wv1 = Vector3.TransformNormal(triangle[1], _worldTrans); wv2 = Vector3.TransformNormal(triangle[2], _worldTrans); _debugDrawer.DrawLine(wv0, wv1, _color); _debugDrawer.DrawLine(wv1, wv2, _color); _debugDrawer.DrawLine(wv2, wv0, _color); } #endregion } }
namespace AbpCompanyName.AbpProjectName.Migrations { using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.Migrations; public partial class AbpZero_Initial : DbMigration { public override void Up() { CreateTable( "dbo.AbpAuditLogs", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), ServiceName = c.String(maxLength: 256), MethodName = c.String(maxLength: 256), Parameters = c.String(maxLength: 1024), ExecutionTime = c.DateTime(nullable: false), ExecutionDuration = c.Int(nullable: false), ClientIpAddress = c.String(maxLength: 64), ClientName = c.String(maxLength: 128), BrowserInfo = c.String(maxLength: 256), Exception = c.String(maxLength: 2000), }, annotations: new Dictionary<string, object> { { "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpPermissions", c => new { Id = c.Long(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 128), IsGranted = c.Boolean(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), RoleId = c.Int(), UserId = c.Long(), Discriminator = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.AbpRoles", t => t.RoleId, cascadeDelete: true) .Index(t => t.RoleId) .Index(t => t.UserId); CreateTable( "dbo.AbpRoles", c => new { Id = c.Int(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 32), DisplayName = c.String(nullable: false, maxLength: 64), IsStatic = c.Boolean(nullable: false), IsDefault = c.Boolean(nullable: false), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .ForeignKey("dbo.AbpTenants", t => t.TenantId) .Index(t => t.TenantId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUsers", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), AuthenticationSource = c.String(maxLength: 64), Name = c.String(nullable: false, maxLength: 32), Surname = c.String(nullable: false, maxLength: 32), UserName = c.String(nullable: false, maxLength: 32), Password = c.String(nullable: false, maxLength: 128), EmailAddress = c.String(nullable: false, maxLength: 256), IsEmailConfirmed = c.Boolean(nullable: false), EmailConfirmationCode = c.String(maxLength: 128), PasswordResetCode = c.String(maxLength: 128), LastLoginTime = c.DateTime(), IsActive = c.Boolean(nullable: false), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .ForeignKey("dbo.AbpTenants", t => t.TenantId) .Index(t => t.TenantId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUserLogins", c => new { Id = c.Long(nullable: false, identity: true), UserId = c.Long(nullable: false), LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpUserRoles", c => new { Id = c.Long(nullable: false, identity: true), UserId = c.Long(nullable: false), RoleId = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpSettings", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), Name = c.String(nullable: false, maxLength: 256), Value = c.String(maxLength: 2000), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId) .ForeignKey("dbo.AbpTenants", t => t.TenantId) .Index(t => t.TenantId) .Index(t => t.UserId); CreateTable( "dbo.AbpTenants", c => new { Id = c.Int(nullable: false, identity: true), TenancyName = c.String(nullable: false, maxLength: 64), Name = c.String(nullable: false, maxLength: 128), IsActive = c.Boolean(nullable: false), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); } public override void Down() { DropForeignKey("dbo.AbpRoles", "TenantId", "dbo.AbpTenants"); DropForeignKey("dbo.AbpPermissions", "RoleId", "dbo.AbpRoles"); DropForeignKey("dbo.AbpRoles", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpRoles", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpRoles", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "TenantId", "dbo.AbpTenants"); DropForeignKey("dbo.AbpSettings", "TenantId", "dbo.AbpTenants"); DropForeignKey("dbo.AbpTenants", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpTenants", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpTenants", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpSettings", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserRoles", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpPermissions", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserLogins", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "CreatorUserId", "dbo.AbpUsers"); DropIndex("dbo.AbpTenants", new[] { "CreatorUserId" }); DropIndex("dbo.AbpTenants", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpTenants", new[] { "DeleterUserId" }); DropIndex("dbo.AbpSettings", new[] { "UserId" }); DropIndex("dbo.AbpSettings", new[] { "TenantId" }); DropIndex("dbo.AbpUserRoles", new[] { "UserId" }); DropIndex("dbo.AbpUserLogins", new[] { "UserId" }); DropIndex("dbo.AbpUsers", new[] { "CreatorUserId" }); DropIndex("dbo.AbpUsers", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpUsers", new[] { "DeleterUserId" }); DropIndex("dbo.AbpUsers", new[] { "TenantId" }); DropIndex("dbo.AbpRoles", new[] { "CreatorUserId" }); DropIndex("dbo.AbpRoles", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpRoles", new[] { "DeleterUserId" }); DropIndex("dbo.AbpRoles", new[] { "TenantId" }); DropIndex("dbo.AbpPermissions", new[] { "UserId" }); DropIndex("dbo.AbpPermissions", new[] { "RoleId" }); DropTable("dbo.AbpTenants", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpSettings"); DropTable("dbo.AbpUserRoles"); DropTable("dbo.AbpUserLogins"); DropTable("dbo.AbpUsers", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpRoles", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpPermissions"); DropTable("dbo.AbpAuditLogs", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); } } }
#region License // // Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com> // Copyright (c) 2010, Nathan Brown // // 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.Collections.Generic; using System.Data; using System.Linq; using FluentMigrator.Builders.Execute; using FluentMigrator.Model; using FluentMigrator.Runner; using FluentMigrator.Runner.Processors.SqlServer; namespace FluentMigrator.SchemaDump.SchemaDumpers { public class SqlServerSchemaDumper : ISchemaDumper { public virtual IAnnouncer Announcer { get; set; } public SqlServerProcessor Processor { get; set; } public SqlServerSchemaDumper(SqlServerProcessor processor, IAnnouncer announcer) { Announcer = announcer; Processor = processor; } public virtual void Execute(string template, params object[] args) { Processor.Execute(template, args); } public virtual bool Exists(string template, params object[] args) { return Processor.Exists(template, args); } public virtual DataSet ReadTableData(string tableName) { return Processor.Read("SELECT * FROM [{0}]", tableName); } public virtual DataSet Read(string template, params object[] args) { return Processor.Read(template, args); } public virtual void Process(PerformDBOperationExpression expression) { Processor.Process(expression); } public virtual IList<TableDefinition> ReadDbSchema() { IList<TableDefinition> tables = ReadTables(); foreach (TableDefinition table in tables) { table.Indexes = ReadIndexes(table.SchemaName, table.Name); table.ForeignKeys = ReadForeignKeys(table.SchemaName, table.Name); } return tables; } protected virtual IList<TableDefinition> ReadTables() { const string query = @"SELECT OBJECT_SCHEMA_NAME(t.[object_id],DB_ID()) AS [Schema], t.name AS [Table], c.[Name] AS ColumnName, t.object_id AS [TableID], c.column_id AS [ColumnID], def.definition AS [DefaultValue], c.[system_type_id] AS [TypeID], c.[user_type_id] AS [UserTypeID], c.[max_length] AS [Length], c.[precision] AS [Precision], c.[scale] AS [Scale], c.[is_identity] AS [IsIdentity], c.[is_nullable] AS [IsNullable], CASE WHEN EXISTS(SELECT 1 FROM sys.foreign_key_columns fkc WHERE t.object_id = fkc.parent_object_id AND c.column_id = fkc.parent_column_id) THEN 1 ELSE 0 END AS IsForeignKey, CASE WHEN EXISTS(select 1 from sys.index_columns ic WHERE t.object_id = ic.object_id AND c.column_id = ic.column_id) THEN 1 ELSE 0 END AS IsIndexed ,CASE WHEN kcu.CONSTRAINT_NAME IS NOT NULL THEN 1 ELSE 0 END AS IsPrimaryKey , CASE WHEN EXISTS(select stc.CONSTRAINT_NAME, skcu.TABLE_NAME, skcu.COLUMN_NAME from INFORMATION_SCHEMA.TABLE_CONSTRAINTS stc JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE skcu ON skcu.CONSTRAINT_NAME = stc.CONSTRAINT_NAME WHERE stc.CONSTRAINT_TYPE = 'UNIQUE' AND skcu.TABLE_NAME = t.name AND skcu.COLUMN_NAME = c.name) THEN 1 ELSE 0 END AS IsUnique ,pk.name AS PrimaryKeyName FROM sys.all_columns c JOIN sys.tables t ON c.object_id = t.object_id AND t.type = 'u' LEFT JOIN sys.default_constraints def ON c.default_object_id = def.object_id LEFT JOIN sys.key_constraints pk ON t.object_id = pk.parent_object_id AND pk.type = 'PK' LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu ON t.name = kcu.TABLE_NAME AND c.name = kcu.COLUMN_NAME AND pk.name = kcu.CONSTRAINT_NAME ORDER BY t.name, c.name"; DataSet ds = Read(query); DataTable dt = ds.Tables[0]; IList<TableDefinition> tables = new List<TableDefinition>(); foreach (DataRow dr in dt.Rows) { List<TableDefinition> matches = (from t in tables where t.Name == dr["Table"].ToString() && t.SchemaName == dr["Schema"].ToString() select t).ToList(); TableDefinition tableDef = null; if (matches.Count > 0) tableDef = matches[0]; // create the table if not found if (tableDef == null) { tableDef = new TableDefinition { Name = dr["Table"].ToString(), SchemaName = dr["Schema"].ToString() }; tables.Add(tableDef); } //find the column List<ColumnDefinition> cmatches = (from c in tableDef.Columns where c.Name == dr["ColumnName"].ToString() select c).ToList(); ColumnDefinition colDef = null; if (cmatches.Count > 0) colDef = cmatches[0]; if (colDef == null) { //need to create and add the column tableDef.Columns.Add(new ColumnDefinition { Name = dr["ColumnName"].ToString(), CustomType = "", //TODO: set this property DefaultValue = dr.IsNull("DefaultValue") ? "" : dr["DefaultValue"].ToString(), IsForeignKey = dr["IsForeignKey"].ToString() == "1", IsIdentity = dr["IsIdentity"].ToString() == "True", IsIndexed = dr["IsIndexed"].ToString() == "1", IsNullable = dr["IsNullable"].ToString() == "True", IsPrimaryKey = dr["IsPrimaryKey"].ToString() == "1", IsUnique = dr["IsUnique"].ToString() == "1", Precision = int.Parse(dr["Precision"].ToString()), PrimaryKeyName = dr.IsNull("PrimaryKeyName") ? "" : dr["PrimaryKeyName"].ToString(), Size = int.Parse(dr["Length"].ToString()), TableName = dr["Table"].ToString(), Type = GetDbType(int.Parse(dr["TypeID"].ToString())), //TODO: set this property ModificationType = ColumnModificationType.Create }); } } return tables; } protected virtual DbType GetDbType(int typeNum) { switch (typeNum) { case 34: //'byte[]' return DbType.Byte; case 35: //'string' return DbType.String; case 36: //'System.Guid' return DbType.Guid; case 48: //'byte' return DbType.Byte; case 52: //'short' return DbType.Int16; case 56: //'int' return DbType.Int32; case 58: //'System.DateTime' return DbType.DateTime; case 59: //'float' return DbType.Int64; case 60: //'decimal' return DbType.Decimal; case 61: //'System.DateTime' return DbType.DateTime; case 62: //'double' return DbType.Double; case 98: //'object' return DbType.Object; case 99: //'string' return DbType.String; case 104: //'bool' return DbType.Boolean; case 106: //'decimal' return DbType.Decimal; case 108: //'decimal' return DbType.Decimal; case 122: //'decimal' return DbType.Decimal; case 127: //'long' return DbType.Int64; case 165: //'byte[]' return DbType.Byte; case 167: //'string' return DbType.String; case 173: //'byte[]' return DbType.Byte; case 175: //'string' return DbType.String; case 189: //'long' return DbType.Int64; case 231: //'string' case 239: //'string' case 241: //'string' default: return DbType.String; } } protected virtual IList<IndexDefinition> ReadIndexes(string schemaName, string tableName) { const string query = @"SELECT OBJECT_SCHEMA_NAME(T.[object_id],DB_ID()) AS [Schema], T.[name] AS [table_name], I.[name] AS [index_name], AC.[name] AS [column_name], I.[type_desc], I.[is_unique], I.[data_space_id], I.[ignore_dup_key], I.[is_primary_key], I.[is_unique_constraint], I.[fill_factor], I.[is_padded], I.[is_disabled], I.[is_hypothetical], I.[allow_row_locks], I.[allow_page_locks], IC.[is_descending_key], IC.[is_included_column] FROM sys.[tables] AS T INNER JOIN sys.[indexes] I ON T.[object_id] = I.[object_id] INNER JOIN sys.[index_columns] IC ON I.[object_id] = IC.[object_id] INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id] AND IC.[column_id] = AC.[column_id] WHERE T.[is_ms_shipped] = 0 AND I.[type_desc] <> 'HEAP' AND T.object_id = OBJECT_ID('[{0}].[{1}]') ORDER BY T.[name], I.[index_id], IC.[key_ordinal]"; DataSet ds = Read(query, schemaName, tableName); DataTable dt = ds.Tables[0]; IList<IndexDefinition> indexes = new List<IndexDefinition>(); foreach (DataRow dr in dt.Rows) { List<IndexDefinition> matches = (from i in indexes where i.Name == dr["index_name"].ToString() && i.SchemaName == dr["Schema"].ToString() select i).ToList(); IndexDefinition iDef = null; if (matches.Count > 0) iDef = matches[0]; // create the table if not found if (iDef == null) { iDef = new IndexDefinition { Name = dr["index_name"].ToString(), SchemaName = dr["Schema"].ToString(), IsClustered = dr["type_desc"].ToString() == "CLUSTERED", IsUnique = dr["is_unique"].ToString() == "1", TableName = dr["table_name"].ToString() }; indexes.Add(iDef); } // columns ICollection<IndexColumnDefinition> ms = (from m in iDef.Columns where m.Name == dr["column_name"].ToString() select m).ToList(); if (ms.Count == 0) { iDef.Columns.Add(new IndexColumnDefinition { Name = dr["column_name"].ToString(), Direction = dr["is_descending_key"].ToString() == "1" ? Direction.Descending : Direction.Ascending }); } } return indexes; } protected virtual IList<ForeignKeyDefinition> ReadForeignKeys(string schemaName, string tableName) { const string query = @"SELECT C.CONSTRAINT_SCHEMA AS Contraint_Schema, C.CONSTRAINT_NAME AS Constraint_Name, FK.CONSTRAINT_SCHEMA AS ForeignTableSchema, FK.TABLE_NAME AS FK_Table, CU.COLUMN_NAME AS FK_Column, PK.CONSTRAINT_SCHEMA as PrimaryTableSchema, PK.TABLE_NAME AS PK_Table, PT.COLUMN_NAME AS PK_Column FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME INNER JOIN ( SELECT i1.TABLE_NAME, i2.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY' ) PT ON PT.TABLE_NAME = PK.TABLE_NAME WHERE PK.TABLE_NAME = '{1}' AND PK.CONSTRAINT_SCHEMA = '{0}' ORDER BY Constraint_Name"; DataSet ds = Read(query, schemaName, tableName); DataTable dt = ds.Tables[0]; IList<ForeignKeyDefinition> keys = new List<ForeignKeyDefinition>(); foreach (DataRow dr in dt.Rows) { List<ForeignKeyDefinition> matches = (from i in keys where i.Name == dr["Constraint_Name"].ToString() select i).ToList(); ForeignKeyDefinition d = null; if (matches.Count > 0) d = matches[0]; // create the table if not found if (d == null) { d = new ForeignKeyDefinition { Name = dr["Constraint_Name"].ToString(), ForeignTableSchema = dr["ForeignTableSchema"].ToString(), ForeignTable = dr["FK_Table"].ToString(), PrimaryTable = dr["PK_Table"].ToString(), PrimaryTableSchema = dr["PrimaryTableSchema"].ToString() }; keys.Add(d); } // Foreign Columns ICollection<string> ms = (from m in d.ForeignColumns where m == dr["FK_Table"].ToString() select m).ToList(); if (ms.Count == 0) d.ForeignColumns.Add(dr["FK_Table"].ToString()); // Primary Columns ms = (from m in d.PrimaryColumns where m == dr["PK_Table"].ToString() select m).ToList(); if (ms.Count == 0) d.PrimaryColumns.Add(dr["PK_Table"].ToString()); } return keys; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Net.NetworkInformation; using System.Text; // Relevant cookie specs: // // PERSISTENT CLIENT STATE HTTP COOKIES (1996) // From <http:// web.archive.org/web/20020803110822/http://wp.netscape.com/newsref/std/cookie_spec.html> // // RFC2109 HTTP State Management Mechanism (February 1997) // From <http:// tools.ietf.org/html/rfc2109> // // RFC2965 HTTP State Management Mechanism (October 2000) // From <http:// tools.ietf.org/html/rfc2965> // // RFC6265 HTTP State Management Mechanism (April 2011) // From <http:// tools.ietf.org/html/rfc6265> // // The Version attribute of the cookie header is defined and used only in RFC2109 and RFC2965 cookie // specs and specifies Version=1. The Version attribute is not used in the Netscape cookie spec // (considered as Version=0). Nor is it used in the most recent cookie spec, RFC6265, introduced in 2011. // RFC6265 deprecates all previous cookie specs including the Version attribute. // // Cookies without an explicit Domain attribute will only match a potential uri that matches the original // uri from where the cookie came from. // // For explicit Domain attribute in the cookie, the following rules apply: // // Version=0 (Netscape, RFC6265) allows the Domain attribute of the cookie to match any tail substring // of the host uri. // // Version=1 related cookie specs only allows the Domain attribute to match the host uri based on a // more restricted set of rules. // // According to RFC2109/RFC2965, the cookie will be rejected for matching if: // * The value for the Domain attribute contains no embedded dots or does not start with a dot. // * The value for the request-host does not domain-match the Domain attribute. // " The request-host is a FQDN (not IP address) and has the form HD, where D is the value of the Domain // attribute, and H is a string that contains one or more dots. // // Examples: // * A cookie from request-host y.x.foo.com for Domain=.foo.com would be rejected, because H is y.x // and contains a dot. // // * A cookie from request-host x.foo.com for Domain=.foo.com would be accepted. // // * A cookie with Domain=.com or Domain=.com., will always be rejected, because there is no embedded dot. // // * A cookie with Domain=ajax.com will be rejected because the value for Domain does not begin with a dot. namespace System.Net { internal struct HeaderVariantInfo { private readonly string _name; private readonly CookieVariant _variant; internal HeaderVariantInfo(string name, CookieVariant variant) { _name = name; _variant = variant; } internal string Name { get { return _name; } } internal CookieVariant Variant { get { return _variant; } } } // CookieContainer // // Manage cookies for a user (implicit). Based on RFC 2965. public class CookieContainer { public const int DefaultCookieLimit = 300; public const int DefaultPerDomainCookieLimit = 20; public const int DefaultCookieLengthLimit = 4096; private static readonly HeaderVariantInfo[] s_headerInfo = { new HeaderVariantInfo(HttpKnownHeaderNames.SetCookie, CookieVariant.Rfc2109), new HeaderVariantInfo(HttpKnownHeaderNames.SetCookie2, CookieVariant.Rfc2965) }; // NOTE: all accesses of _domainTable must be performed with _domainTable locked. private Dictionary<string, PathList> _domainTable = new Dictionary<string, PathList>(); private int _maxCookieSize = DefaultCookieLengthLimit; private int _maxCookies = DefaultCookieLimit; private int _maxCookiesPerDomain = DefaultPerDomainCookieLimit; private int _count = 0; private string _fqdnMyDomain = string.Empty; public CookieContainer() { string domain = HostInformation.DomainName; if (domain != null && domain.Length > 1) { _fqdnMyDomain = '.' + domain; } // Otherwise it will remain string.Empty. } public CookieContainer(int capacity) : this() { if (capacity <= 0) { throw new ArgumentException(SR.net_toosmall, "Capacity"); } _maxCookies = capacity; } public CookieContainer(int capacity, int perDomainCapacity, int maxCookieSize) : this(capacity) { if (perDomainCapacity != Int32.MaxValue && (perDomainCapacity <= 0 || perDomainCapacity > capacity)) { throw new ArgumentOutOfRangeException(nameof(perDomainCapacity), SR.Format(SR.net_cookie_capacity_range, "PerDomainCapacity", 0, capacity)); } _maxCookiesPerDomain = perDomainCapacity; if (maxCookieSize <= 0) { throw new ArgumentException(SR.net_toosmall, "MaxCookieSize"); } _maxCookieSize = maxCookieSize; } // NOTE: after shrinking the capacity, Count can become greater than Capacity. public int Capacity { get { return _maxCookies; } set { if (value <= 0 || (value < _maxCookiesPerDomain && _maxCookiesPerDomain != Int32.MaxValue)) { throw new ArgumentOutOfRangeException(nameof(value), SR.Format(SR.net_cookie_capacity_range, "Capacity", 0, _maxCookiesPerDomain)); } if (value < _maxCookies) { _maxCookies = value; AgeCookies(null); } _maxCookies = value; } } /// <devdoc> /// <para>Returns the total number of cookies in the container.</para> /// </devdoc> public int Count { get { return _count; } } public int MaxCookieSize { get { return _maxCookieSize; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value)); } _maxCookieSize = value; } } /// <devdoc> /// <para>After shrinking domain capacity, each domain will less hold than new domain capacity.</para> /// </devdoc> public int PerDomainCapacity { get { return _maxCookiesPerDomain; } set { if (value <= 0 || (value > _maxCookies && value != Int32.MaxValue)) { throw new ArgumentOutOfRangeException(nameof(value)); } if (value < _maxCookiesPerDomain) { _maxCookiesPerDomain = value; AgeCookies(null); } _maxCookiesPerDomain = value; } } // This method will construct a faked URI: the Domain property is required for param. public void Add(Cookie cookie) { if (cookie == null) { throw new ArgumentNullException(nameof(cookie)); } if (cookie.Domain.Length == 0) { throw new ArgumentException(SR.net_emptystringcall, "cookie.Domain"); } Uri uri; var uriSb = new StringBuilder(); // We cannot add an invalid cookie into the container. // Trying to prepare Uri for the cookie verification. uriSb.Append(cookie.Secure ? UriScheme.Https : UriScheme.Http).Append(UriScheme.SchemeDelimiter); // If the original cookie has an explicitly set domain, copy it over to the new cookie. if (!cookie.DomainImplicit) { if (cookie.Domain[0] == '.') { uriSb.Append("0"); // URI cctor should consume this faked host. } } uriSb.Append(cookie.Domain); // Either keep Port as implicit or set it according to original cookie. if (cookie.PortList != null) { uriSb.Append(":").Append(cookie.PortList[0]); } // Path must be present, set to root by default. uriSb.Append(cookie.Path); if (!Uri.TryCreate(uriSb.ToString(), UriKind.Absolute, out uri)) throw new CookieException(SR.Format(SR.net_cookie_attribute, "Domain", cookie.Domain)); // We don't know cookie verification status, so re-create the cookie and verify it. Cookie new_cookie = cookie.Clone(); new_cookie.VerifySetDefaults(new_cookie.Variant, uri, IsLocalDomain(uri.Host), _fqdnMyDomain, true, true); Add(new_cookie, true); } private void AddRemoveDomain(string key, PathList value) { lock (_domainTable) { if (value == null) { _domainTable.Remove(key); } else { _domainTable[key] = value; } } } // This method is called *only* when cookie verification is done, so unlike with public // Add(Cookie cookie) the cookie is in a reasonable condition. internal void Add(Cookie cookie, bool throwOnError) { PathList pathList; if (cookie.Value.Length > _maxCookieSize) { if (throwOnError) { throw new CookieException(SR.Format(SR.net_cookie_size, cookie.ToString(), _maxCookieSize)); } return; } try { lock (_domainTable) { _domainTable.TryGetValue(cookie.DomainKey, out pathList); if (pathList == null) { pathList = new PathList(); AddRemoveDomain(cookie.DomainKey, pathList); } } int domain_count = pathList.GetCookiesCount(); CookieCollection cookies; lock (pathList.SyncRoot) { cookies = pathList[cookie.Path]; if (cookies == null) { cookies = new CookieCollection(); pathList[cookie.Path] = cookies; } } if (cookie.Expired) { // Explicit removal command (Max-Age == 0) lock (cookies) { int idx = cookies.IndexOf(cookie); if (idx != -1) { cookies.RemoveAt(idx); --_count; } } } else { // This is about real cookie adding, check Capacity first if (domain_count >= _maxCookiesPerDomain && !AgeCookies(cookie.DomainKey)) { return; // Cannot age: reject new cookie } else if (_count >= _maxCookies && !AgeCookies(null)) { return; // Cannot age: reject new cookie } // About to change the collection lock (cookies) { _count += cookies.InternalAdd(cookie, true); } } } catch (OutOfMemoryException) { throw; } catch (Exception e) { if (throwOnError) { throw new CookieException(SR.net_container_add_cookie, e); } } } // This function, when called, must delete at least one cookie. // If there are expired cookies in given scope they are cleaned up. // If nothing is found the least used Collection will be found and removed // from the container. // // Also note that expired cookies are also removed during request preparation // (this.GetCookies method). // // Param. 'domain' == null means to age in the whole container. private bool AgeCookies(string domain) { // Border case: shrunk to zero if (_maxCookies == 0 || _maxCookiesPerDomain == 0) { _domainTable = new Dictionary<string, PathList>(); _count = 0; return false; } int removed = 0; DateTime oldUsed = DateTime.MaxValue; DateTime tempUsed; CookieCollection lruCc = null; string lruDomain = null; string tempDomain = null; PathList pathList; int domain_count = 0; int itemp = 0; float remainingFraction = 1.0F; // The container was shrunk, might need additional cleanup for each domain if (_count > _maxCookies) { // Means the fraction of the container to be left. // Each domain will be cut accordingly. remainingFraction = (float)_maxCookies / (float)_count; } lock (_domainTable) { foreach (KeyValuePair<string, PathList> entry in _domainTable) { if (domain == null) { tempDomain = entry.Key; pathList = entry.Value; // Aliasing to trick foreach } else { tempDomain = domain; _domainTable.TryGetValue(domain, out pathList); } domain_count = 0; // Cookies in the domain lock (pathList.SyncRoot) { foreach (KeyValuePair<string, CookieCollection> pair in pathList) { CookieCollection cc = pair.Value; itemp = ExpireCollection(cc); removed += itemp; _count -= itemp; // Update this container's count domain_count += cc.Count; // We also find the least used cookie collection in ENTIRE container. // We count the collection as LRU only if it holds 1+ elements. if (cc.Count > 0 && (tempUsed = cc.TimeStamp(CookieCollection.Stamp.Check)) < oldUsed) { lruDomain = tempDomain; lruCc = cc; oldUsed = tempUsed; } } } // Check if we have reduced to the limit of the domain by expiration only. int min_count = Math.Min((int)(domain_count * remainingFraction), Math.Min(_maxCookiesPerDomain, _maxCookies) - 1); if (domain_count > min_count) { // This case requires sorting all domain collections by timestamp. KeyValuePair<DateTime, CookieCollection>[] cookies; lock (pathList.SyncRoot) { cookies = new KeyValuePair<DateTime, CookieCollection>[pathList.Count]; foreach (KeyValuePair<string, CookieCollection> pair in pathList) { CookieCollection cc = pair.Value; cookies[itemp] = new KeyValuePair<DateTime, CookieCollection>(cc.TimeStamp(CookieCollection.Stamp.Check), cc); ++itemp; } } Array.Sort(cookies, (a, b) => a.Key.CompareTo(b.Key)); itemp = 0; for (int i = 0; i < cookies.Length; ++i) { CookieCollection cc = cookies[i].Value; lock (cc) { while (domain_count > min_count && cc.Count > 0) { cc.RemoveAt(0); --domain_count; --_count; ++removed; } } if (domain_count <= min_count) { break; } } if (domain_count > min_count && domain != null) { // Cannot complete aging of explicit domain (no cookie adding allowed). return false; } } } } // We have completed aging of the specified domain. if (domain != null) { return true; } // The rest is for entire container aging. // We must get at least one free slot. // Don't need to apply LRU if we already cleaned something. if (removed != 0) { return true; } if (oldUsed == DateTime.MaxValue) { // Something strange. Either capacity is 0 or all collections are locked with cc.Used. return false; } // Remove oldest cookies from the least used collection. lock (lruCc) { while (_count >= _maxCookies && lruCc.Count > 0) { lruCc.RemoveAt(0); --_count; } } return true; } // Return number of cookies removed from the collection. private int ExpireCollection(CookieCollection cc) { lock (cc) { int oldCount = cc.Count; int idx = oldCount - 1; // Cannot use enumerator as we are going to alter collection. while (idx >= 0) { Cookie cookie = cc[idx]; if (cookie.Expired) { cc.RemoveAt(idx); } --idx; } return oldCount - cc.Count; } } public void Add(CookieCollection cookies) { if (cookies == null) { throw new ArgumentNullException(nameof(cookies)); } foreach (Cookie c in cookies) { Add(c); } } // This will try (if needed) get the full domain name of the host given the Uri. // NEVER call this function from internal methods with 'fqdnRemote' == null. // Since this method counts security issue for DNS and hence will slow // the performance. internal bool IsLocalDomain(string host) { int dot = host.IndexOf('.'); if (dot == -1) { // No choice but to treat it as a host on the local domain. // This also covers 'localhost' and 'loopback'. return true; } // Quick test for typical cases: loopback addresses for IPv4 and IPv6. if ((host == "127.0.0.1") || (host == "::1") || (host == "0:0:0:0:0:0:0:1")) { return true; } // Test domain membership. if (string.Compare(_fqdnMyDomain, 0, host, dot, _fqdnMyDomain.Length, StringComparison.OrdinalIgnoreCase) == 0) { return true; } // Test for "127.###.###.###" without using regex. string[] ipParts = host.Split('.'); if (ipParts != null && ipParts.Length == 4 && ipParts[0] == "127") { int i; for (i = 1; i < 4; i++) { switch (ipParts[i].Length) { case 3: if (ipParts[i][2] < '0' || ipParts[i][2] > '9') { break; } goto case 2; case 2: if (ipParts[i][1] < '0' || ipParts[i][1] > '9') { break; } goto case 1; case 1: if (ipParts[i][0] < '0' || ipParts[i][0] > '9') { break; } continue; } break; } if (i == 4) { return true; } } return false; } public void Add(Uri uri, Cookie cookie) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (cookie == null) { throw new ArgumentNullException(nameof(cookie)); } Cookie new_cookie = cookie.Clone(); new_cookie.VerifySetDefaults(new_cookie.Variant, uri, IsLocalDomain(uri.Host), _fqdnMyDomain, true, true); Add(new_cookie, true); } public void Add(Uri uri, CookieCollection cookies) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (cookies == null) { throw new ArgumentNullException(nameof(cookies)); } bool isLocalDomain = IsLocalDomain(uri.Host); foreach (Cookie c in cookies) { Cookie new_cookie = c.Clone(); new_cookie.VerifySetDefaults(new_cookie.Variant, uri, isLocalDomain, _fqdnMyDomain, true, true); Add(new_cookie, true); } } internal CookieCollection CookieCutter(Uri uri, string headerName, string setCookieHeader, bool isThrow) { if (GlobalLog.IsEnabled) { GlobalLog.Print("CookieContainer#" + LoggingHash.HashString(this) + "::CookieCutter() uri:" + uri + " headerName:" + headerName + " setCookieHeader:" + setCookieHeader + " isThrow:" + isThrow); } CookieCollection cookies = new CookieCollection(); CookieVariant variant = CookieVariant.Unknown; if (headerName == null) { variant = CookieVariant.Default; } else { for (int i = 0; i < s_headerInfo.Length; ++i) { if ((String.Compare(headerName, s_headerInfo[i].Name, StringComparison.OrdinalIgnoreCase) == 0)) { variant = s_headerInfo[i].Variant; } } } bool isLocalDomain = IsLocalDomain(uri.Host); try { CookieParser parser = new CookieParser(setCookieHeader); do { Cookie cookie = parser.Get(); if (GlobalLog.IsEnabled) { GlobalLog.Print("CookieContainer#" + LoggingHash.HashString(this) + "::CookieCutter() CookieParser returned cookie:" + LoggingHash.ObjectToString(cookie)); } if (cookie == null) { break; } // Parser marks invalid cookies this way if (String.IsNullOrEmpty(cookie.Name)) { if (isThrow) { throw new CookieException(SR.net_cookie_format); } // Otherwise, ignore (reject) cookie continue; } // This will set the default values from the response URI // AND will check for cookie validity if (!cookie.VerifySetDefaults(variant, uri, isLocalDomain, _fqdnMyDomain, true, isThrow)) { continue; } // If many same cookies arrive we collapse them into just one, hence setting // parameter isStrict = true below cookies.InternalAdd(cookie, true); } while (true); } catch (OutOfMemoryException) { throw; } catch (Exception e) { if (isThrow) { throw new CookieException(SR.Format(SR.net_cookie_parse_header, uri.AbsoluteUri), e); } } foreach (Cookie c in cookies) { Add(c, isThrow); } return cookies; } public CookieCollection GetCookies(Uri uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } return InternalGetCookies(uri); } internal CookieCollection InternalGetCookies(Uri uri) { bool isSecure = (uri.Scheme == UriScheme.Https); int port = uri.Port; CookieCollection cookies = new CookieCollection(); List<string> domainAttributeMatchAnyCookieVariant = new List<string>(); List<string> domainAttributeMatchOnlyCookieVariantPlain = new List<string>(); string fqdnRemote = uri.Host; // Add initial candidates to match Domain attribute of possible cookies. // For these Domains, cookie can have any CookieVariant enum value. domainAttributeMatchAnyCookieVariant.Add(fqdnRemote); domainAttributeMatchAnyCookieVariant.Add("." + fqdnRemote); int dot = fqdnRemote.IndexOf('.'); if (dot == -1) { // DNS.resolve may return short names even for other inet domains ;-( // We _don't_ know what the exact domain is, so try also grab short hostname cookies. // Grab long name from the local domain if (_fqdnMyDomain != null && _fqdnMyDomain.Length != 0) { domainAttributeMatchAnyCookieVariant.Add(fqdnRemote + _fqdnMyDomain); // Grab the local domain itself domainAttributeMatchAnyCookieVariant.Add(_fqdnMyDomain); } } else { // Grab the host domain domainAttributeMatchAnyCookieVariant.Add(fqdnRemote.Substring(dot)); // The following block is only for compatibility with Version0 spec. // Still, we'll add only Plain-Variant cookies if found under below keys if (fqdnRemote.Length > 2) { // We ignore the '.' at the end on the name int last = fqdnRemote.LastIndexOf('.', fqdnRemote.Length - 2); // AND keys with <2 dots inside. if (last > 0) { last = fqdnRemote.LastIndexOf('.', last - 1); } if (last != -1) { while ((dot < last) && (dot = fqdnRemote.IndexOf('.', dot + 1)) != -1) { // These candidates can only match CookieVariant.Plain cookies. domainAttributeMatchOnlyCookieVariantPlain.Add(fqdnRemote.Substring(dot)); } } } } BuildCookieCollectionFromDomainMatches(uri, isSecure, port, cookies, domainAttributeMatchAnyCookieVariant, false); BuildCookieCollectionFromDomainMatches(uri, isSecure, port, cookies, domainAttributeMatchOnlyCookieVariantPlain, true); return cookies; } private void BuildCookieCollectionFromDomainMatches(Uri uri, bool isSecure, int port, CookieCollection cookies, List<string> domainAttribute, bool matchOnlyPlainCookie) { for (int i = 0; i < domainAttribute.Count; i++) { bool found = false; bool defaultAdded = false; PathList pathList; lock (_domainTable) { _domainTable.TryGetValue(domainAttribute[i], out pathList); } if (pathList == null) { continue; } lock (pathList.SyncRoot) { foreach (KeyValuePair<string, CookieCollection> pair in pathList) { string path = pair.Key; if (uri.AbsolutePath.StartsWith(CookieParser.CheckQuoted(path))) { found = true; CookieCollection cc = pair.Value; cc.TimeStamp(CookieCollection.Stamp.Set); MergeUpdateCollections(cookies, cc, port, isSecure, matchOnlyPlainCookie); if (path == "/") { defaultAdded = true; } } else if (found) { break; } } } if (!defaultAdded) { CookieCollection cc = pathList["/"]; if (cc != null) { cc.TimeStamp(CookieCollection.Stamp.Set); MergeUpdateCollections(cookies, cc, port, isSecure, matchOnlyPlainCookie); } } // Remove unused domain // (This is the only place that does domain removal) if (pathList.Count == 0) { AddRemoveDomain(domainAttribute[i], null); } } } private void MergeUpdateCollections(CookieCollection destination, CookieCollection source, int port, bool isSecure, bool isPlainOnly) { lock (source) { // Cannot use foreach as we going update 'source' for (int idx = 0; idx < source.Count; ++idx) { bool to_add = false; Cookie cookie = source[idx]; if (cookie.Expired) { // If expired, remove from container and don't add to the destination source.RemoveAt(idx); --_count; --idx; } else { // Add only if port does match to this request URI // or was not present in the original response. if (isPlainOnly && cookie.Variant != CookieVariant.Plain) { ; // Don't add } else if (cookie.PortList != null) { foreach (int p in cookie.PortList) { if (p == port) { to_add = true; break; } } } else { // It was implicit Port, always OK to add. to_add = true; } // Refuse to add a secure cookie into an 'unsecure' destination if (cookie.Secure && !isSecure) { to_add = false; } if (to_add) { // In 'source' are already orederd. // If two same cookies come from different 'source' then they // will follow (not replace) each other. destination.InternalAdd(cookie, false); } } } } } public string GetCookieHeader(Uri uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } string dummy; return GetCookieHeader(uri, out dummy); } internal string GetCookieHeader(Uri uri, out string optCookie2) { CookieCollection cookies = InternalGetCookies(uri); string delimiter = string.Empty; var builder = new StringBuilder(); foreach (Cookie cookie in cookies) { builder.Append(delimiter).Append(cookie.ToString()); delimiter = "; "; } optCookie2 = cookies.IsOtherVersionSeen ? (Cookie.SpecialAttributeLiteral + Cookie.VersionAttributeName + Cookie.EqualsLiteral + Cookie.MaxSupportedVersionString) : string.Empty; return builder.ToString(); } public void SetCookies(Uri uri, string cookieHeader) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (cookieHeader == null) { throw new ArgumentNullException(nameof(cookieHeader)); } CookieCutter(uri, null, cookieHeader, true); // Will throw on error } } internal sealed class PathList { private readonly SortedList<string, CookieCollection> _list = new SortedList<string, CookieCollection>(PathListComparer.StaticInstance); private readonly object _lock = new object(); public int Count { get { lock (SyncRoot) { return _list.Count; } } } public int GetCookiesCount() { int count = 0; lock (SyncRoot) { foreach (KeyValuePair<string, CookieCollection> pair in _list) { CookieCollection cc = pair.Value; count += cc.Count; } } return count; } public CookieCollection this[string s] { get { lock (SyncRoot) { CookieCollection value; return _list.TryGetValue(s, out value) ? value : null; } } set { lock (SyncRoot) { Debug.Assert(value != null); _list[s] = value; } } } public IEnumerator<KeyValuePair<string, CookieCollection>> GetEnumerator() { lock (SyncRoot) { return _list.GetEnumerator(); } } public object SyncRoot => _lock; private sealed class PathListComparer : IComparer<string> { internal static readonly PathListComparer StaticInstance = new PathListComparer(); int IComparer<string>.Compare(string x, string y) { string pathLeft = CookieParser.CheckQuoted(x); string pathRight = CookieParser.CheckQuoted(y); int ll = pathLeft.Length; int lr = pathRight.Length; int length = Math.Min(ll, lr); for (int i = 0; i < length; ++i) { if (pathLeft[i] != pathRight[i]) { return pathLeft[i] - pathRight[i]; } } return lr - ll; } } } }
/** * (C) Copyright IBM Corp. 2019, 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.Collections.Generic; using JsonSubTypes; using Newtonsoft.Json; namespace IBM.Watson.Assistant.V1.Model { /// <summary> /// DialogNodeOutputGeneric. /// Classes which extend this class: /// - DialogNodeOutputGenericDialogNodeOutputResponseTypeText /// - DialogNodeOutputGenericDialogNodeOutputResponseTypePause /// - DialogNodeOutputGenericDialogNodeOutputResponseTypeImage /// - DialogNodeOutputGenericDialogNodeOutputResponseTypeOption /// - DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent /// - DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill /// - DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer /// - DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined /// </summary> [JsonConverter(typeof(JsonSubtypes), "response_type")] [JsonSubtypes.KnownSubType(typeof(DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer), "channel_transfer")] [JsonSubtypes.KnownSubType(typeof(DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent), "connect_to_agent")] [JsonSubtypes.KnownSubType(typeof(DialogNodeOutputGenericDialogNodeOutputResponseTypeImage), "image")] [JsonSubtypes.KnownSubType(typeof(DialogNodeOutputGenericDialogNodeOutputResponseTypeOption), "option")] [JsonSubtypes.KnownSubType(typeof(DialogNodeOutputGenericDialogNodeOutputResponseTypePause), "pause")] [JsonSubtypes.KnownSubType(typeof(DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill), "search_skill")] [JsonSubtypes.KnownSubType(typeof(DialogNodeOutputGenericDialogNodeOutputResponseTypeText), "text")] [JsonSubtypes.KnownSubType(typeof(DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined), "user_defined")] public class DialogNodeOutputGeneric { /// This ctor is protected to prevent instantiation of this base class. /// Instead, users should instantiate one of the subclasses listed below: /// - DialogNodeOutputGenericDialogNodeOutputResponseTypeText /// - DialogNodeOutputGenericDialogNodeOutputResponseTypePause /// - DialogNodeOutputGenericDialogNodeOutputResponseTypeImage /// - DialogNodeOutputGenericDialogNodeOutputResponseTypeOption /// - DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent /// - DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill /// - DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer /// - DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined protected DialogNodeOutputGeneric() { } /// <summary> /// How a response is selected from the list, if more than one response is specified. /// </summary> public class SelectionPolicyValue { /// <summary> /// Constant SEQUENTIAL for sequential /// </summary> public const string SEQUENTIAL = "sequential"; /// <summary> /// Constant RANDOM for random /// </summary> public const string RANDOM = "random"; /// <summary> /// Constant MULTILINE for multiline /// </summary> public const string MULTILINE = "multiline"; } /// <summary> /// The preferred type of control to display, if supported by the channel. /// </summary> public class PreferenceValue { /// <summary> /// Constant DROPDOWN for dropdown /// </summary> public const string DROPDOWN = "dropdown"; /// <summary> /// Constant BUTTON for button /// </summary> public const string BUTTON = "button"; } /// <summary> /// The type of the search query. /// </summary> public class QueryTypeValue { /// <summary> /// Constant NATURAL_LANGUAGE for natural_language /// </summary> public const string NATURAL_LANGUAGE = "natural_language"; /// <summary> /// Constant DISCOVERY_QUERY_LANGUAGE for discovery_query_language /// </summary> public const string DISCOVERY_QUERY_LANGUAGE = "discovery_query_language"; } /// <summary> /// How a response is selected from the list, if more than one response is specified. /// Constants for possible values can be found using DialogNodeOutputGeneric.SelectionPolicyValue /// </summary> [JsonProperty("selection_policy", NullValueHandling = NullValueHandling.Ignore)] public string SelectionPolicy { get; set; } /// <summary> /// The preferred type of control to display, if supported by the channel. /// Constants for possible values can be found using DialogNodeOutputGeneric.PreferenceValue /// </summary> [JsonProperty("preference", NullValueHandling = NullValueHandling.Ignore)] public string Preference { get; set; } /// <summary> /// The type of the search query. /// Constants for possible values can be found using DialogNodeOutputGeneric.QueryTypeValue /// </summary> [JsonProperty("query_type", NullValueHandling = NullValueHandling.Ignore)] public string QueryType { get; set; } /// <summary> /// The type of response returned by the dialog node. The specified response type must be supported by the /// client application or channel. /// </summary> [JsonProperty("response_type", NullValueHandling = NullValueHandling.Ignore)] public string ResponseType { get; protected set; } /// <summary> /// A list of one or more objects defining text responses. /// </summary> [JsonProperty("values", NullValueHandling = NullValueHandling.Ignore)] public List<DialogNodeOutputTextValuesElement> Values { get; protected set; } /// <summary> /// The delimiter to use as a separator between responses when `selection_policy`=`multiline`. /// </summary> [JsonProperty("delimiter", NullValueHandling = NullValueHandling.Ignore)] public string Delimiter { get; protected set; } /// <summary> /// An array of objects specifying channels for which the response is intended. /// </summary> [JsonProperty("channels", NullValueHandling = NullValueHandling.Ignore)] public List<ResponseGenericChannel> Channels { get; protected set; } /// <summary> /// How long to pause, in milliseconds. The valid values are from 0 to 10000. /// </summary> [JsonProperty("time", NullValueHandling = NullValueHandling.Ignore)] public long? Time { get; protected set; } /// <summary> /// Whether to send a "user is typing" event during the pause. Ignored if the channel does not support this /// event. /// </summary> [JsonProperty("typing", NullValueHandling = NullValueHandling.Ignore)] public bool? Typing { get; protected set; } /// <summary> /// The `https:` URL of the image. /// </summary> [JsonProperty("source", NullValueHandling = NullValueHandling.Ignore)] public string Source { get; protected set; } /// <summary> /// An optional title to show before the response. /// </summary> [JsonProperty("title", NullValueHandling = NullValueHandling.Ignore)] public string Title { get; protected set; } /// <summary> /// An optional description to show with the response. /// </summary> [JsonProperty("description", NullValueHandling = NullValueHandling.Ignore)] public string Description { get; protected set; } /// <summary> /// Descriptive text that can be used for screen readers or other situations where the image cannot be seen. /// </summary> [JsonProperty("alt_text", NullValueHandling = NullValueHandling.Ignore)] public string AltText { get; protected set; } /// <summary> /// An array of objects describing the options from which the user can choose. You can include up to 20 options. /// </summary> [JsonProperty("options", NullValueHandling = NullValueHandling.Ignore)] public List<DialogNodeOutputOptionsElement> Options { get; protected set; } /// <summary> /// An optional message to be sent to the human agent who will be taking over the conversation. /// </summary> [JsonProperty("message_to_human_agent", NullValueHandling = NullValueHandling.Ignore)] public string MessageToHumanAgent { get; protected set; } /// <summary> /// An optional message to be displayed to the user to indicate that the conversation will be transferred to the /// next available agent. /// </summary> [JsonProperty("agent_available", NullValueHandling = NullValueHandling.Ignore)] public AgentAvailabilityMessage AgentAvailable { get; protected set; } /// <summary> /// An optional message to be displayed to the user to indicate that no online agent is available to take over /// the conversation. /// </summary> [JsonProperty("agent_unavailable", NullValueHandling = NullValueHandling.Ignore)] public AgentAvailabilityMessage AgentUnavailable { get; protected set; } /// <summary> /// The text of the search query. This can be either a natural-language query or a query that uses the Discovery /// query language syntax, depending on the value of the **query_type** property. For more information, see the /// [Discovery service /// documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-operators#query-operators). /// </summary> [JsonProperty("query", NullValueHandling = NullValueHandling.Ignore)] public string Query { get; protected set; } /// <summary> /// An optional filter that narrows the set of documents to be searched. For more information, see the /// [Discovery service documentation]([Discovery service /// documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-parameters#filter). /// </summary> [JsonProperty("filter", NullValueHandling = NullValueHandling.Ignore)] public string Filter { get; protected set; } /// <summary> /// The version of the Discovery service API to use for the query. /// </summary> [JsonProperty("discovery_version", NullValueHandling = NullValueHandling.Ignore)] public string DiscoveryVersion { get; protected set; } /// <summary> /// The message to display to the user when initiating a channel transfer. /// </summary> [JsonProperty("message_to_user", NullValueHandling = NullValueHandling.Ignore)] public string MessageToUser { get; protected set; } /// <summary> /// An object containing any properties for the user-defined response type. The total size of this object cannot /// exceed 5000 bytes. /// </summary> [JsonProperty("user_defined", NullValueHandling = NullValueHandling.Ignore)] public Dictionary<string, object> UserDefined { get; protected set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Text; using System.Windows.Forms; using MyDownloader.Core.Common; using MyDownloader.Core; using MyDownloader.Core.UI; using MyDownloader.Extension.Protocols; using ICSharpCode.SharpZipLib.Zip; using MyDownloader.Extension.Zip; using System.IO; using System.Threading; using WebKit; namespace MyDownloader.App.UI { public partial class NewDownloadDialog : Form { public NewDownloadDialog() { InitializeComponent(); locationMain.UrlChanged += new EventHandler(locationMain_UrlChanged); } void locationMain_UrlChanged(object sender, EventArgs e) { try { Uri u = new Uri(locationMain.ResourceLocation.URL); string fn = u.Segments[u.Segments.Length - 1]; if (!fn.EndsWith("/")) { txtFilename.Text = u.Segments[u.Segments.Length - 1]; } else txtFilename.Text = "Unrecognized Download.file"; } catch { txtFilename.Text = string.Empty; } } public ResourceLocation DownloadLocation { get { return locationMain.ResourceLocation; } set { locationMain.ResourceLocation = value; } } public ResourceLocation[] Mirrors { get { MyDownloader.Core.ResourceLocation[] mirrors = new MyDownloader.Core.ResourceLocation[lvwLocations.Items.Count]; for (int i = 0; i < lvwLocations.Items.Count; i++) { ListViewItem item = lvwLocations.Items[i]; mirrors[i] = MyDownloader.Core.ResourceLocation.FromURL( item.SubItems[0].Text, BoolFormatter.FromString(item.SubItems[1].Text), item.SubItems[2].Text, item.SubItems[3].Text); } return mirrors; } } public int Segments { get { return 1; } } public bool StartNow { get { return true; } } private void lvwLocations_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) { bool hasSelected = lvwLocations.SelectedItems.Count > 0; btnRemove.Enabled = hasSelected; if (hasSelected) { ListViewItem item = lvwLocations.SelectedItems[0]; locationAlternate.ResourceLocation = MyDownloader.Core.ResourceLocation.FromURL( item.SubItems[0].Text, BoolFormatter.FromString(item.SubItems[1].Text), item.SubItems[2].Text, item.SubItems[3].Text); } else { locationAlternate.ResourceLocation = null; } } private void btnRemove_Click(object sender, EventArgs e) { for (int i = lvwLocations.Items.Count - 1; i >= 0; i--) { if (lvwLocations.Items[i].Selected) { lvwLocations.Items.RemoveAt(i); } } } private void btnAdd_Click(object sender, EventArgs e) { ResourceLocation rl = locationAlternate.ResourceLocation; if (lvwLocations.SelectedItems.Count > 0) { ListViewItem item = lvwLocations.SelectedItems[0]; item.SubItems[0].Text = rl.URL; item.SubItems[1].Text = BoolFormatter.ToString(rl.Authenticate); item.SubItems[2].Text = rl.Login; item.SubItems[3].Text = rl.Password; } else { ListViewItem item = new ListViewItem(); item.Text = rl.URL; item.SubItems.Add(BoolFormatter.ToString(rl.Authenticate)); item.SubItems.Add(rl.Login); item.SubItems.Add(rl.Password); lvwLocations.Items.Add(item); } } public string LocalFile; string folderpath = GlobalPreferences.DownloadsFolder; private void btnOK_Click(object sender, EventArgs e) { string SaveFilePath = string.Empty; folderpath = GlobalPreferences.DownloadsFolder; if (folderpath != string.Empty) { if (folderpath.EndsWith("\\")) SaveFilePath = folderpath + txtFilename.Text; else SaveFilePath = folderpath + "\\" + txtFilename.Text; } else { System.Windows.Forms.FolderBrowserDialog f = new FolderBrowserDialog(); f.Description = "Please select the folder where you want the file to be saved."; if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK) { SaveFilePath = f.SelectedPath + "\\" + txtFilename.Text; } else { this.DialogResult = System.Windows.Forms.DialogResult.Cancel; return; } } this.LocalFile = SaveFilePath; try { ResourceLocation rl = this.DownloadLocation; rl.BindProtocolProviderType(); if (rl.ProtocolProviderType == null) { MessageBox.Show("Invalid URL format, please check the location field.", AppManager.Instance.Application.MainForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); DialogResult = DialogResult.None; return; } ResourceLocation[] mirrors = this.Mirrors; if (mirrors != null && mirrors.Length > 0) { foreach (ResourceLocation mirrorRl in mirrors) { mirrorRl.BindProtocolProviderType(); if (mirrorRl.ProtocolProviderType == null) { MessageBox.Show("Invalid mirror URL format, please check the mirror URLs.", AppManager.Instance.Application.MainForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); DialogResult = DialogResult.None; return; } } } Downloader download = DownloadManager.Instance.Add( rl, mirrors, this.LocalFile, this.Segments, this.StartNow); Close(); } catch (Exception) { DialogResult = DialogResult.None; MessageBox.Show("Unknow error, please check your input data.", AppManager.Instance.Application.MainForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnCancel_Click(object sender, EventArgs e) { Close(); } private void chkChooseZIP_CheckedChanged(object sender, EventArgs e) { } private void NewDownloadForm_FormClosing(object sender, FormClosingEventArgs e) { } private void NewDownloadForm_Load(object sender, EventArgs e) { } private void folderBrowser1_Load(object sender, EventArgs e) { } private void NewDownloadForm_Load_1(object sender, EventArgs e) { } } }
// This is always generated file. Do not change anything. using SoftFX.Lrp; namespace SoftFX.Extended.Generated { internal class FeedServer { private readonly IClient m_client; public FeedServer(IClient client) { if(null == client) { throw new System.ArgumentNullException("client", "Client argument can not be null"); } m_client = client; } public bool IsSupported { get { return m_client.IsSupported(5); } } public bool Is_Create_Supported { get { return m_client.IsSupported(5, 0); } } public SoftFX.Lrp.LPtr Create(string name, string connectionString) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteAString(name); buffer.WriteAString(connectionString); int _status = m_client.Invoke(5, 0, buffer); TypesSerializer.Throw(_status, buffer); var _result = buffer.ReadLocalPointer(); return _result; } } public bool Is_GetQuoteHistoryFiles_Supported { get { return m_client.IsSupported(5, 1); } } public SoftFX.Extended.DataHistoryInfo GetQuoteHistoryFiles(SoftFX.Lrp.LPtr handle, string symbol, bool includeLevel2, System.DateTime time, uint timeoutInMilliseconds) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); buffer.WriteAString(symbol); buffer.WriteBoolean(includeLevel2); buffer.WriteTime(time); buffer.WriteUInt32(timeoutInMilliseconds); int _status = m_client.Invoke(5, 1, buffer); TypesSerializer.Throw(_status, buffer); var _result = buffer.ReadDataHistoryInfo(); return _result; } } public bool Is_GetBarsHistoryFiles_Supported { get { return m_client.IsSupported(5, 2); } } public SoftFX.Extended.DataHistoryInfo GetBarsHistoryFiles(SoftFX.Lrp.LPtr handle, string symbol, SoftFX.Extended.PriceType priceType, string period, System.DateTime time, uint timeoutInMilliseconds) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); buffer.WriteAString(symbol); buffer.WritePriceType(priceType); buffer.WriteAString(period); buffer.WriteTime(time); buffer.WriteUInt32(timeoutInMilliseconds); int _status = m_client.Invoke(5, 2, buffer); TypesSerializer.Throw(_status, buffer); var _result = buffer.ReadDataHistoryInfo(); return _result; } } public bool Is_GetCurrencies_Supported { get { return m_client.IsSupported(5, 3); } } public SoftFX.Extended.CurrencyInfo[] GetCurrencies(SoftFX.Lrp.LPtr handle, uint timeoutInMilliseconds) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); buffer.WriteUInt32(timeoutInMilliseconds); int _status = m_client.Invoke(5, 3, buffer); TypesSerializer.Throw(_status, buffer); var _result = buffer.ReadCurrencyInfoArray(); return _result; } } public bool Is_GetSymbols_Supported { get { return m_client.IsSupported(5, 4); } } public SoftFX.Extended.SymbolInfo[] GetSymbols(SoftFX.Lrp.LPtr handle, uint timeoutInMilliseconds) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); buffer.WriteUInt32(timeoutInMilliseconds); int _status = m_client.Invoke(5, 4, buffer); TypesSerializer.Throw(_status, buffer); var _result = buffer.ReadSymbolInfoArray(); return _result; } } public bool Is_SubscribeToQuotes_Supported { get { return m_client.IsSupported(5, 5); } } public void SubscribeToQuotes(SoftFX.Lrp.LPtr handle, string[] symbols, int depth, uint timeoutInMilliseconds) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); buffer.WriteStringArray(symbols); buffer.WriteInt32(depth); buffer.WriteUInt32(timeoutInMilliseconds); int _status = m_client.Invoke(5, 5, buffer); TypesSerializer.Throw(_status, buffer); } } public bool Is_UnsubscribeQuotes_Supported { get { return m_client.IsSupported(5, 6); } } public void UnsubscribeQuotes(SoftFX.Lrp.LPtr handle, string[] symbols, uint timeoutInMilliseconds) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); buffer.WriteStringArray(symbols); buffer.WriteUInt32(timeoutInMilliseconds); int _status = m_client.Invoke(5, 6, buffer); TypesSerializer.Throw(_status, buffer); } } public bool Is_GetBarsHistoryMetaInfoFile_Supported { get { return m_client.IsSupported(5, 7); } } public string GetBarsHistoryMetaInfoFile(SoftFX.Lrp.LPtr handle, string symbol, SoftFX.Extended.PriceType priceType, string period, uint timeoutInMilliseconds) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); buffer.WriteAString(symbol); buffer.WritePriceType(priceType); buffer.WriteAString(period); buffer.WriteUInt32(timeoutInMilliseconds); int _status = m_client.Invoke(5, 7, buffer); TypesSerializer.Throw(_status, buffer); var _result = buffer.ReadAString(); return _result; } } public bool Is_GetQuotesHistoryMetaInfoFile_Supported { get { return m_client.IsSupported(5, 8); } } public string GetQuotesHistoryMetaInfoFile(SoftFX.Lrp.LPtr handle, string symbol, bool includeLevel2, uint timeoutInMilliseconds) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); buffer.WriteAString(symbol); buffer.WriteBoolean(includeLevel2); buffer.WriteUInt32(timeoutInMilliseconds); int _status = m_client.Invoke(5, 8, buffer); TypesSerializer.Throw(_status, buffer); var _result = buffer.ReadAString(); return _result; } } public bool Is_GetHistoryBars_Supported { get { return m_client.IsSupported(5, 9); } } public SoftFX.Extended.DataHistoryInfo GetHistoryBars(SoftFX.Lrp.LPtr handle, string symbol, System.DateTime time, int barsNumber, SoftFX.Extended.PriceType priceType, string period, uint timeoutInMilliseconds) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); buffer.WriteAString(symbol); buffer.WriteTime(time); buffer.WriteInt32(barsNumber); buffer.WritePriceType(priceType); buffer.WriteAString(period); buffer.WriteUInt32(timeoutInMilliseconds); int _status = m_client.Invoke(5, 9, buffer); TypesSerializer.Throw(_status, buffer); var _result = buffer.ReadDataHistoryInfo(); return _result; } } public bool Is_GetQueueThreshold_Supported { get { return m_client.IsSupported(5, 10); } } public int GetQueueThreshold(SoftFX.Lrp.LPtr handle) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); int _status = m_client.Invoke(5, 10, buffer); TypesSerializer.Throw(_status, buffer); var _result = buffer.ReadInt32(); return _result; } } public bool Is_SetQueueThreshold_Supported { get { return m_client.IsSupported(5, 11); } } public void SetQueueThreshold(SoftFX.Lrp.LPtr handle, int newSize) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); buffer.WriteInt32(newSize); int _status = m_client.Invoke(5, 11, buffer); TypesSerializer.Throw(_status, buffer); } } public bool Is_GetQuotesHistoryVersion_Supported { get { return m_client.IsSupported(5, 12); } } public int GetQuotesHistoryVersion(SoftFX.Lrp.LPtr handle, uint timeoutInMilliseconds) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); buffer.WriteUInt32(timeoutInMilliseconds); int _status = m_client.Invoke(5, 12, buffer); TypesSerializer.Throw(_status, buffer); var _result = buffer.ReadInt32(); return _result; } } } }
/* Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft 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 C5; using NUnit.Framework; using SCG=System.Collections.Generic; namespace C5UnitTests.trees.RBDictionary { using DictionaryIntToInt = TreeDictionary<int, int>; static class Factory { public static IDictionary<K,V> New<K,V>() { return new TreeDictionary<K,V>(); } } [TestFixture] public class GenericTesters { [Test] public void TestSerialize() { C5UnitTests.Templates.Extensible.Serialization.DTester<DictionaryIntToInt>(); } } [TestFixture] public class Formatting { IDictionary<int,int> coll; IFormatProvider rad16; [SetUp] public void Init() { coll = Factory.New<int,int>(); rad16 = new RadixFormatProvider(16); } [TearDown] public void Dispose() { coll = null; rad16 = null; } [Test] public void Format() { Assert.AreEqual("[ ]", coll.ToString()); coll.Add(23, 67); coll.Add(45, 89); Assert.AreEqual("[ 23 => 67, 45 => 89 ]", coll.ToString()); Assert.AreEqual("[ 17 => 43, 2D => 59 ]", coll.ToString(null, rad16)); Assert.AreEqual("[ 23 => 67, ... ]", coll.ToString("L14", null)); Assert.AreEqual("[ 17 => 43, ... ]", coll.ToString("L14", rad16)); } } [TestFixture] public class RBDict { private TreeDictionary<string,string> dict; [SetUp] public void Init() { dict = new TreeDictionary<string,string>(new SC()); } [TearDown] public void Dispose() { dict = null; } [Test] [ExpectedException(typeof(NullReferenceException))] public void NullEqualityComparerinConstructor1() { new TreeDictionary<int,int>(null); } [Test] public void Choose() { dict.Add("YES","NO"); Assert.AreEqual(new KeyValuePair<string,string>("YES","NO"), dict.Choose()); } [Test] [ExpectedException(typeof(NoSuchItemException))] public void BadChoose() { dict.Choose(); } [Test] public void Pred1() { dict.Add("A", "1"); dict.Add("C", "2"); dict.Add("E", "3"); Assert.AreEqual("1", dict.Predecessor("B").Value); Assert.AreEqual("1", dict.Predecessor("C").Value); Assert.AreEqual("1", dict.WeakPredecessor("B").Value); Assert.AreEqual("2", dict.WeakPredecessor("C").Value); Assert.AreEqual("2", dict.Successor("B").Value); Assert.AreEqual("3", dict.Successor("C").Value); Assert.AreEqual("2", dict.WeakSuccessor("B").Value); Assert.AreEqual("2", dict.WeakSuccessor("C").Value); } [Test] public void Pred2() { dict.Add("A", "1"); dict.Add("C", "2"); dict.Add("E", "3"); KeyValuePair<String, String> res; Assert.IsTrue(dict.TryPredecessor("B", out res)); Assert.AreEqual("1", res.Value); Assert.IsTrue(dict.TryPredecessor("C", out res)); Assert.AreEqual("1", res.Value); Assert.IsTrue(dict.TryWeakPredecessor("B", out res)); Assert.AreEqual("1", res.Value); Assert.IsTrue(dict.TryWeakPredecessor("C", out res)); Assert.AreEqual("2", res.Value); Assert.IsTrue(dict.TrySuccessor("B", out res)); Assert.AreEqual("2", res.Value); Assert.IsTrue(dict.TrySuccessor("C", out res)); Assert.AreEqual("3", res.Value); Assert.IsTrue(dict.TryWeakSuccessor("B", out res)); Assert.AreEqual("2", res.Value); Assert.IsTrue(dict.TryWeakSuccessor("C", out res)); Assert.AreEqual("2", res.Value); Assert.IsFalse(dict.TryPredecessor("A", out res)); Assert.AreEqual(null, res.Key); Assert.AreEqual(null, res.Value); Assert.IsFalse(dict.TryWeakPredecessor("@", out res)); Assert.AreEqual(null, res.Key); Assert.AreEqual(null, res.Value); Assert.IsFalse(dict.TrySuccessor("E", out res)); Assert.AreEqual(null, res.Key); Assert.AreEqual(null, res.Value); Assert.IsFalse(dict.TryWeakSuccessor("F", out res)); Assert.AreEqual(null, res.Key); Assert.AreEqual(null, res.Value); } [Test] public void Initial() { bool res; Assert.IsFalse(dict.IsReadOnly); Assert.AreEqual(dict.Count, 0, "new dict should be empty"); dict.Add("A", "B"); Assert.AreEqual(dict.Count, 1, "bad count"); Assert.AreEqual(dict["A"], "B", "Wrong value for dict[A]"); dict.Add("C", "D"); Assert.AreEqual(dict.Count, 2, "bad count"); Assert.AreEqual(dict["A"], "B", "Wrong value"); Assert.AreEqual(dict["C"], "D", "Wrong value"); res = dict.Remove("A"); Assert.IsTrue(res, "bad return value from Remove(A)"); Assert.IsTrue(dict.Check()); Assert.AreEqual(dict.Count, 1, "bad count"); Assert.AreEqual(dict["C"], "D", "Wrong value of dict[C]"); res = dict.Remove("Z"); Assert.IsFalse(res, "bad return value from Remove(Z)"); Assert.AreEqual(dict.Count, 1, "bad count"); Assert.AreEqual(dict["C"], "D", "Wrong value of dict[C] (2)"); dict.Clear(); Assert.AreEqual(dict.Count, 0, "dict should be empty"); } [Test] public void Contains() { dict.Add("C", "D"); Assert.IsTrue(dict.Contains("C")); Assert.IsFalse(dict.Contains("D")); } [Test] [ExpectedException(typeof(DuplicateNotAllowedException), ExpectedMessage="Key being added: 'A'")] public void IllegalAdd() { dict.Add("A", "B"); dict.Add("A", "B"); } [Test] [ExpectedException(typeof(NoSuchItemException))] public void GettingNonExisting() { Console.WriteLine(dict["R"]); } [Test] public void Setter() { dict["R"] = "UYGUY"; Assert.AreEqual(dict["R"], "UYGUY"); dict["R"] = "UIII"; Assert.AreEqual(dict["R"], "UIII"); dict["S"] = "VVV"; Assert.AreEqual(dict["R"], "UIII"); Assert.AreEqual(dict["S"], "VVV"); //dict.dump(); } } [TestFixture] public class GuardedSortedDictionaryTest { private GuardedSortedDictionary<string, string> dict; [SetUp] public void Init() { ISortedDictionary<string,string> dict = new TreeDictionary<string, string>(new SC()); dict.Add("A", "1"); dict.Add("C", "2"); dict.Add("E", "3"); this.dict = new GuardedSortedDictionary<string, string>(dict); } [TearDown] public void Dispose() { dict = null; } [Test] public void Pred1() { Assert.AreEqual("1", dict.Predecessor("B").Value); Assert.AreEqual("1", dict.Predecessor("C").Value); Assert.AreEqual("1", dict.WeakPredecessor("B").Value); Assert.AreEqual("2", dict.WeakPredecessor("C").Value); Assert.AreEqual("2", dict.Successor("B").Value); Assert.AreEqual("3", dict.Successor("C").Value); Assert.AreEqual("2", dict.WeakSuccessor("B").Value); Assert.AreEqual("2", dict.WeakSuccessor("C").Value); } [Test] public void Pred2() { KeyValuePair<String, String> res; Assert.IsTrue(dict.TryPredecessor("B", out res)); Assert.AreEqual("1", res.Value); Assert.IsTrue(dict.TryPredecessor("C", out res)); Assert.AreEqual("1", res.Value); Assert.IsTrue(dict.TryWeakPredecessor("B", out res)); Assert.AreEqual("1", res.Value); Assert.IsTrue(dict.TryWeakPredecessor("C", out res)); Assert.AreEqual("2", res.Value); Assert.IsTrue(dict.TrySuccessor("B", out res)); Assert.AreEqual("2", res.Value); Assert.IsTrue(dict.TrySuccessor("C", out res)); Assert.AreEqual("3", res.Value); Assert.IsTrue(dict.TryWeakSuccessor("B", out res)); Assert.AreEqual("2", res.Value); Assert.IsTrue(dict.TryWeakSuccessor("C", out res)); Assert.AreEqual("2", res.Value); Assert.IsFalse(dict.TryPredecessor("A", out res)); Assert.AreEqual(null, res.Key); Assert.AreEqual(null, res.Value); Assert.IsFalse(dict.TryWeakPredecessor("@", out res)); Assert.AreEqual(null, res.Key); Assert.AreEqual(null, res.Value); Assert.IsFalse(dict.TrySuccessor("E", out res)); Assert.AreEqual(null, res.Key); Assert.AreEqual(null, res.Value); Assert.IsFalse(dict.TryWeakSuccessor("F", out res)); Assert.AreEqual(null, res.Key); Assert.AreEqual(null, res.Value); } [Test] public void Initial() { Assert.IsTrue(dict.IsReadOnly); Assert.AreEqual(3, dict.Count); Assert.AreEqual("1", dict["A"]); } [Test] public void Contains() { Assert.IsTrue(dict.Contains("A")); Assert.IsFalse(dict.Contains("1")); } [Test] [ExpectedException(typeof(ReadOnlyCollectionException))] public void IllegalAdd() { dict.Add("Q", "7"); } [Test] [ExpectedException(typeof(ReadOnlyCollectionException))] public void IllegalClear() { dict.Clear(); } [Test] [ExpectedException(typeof(ReadOnlyCollectionException))] public void IllegalSet() { dict["A"] = "8"; } [ExpectedException(typeof(ReadOnlyCollectionException))] public void IllegalRemove() { dict.Remove("A"); } [Test] [ExpectedException(typeof(NoSuchItemException))] public void GettingNonExisting() { Console.WriteLine(dict["R"]); } } [TestFixture] public class Enumerators { private TreeDictionary<string,string> dict; private SCG.IEnumerator<KeyValuePair<string,string>> dictenum; [SetUp] public void Init() { dict = new TreeDictionary<string,string>(new SC()); dict["S"] = "A"; dict["T"] = "B"; dict["R"] = "C"; dictenum = dict.GetEnumerator(); } [TearDown] public void Dispose() { dictenum = null; dict = null; } [Test] public void KeysEnumerator() { SCG.IEnumerator<string> keys = dict.Keys.GetEnumerator(); Assert.AreEqual(3, dict.Keys.Count); Assert.IsTrue(keys.MoveNext()); Assert.AreEqual("R",keys.Current); Assert.IsTrue(keys.MoveNext()); Assert.AreEqual("S",keys.Current); Assert.IsTrue(keys.MoveNext()); Assert.AreEqual("T",keys.Current); Assert.IsFalse(keys.MoveNext()); } [Test] public void KeysISorted() { ISorted<string> keys = dict.Keys; Assert.IsTrue(keys.IsReadOnly); Assert.AreEqual("R", keys.FindMin()); Assert.AreEqual("T", keys.FindMax()); Assert.IsTrue(keys.Contains("S")); Assert.AreEqual(3, keys.Count); // This doesn't hold, maybe because the dict uses a special key comparer? // Assert.IsTrue(keys.SequencedEquals(new WrappedArray<string>(new string[] { "R", "S", "T" }))); Assert.IsTrue(keys.UniqueItems().All(delegate(String s) { return s == "R" || s == "S" || s == "T"; })); Assert.IsTrue(keys.All(delegate(String s) { return s == "R" || s == "S" || s == "T"; })); Assert.IsFalse(keys.Exists(delegate(String s) { return s != "R" && s != "S" && s != "T"; })); String res; Assert.IsTrue(keys.Find(delegate(String s) { return s == "R"; }, out res)); Assert.AreEqual("R", res); Assert.IsFalse(keys.Find(delegate(String s) { return s == "Q"; }, out res)); Assert.AreEqual(null, res); } [Test] public void KeysISortedPred() { ISorted<string> keys = dict.Keys; String res; Assert.IsTrue(keys.TryPredecessor("S", out res)); Assert.AreEqual("R", res); Assert.IsTrue(keys.TryWeakPredecessor("R", out res)); Assert.AreEqual("R", res); Assert.IsTrue(keys.TrySuccessor("S", out res)); Assert.AreEqual("T", res); Assert.IsTrue(keys.TryWeakSuccessor("T", out res)); Assert.AreEqual("T", res); Assert.IsFalse(keys.TryPredecessor("R", out res)); Assert.AreEqual(null, res); Assert.IsFalse(keys.TryWeakPredecessor("P", out res)); Assert.AreEqual(null, res); Assert.IsFalse(keys.TrySuccessor("T", out res)); Assert.AreEqual(null, res); Assert.IsFalse(keys.TryWeakSuccessor("U", out res)); Assert.AreEqual(null, res); Assert.AreEqual("R", keys.Predecessor("S")); Assert.AreEqual("R", keys.WeakPredecessor("R")); Assert.AreEqual("T", keys.Successor("S")); Assert.AreEqual("T", keys.WeakSuccessor("T")); } [Test] public void ValuesEnumerator() { SCG.IEnumerator<string> values = dict.Values.GetEnumerator(); Assert.AreEqual(3, dict.Values.Count); Assert.IsTrue(values.MoveNext()); Assert.AreEqual("C",values.Current); Assert.IsTrue(values.MoveNext()); Assert.AreEqual("A",values.Current); Assert.IsTrue(values.MoveNext()); Assert.AreEqual("B",values.Current); Assert.IsFalse(values.MoveNext()); } [Test] public void Fun() { Assert.AreEqual("B", dict.Fun("T")); } [Test] public void NormalUse() { Assert.IsTrue(dictenum.MoveNext()); Assert.AreEqual(dictenum.Current, new KeyValuePair<string,string>("R", "C")); Assert.IsTrue(dictenum.MoveNext()); Assert.AreEqual(dictenum.Current, new KeyValuePair<string,string>("S", "A")); Assert.IsTrue(dictenum.MoveNext()); Assert.AreEqual(dictenum.Current, new KeyValuePair<string,string>("T", "B")); Assert.IsFalse(dictenum.MoveNext()); } } namespace PathCopyPersistence { [TestFixture] public class Simple { private TreeDictionary<string,string> dict; private TreeDictionary<string,string> snap; [SetUp] public void Init() { dict = new TreeDictionary<string,string>(new SC()); dict["S"] = "A"; dict["T"] = "B"; dict["R"] = "C"; dict["V"] = "G"; snap = (TreeDictionary<string,string>)dict.Snapshot(); } [Test] public void Test() { dict["SS"] = "D"; Assert.AreEqual(5, dict.Count); Assert.AreEqual(4, snap.Count); dict["T"] = "bb"; Assert.AreEqual(5, dict.Count); Assert.AreEqual(4, snap.Count); Assert.AreEqual("B", snap["T"]); Assert.AreEqual("bb", dict["T"]); Assert.IsFalse(dict.IsReadOnly); Assert.IsTrue(snap.IsReadOnly); //Finally, update of root node: TreeDictionary<string,string> snap2 = (TreeDictionary<string,string>)dict.Snapshot(); dict["S"] = "abe"; Assert.AreEqual("abe", dict["S"]); } [Test] [ExpectedException(typeof(ReadOnlyCollectionException))] public void UpdateSnap() { snap["Y"] = "J"; } [TearDown] public void Dispose() { dict = null; snap = null; } } } }
/* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Antlr.Runtime.Debug { using System.Collections.Generic; using System.Collections.ObjectModel; using Antlr.Runtime.Debug.Misc; using Array = System.Array; using CLSCompliantAttribute = System.CLSCompliantAttribute; using Console = System.Console; using DateTime = System.DateTime; using Environment = System.Environment; using Math = System.Math; using StringBuilder = System.Text.StringBuilder; /** <summary>Using the debug event interface, track what is happening in the parser * and record statistics about the runtime. */ public class Profiler : BlankDebugEventListener { public static readonly string DataSeparator = "\t"; public static readonly string NewLine = Environment.NewLine; internal static bool dump = false; /** Because I may change the stats, I need to track that for later * computations to be consistent. */ public static readonly string Version = "3"; public static readonly string RuntimeStatsFilename = "runtime.stats"; /** Ack, should not store parser; can't do remote stuff. Well, we pass * input stream around too so I guess it's ok. */ public DebugParser parser = null; // working variables [CLSCompliant(false)] protected int ruleLevel = 0; //protected int decisionLevel = 0; protected IToken lastRealTokenTouchedInDecision; protected Dictionary<string, bool> uniqueRules = new Dictionary<string, bool>(); protected Stack<string> currentGrammarFileName = new Stack<string>(); protected Stack<string> currentRuleName = new Stack<string>(); protected Stack<int> currentLine = new Stack<int>(); protected Stack<int> currentPos = new Stack<int>(); // Vector<DecisionStats> //protected Vector decisions = new Vector(200); // need setSize protected DoubleKeyMap<string, int, DecisionDescriptor> decisions = new DoubleKeyMap<string, int, DecisionDescriptor>(); // Record a DecisionData for each decision we hit while parsing private List<DecisionEvent> decisionEvents = new List<DecisionEvent>(); protected Stack<DecisionEvent> decisionStack = new Stack<DecisionEvent>(); protected int backtrackDepth; ProfileStats stats = new ProfileStats(); public Profiler() { } public Profiler(DebugParser parser) { this.parser = parser; } public override void EnterRule(string grammarFileName, string ruleName) { //System.out.println("enterRule "+grammarFileName+":"+ruleName); ruleLevel++; stats.numRuleInvocations++; uniqueRules.Add(grammarFileName + ":" + ruleName, true); stats.maxRuleInvocationDepth = Math.Max(stats.maxRuleInvocationDepth, ruleLevel); currentGrammarFileName.Push(grammarFileName); currentRuleName.Push(ruleName); } public override void ExitRule(string grammarFileName, string ruleName) { ruleLevel--; currentGrammarFileName.Pop(); currentRuleName.Pop(); } /** Track memoization; this is not part of standard debug interface * but is triggered by profiling. Code gen inserts an override * for this method in the recognizer, which triggers this method. * Called from alreadyParsedRule(). */ public virtual void ExamineRuleMemoization(IIntStream input, int ruleIndex, int stopIndex, // index or MEMO_RULE_UNKNOWN... string ruleName) { if (dump) Console.WriteLine("examine memo " + ruleName + " at " + input.Index + ": " + stopIndex); if (stopIndex == BaseRecognizer.MemoRuleUnknown) { //System.out.println("rule "+ruleIndex+" missed @ "+input.index()); stats.numMemoizationCacheMisses++; stats.numGuessingRuleInvocations++; // we'll have to enter CurrentDecision().numMemoizationCacheMisses++; } else { // regardless of rule success/failure, if in cache, we have a cache hit //System.out.println("rule "+ruleIndex+" hit @ "+input.index()); stats.numMemoizationCacheHits++; CurrentDecision().numMemoizationCacheHits++; } } /** Warning: doesn't track success/failure, just unique recording event */ public virtual void Memoize(IIntStream input, int ruleIndex, int ruleStartIndex, string ruleName) { // count how many entries go into table if (dump) Console.WriteLine("memoize " + ruleName); stats.numMemoizationCacheEntries++; } public override void Location(int line, int pos) { currentLine.Push(line); currentPos.Push(pos); } public override void EnterDecision(int decisionNumber, bool couldBacktrack) { lastRealTokenTouchedInDecision = null; stats.numDecisionEvents++; int startingLookaheadIndex = parser.TokenStream.Index; ITokenStream input = parser.TokenStream; if (dump) { Console.WriteLine("enterDecision canBacktrack=" + couldBacktrack + " " + decisionNumber + " backtrack depth " + backtrackDepth + " @ " + input.Get(input.Index) + " rule " + LocationDescription()); } string g = currentGrammarFileName.Peek(); DecisionDescriptor descriptor = decisions.Get(g, decisionNumber); if (descriptor == null) { descriptor = new DecisionDescriptor(); decisions.Put(g, decisionNumber, descriptor); descriptor.decision = decisionNumber; descriptor.fileName = currentGrammarFileName.Peek(); descriptor.ruleName = currentRuleName.Peek(); descriptor.line = currentLine.Peek(); descriptor.pos = currentPos.Peek(); descriptor.couldBacktrack = couldBacktrack; } descriptor.n++; DecisionEvent d = new DecisionEvent(); decisionStack.Push(d); d.decision = descriptor; d.startTime = DateTime.Now; d.startIndex = startingLookaheadIndex; } public override void ExitDecision(int decisionNumber) { DecisionEvent d = decisionStack.Pop(); d.stopTime = DateTime.Now; int lastTokenIndex = lastRealTokenTouchedInDecision.TokenIndex; int numHidden = GetNumberOfHiddenTokens(d.startIndex, lastTokenIndex); int depth = lastTokenIndex - d.startIndex - numHidden + 1; // +1 counts consuming start token as 1 d.k = depth; d.decision.maxk = Math.Max(d.decision.maxk, depth); if (dump) { Console.WriteLine("exitDecision " + decisionNumber + " in " + d.decision.ruleName + " lookahead " + d.k + " max token " + lastRealTokenTouchedInDecision); } decisionEvents.Add(d); // done with decision; track all } public override void ConsumeToken(IToken token) { if (dump) Console.WriteLine("consume token " + token); if (!InDecision) { stats.numTokens++; return; } if (lastRealTokenTouchedInDecision == null || lastRealTokenTouchedInDecision.TokenIndex < token.TokenIndex) { lastRealTokenTouchedInDecision = token; } DecisionEvent d = CurrentDecision(); // compute lookahead depth int thisRefIndex = token.TokenIndex; int numHidden = GetNumberOfHiddenTokens(d.startIndex, thisRefIndex); int depth = thisRefIndex - d.startIndex - numHidden + 1; // +1 counts consuming start token as 1 //d.maxk = Math.max(d.maxk, depth); if (dump) { Console.WriteLine("consume " + thisRefIndex + " " + depth + " tokens ahead in " + d.decision.ruleName + "-" + d.decision.decision + " start index " + d.startIndex); } } /** The parser is in a decision if the decision depth > 0. This * works for backtracking also, which can have nested decisions. */ public virtual bool InDecision { get { return decisionStack.Count > 0; } } public override void ConsumeHiddenToken(IToken token) { //System.out.println("consume hidden token "+token); if (!InDecision) stats.numHiddenTokens++; } /** Track refs to lookahead if in a fixed/nonfixed decision. */ public override void LT(int i, IToken t) { if (InDecision && i > 0) { DecisionEvent d = CurrentDecision(); if (dump) { Console.WriteLine("LT(" + i + ")=" + t + " index " + t.TokenIndex + " relative to " + d.decision.ruleName + "-" + d.decision.decision + " start index " + d.startIndex); } if (lastRealTokenTouchedInDecision == null || lastRealTokenTouchedInDecision.TokenIndex < t.TokenIndex) { lastRealTokenTouchedInDecision = t; if (dump) Console.WriteLine("set last token " + lastRealTokenTouchedInDecision); } // get starting index off stack // int stackTop = lookaheadStack.size()-1; // Integer startingIndex = (Integer)lookaheadStack.get(stackTop); // // compute lookahead depth // int thisRefIndex = parser.getTokenStream().index(); // int numHidden = // getNumberOfHiddenTokens(startingIndex.intValue(), thisRefIndex); // int depth = i + thisRefIndex - startingIndex.intValue() - numHidden; // /* // System.out.println("LT("+i+") @ index "+thisRefIndex+" is depth "+depth+ // " max is "+maxLookaheadInCurrentDecision); // */ // if ( depth>maxLookaheadInCurrentDecision ) { // maxLookaheadInCurrentDecision = depth; // } // d.maxk = currentDecision()/ } } /** Track backtracking decisions. You'll see a fixed or cyclic decision * and then a backtrack. * * enter rule * ... * enter decision * LA and possibly consumes (for cyclic DFAs) * begin backtrack level * mark m * rewind m * end backtrack level, success * exit decision * ... * exit rule */ public override void BeginBacktrack(int level) { if (dump) Console.WriteLine("enter backtrack " + level); backtrackDepth++; DecisionEvent e = CurrentDecision(); if (e.decision.couldBacktrack) { stats.numBacktrackOccurrences++; e.decision.numBacktrackOccurrences++; e.backtracks = true; } } /** Successful or not, track how much lookahead synpreds use */ public override void EndBacktrack(int level, bool successful) { if (dump) Console.WriteLine("exit backtrack " + level + ": " + successful); backtrackDepth--; } public override void Mark(int i) { if (dump) Console.WriteLine("mark " + i); } public override void Rewind(int i) { if (dump) Console.WriteLine("rewind " + i); } public override void Rewind() { if (dump) Console.WriteLine("rewind"); } protected virtual DecisionEvent CurrentDecision() { return decisionStack.Peek(); } public override void RecognitionException(RecognitionException e) { stats.numReportedErrors++; } public override void SemanticPredicate(bool result, string predicate) { stats.numSemanticPredicates++; if (InDecision) { DecisionEvent d = CurrentDecision(); d.evalSemPred = true; d.decision.numSemPredEvals++; if (dump) { Console.WriteLine("eval " + predicate + " in " + d.decision.ruleName + "-" + d.decision.decision); } } } public override void Terminate() { foreach (DecisionEvent e in decisionEvents) { //System.out.println("decision "+e.decision.decision+": k="+e.k); e.decision.avgk += e.k; stats.avgkPerDecisionEvent += e.k; if (e.backtracks) { // doesn't count gated syn preds on DFA edges stats.avgkPerBacktrackingDecisionEvent += e.k; } } stats.averageDecisionPercentBacktracks = 0.0f; foreach (DecisionDescriptor d in decisions.Values()) { stats.numDecisionsCovered++; d.avgk /= (float)d.n; if (d.couldBacktrack) { stats.numDecisionsThatPotentiallyBacktrack++; float percentBacktracks = d.numBacktrackOccurrences / (float)d.n; //System.out.println("dec "+d.decision+" backtracks "+percentBacktracks*100+"%"); stats.averageDecisionPercentBacktracks += percentBacktracks; } // ignore rules that backtrack along gated DFA edges if (d.numBacktrackOccurrences > 0) { stats.numDecisionsThatDoBacktrack++; } } stats.averageDecisionPercentBacktracks /= stats.numDecisionsThatPotentiallyBacktrack; stats.averageDecisionPercentBacktracks *= 100; // it's a percentage stats.avgkPerDecisionEvent /= stats.numDecisionEvents; stats.avgkPerBacktrackingDecisionEvent /= (float)stats.numBacktrackOccurrences; Console.Error.WriteLine(ToString()); Console.Error.WriteLine(GetDecisionStatsDump()); // String stats = toNotifyString(); // try { // Stats.writeReport(RUNTIME_STATS_FILENAME,stats); // } // catch (IOException ioe) { // System.err.println(ioe); // ioe.printStackTrace(System.err); // } } public virtual void SetParser(DebugParser parser) { this.parser = parser; } // R E P O R T I N G public virtual string ToNotifyString() { StringBuilder buf = new StringBuilder(); buf.Append(Version); buf.Append('\t'); buf.Append(parser.GetType().Name); // buf.Append('\t'); // buf.Append(numRuleInvocations); // buf.Append('\t'); // buf.Append(maxRuleInvocationDepth); // buf.Append('\t'); // buf.Append(numFixedDecisions); // buf.Append('\t'); // buf.Append(Stats.min(decisionMaxFixedLookaheads)); // buf.Append('\t'); // buf.Append(Stats.max(decisionMaxFixedLookaheads)); // buf.Append('\t'); // buf.Append(Stats.avg(decisionMaxFixedLookaheads)); // buf.Append('\t'); // buf.Append(Stats.stddev(decisionMaxFixedLookaheads)); // buf.Append('\t'); // buf.Append(numCyclicDecisions); // buf.Append('\t'); // buf.Append(Stats.min(decisionMaxCyclicLookaheads)); // buf.Append('\t'); // buf.Append(Stats.max(decisionMaxCyclicLookaheads)); // buf.Append('\t'); // buf.Append(Stats.avg(decisionMaxCyclicLookaheads)); // buf.Append('\t'); // buf.Append(Stats.stddev(decisionMaxCyclicLookaheads)); // buf.Append('\t'); // buf.Append(numBacktrackDecisions); // buf.Append('\t'); // buf.Append(Stats.min(toArray(decisionMaxSynPredLookaheads))); // buf.Append('\t'); // buf.Append(Stats.max(toArray(decisionMaxSynPredLookaheads))); // buf.Append('\t'); // buf.Append(Stats.avg(toArray(decisionMaxSynPredLookaheads))); // buf.Append('\t'); // buf.Append(Stats.stddev(toArray(decisionMaxSynPredLookaheads))); // buf.Append('\t'); // buf.Append(numSemanticPredicates); // buf.Append('\t'); // buf.Append(parser.getTokenStream().size()); // buf.Append('\t'); // buf.Append(numHiddenTokens); // buf.Append('\t'); // buf.Append(numCharsMatched); // buf.Append('\t'); // buf.Append(numHiddenCharsMatched); // buf.Append('\t'); // buf.Append(numberReportedErrors); // buf.Append('\t'); // buf.Append(numMemoizationCacheHits); // buf.Append('\t'); // buf.Append(numMemoizationCacheMisses); // buf.Append('\t'); // buf.Append(numGuessingRuleInvocations); // buf.Append('\t'); // buf.Append(numMemoizationCacheEntries); return buf.ToString(); } public override string ToString() { return ToString(GetReport()); } public virtual ProfileStats GetReport() { //ITokenStream input = parser.TokenStream; //for (int i = 0; i < input.Count && lastRealTokenTouchedInDecision != null && i <= lastRealTokenTouchedInDecision.TokenIndex; i++) //{ // IToken t = input.Get(i); // if (t.Channel != TokenChannels.Default) // { // stats.numHiddenTokens++; // stats.numHiddenCharsMatched += t.Text.Length; // } //} stats.Version = Version; stats.name = parser.GetType().Name; stats.numUniqueRulesInvoked = uniqueRules.Count; //stats.numCharsMatched = lastTokenConsumed.getStopIndex() + 1; return stats; } public virtual DoubleKeyMap<string, int, DecisionDescriptor> GetDecisionStats() { return decisions; } public virtual ReadOnlyCollection<DecisionEvent> DecisionEvents { get { return decisionEvents.AsReadOnly(); } } public static string ToString(ProfileStats stats) { StringBuilder buf = new StringBuilder(); buf.Append("ANTLR Runtime Report; Profile Version "); buf.Append(stats.Version); buf.Append(NewLine); buf.Append("parser name "); buf.Append(stats.name); buf.Append(NewLine); buf.Append("Number of rule invocations "); buf.Append(stats.numRuleInvocations); buf.Append(NewLine); buf.Append("Number of unique rules visited "); buf.Append(stats.numUniqueRulesInvoked); buf.Append(NewLine); buf.Append("Number of decision events "); buf.Append(stats.numDecisionEvents); buf.Append(NewLine); buf.Append("Number of rule invocations while backtracking "); buf.Append(stats.numGuessingRuleInvocations); buf.Append(NewLine); buf.Append("max rule invocation nesting depth "); buf.Append(stats.maxRuleInvocationDepth); buf.Append(NewLine); // buf.Append("number of fixed lookahead decisions "); // buf.Append(); // buf.Append(newline); // buf.Append("min lookahead used in a fixed lookahead decision "); // buf.Append(); // buf.Append(newline); // buf.Append("max lookahead used in a fixed lookahead decision "); // buf.Append(); // buf.Append(newline); // buf.Append("average lookahead depth used in fixed lookahead decisions "); // buf.Append(); // buf.Append(newline); // buf.Append("standard deviation of depth used in fixed lookahead decisions "); // buf.Append(); // buf.Append(newline); // buf.Append("number of arbitrary lookahead decisions "); // buf.Append(); // buf.Append(newline); // buf.Append("min lookahead used in an arbitrary lookahead decision "); // buf.Append(); // buf.Append(newline); // buf.Append("max lookahead used in an arbitrary lookahead decision "); // buf.Append(); // buf.Append(newline); // buf.Append("average lookahead depth used in arbitrary lookahead decisions "); // buf.Append(); // buf.Append(newline); // buf.Append("standard deviation of depth used in arbitrary lookahead decisions "); // buf.Append(); // buf.Append(newline); // buf.Append("number of evaluated syntactic predicates "); // buf.Append(); // buf.Append(newline); // buf.Append("min lookahead used in a syntactic predicate "); // buf.Append(); // buf.Append(newline); // buf.Append("max lookahead used in a syntactic predicate "); // buf.Append(); // buf.Append(newline); // buf.Append("average lookahead depth used in syntactic predicates "); // buf.Append(); // buf.Append(newline); // buf.Append("standard deviation of depth used in syntactic predicates "); // buf.Append(); // buf.Append(newline); buf.Append("rule memoization cache size "); buf.Append(stats.numMemoizationCacheEntries); buf.Append(NewLine); buf.Append("number of rule memoization cache hits "); buf.Append(stats.numMemoizationCacheHits); buf.Append(NewLine); buf.Append("number of rule memoization cache misses "); buf.Append(stats.numMemoizationCacheMisses); buf.Append(NewLine); // buf.Append("number of evaluated semantic predicates "); // buf.Append(); // buf.Append(newline); buf.Append("number of tokens "); buf.Append(stats.numTokens); buf.Append(NewLine); buf.Append("number of hidden tokens "); buf.Append(stats.numHiddenTokens); buf.Append(NewLine); buf.Append("number of char "); buf.Append(stats.numCharsMatched); buf.Append(NewLine); buf.Append("number of hidden char "); buf.Append(stats.numHiddenCharsMatched); buf.Append(NewLine); buf.Append("number of syntax errors "); buf.Append(stats.numReportedErrors); buf.Append(NewLine); return buf.ToString(); } public virtual string GetDecisionStatsDump() { StringBuilder buf = new StringBuilder(); buf.Append("location"); buf.Append(DataSeparator); buf.Append("n"); buf.Append(DataSeparator); buf.Append("avgk"); buf.Append(DataSeparator); buf.Append("maxk"); buf.Append(DataSeparator); buf.Append("synpred"); buf.Append(DataSeparator); buf.Append("sempred"); buf.Append(DataSeparator); buf.Append("canbacktrack"); buf.Append("\n"); foreach (string fileName in decisions.KeySet()) { foreach (int d in decisions.KeySet(fileName)) { DecisionDescriptor s = decisions.Get(fileName, d); buf.Append(s.decision); buf.Append("@"); buf.Append(LocationDescription(s.fileName, s.ruleName, s.line, s.pos)); // decision number buf.Append(DataSeparator); buf.Append(s.n); buf.Append(DataSeparator); buf.Append(string.Format("{0}", s.avgk)); buf.Append(DataSeparator); buf.Append(s.maxk); buf.Append(DataSeparator); buf.Append(s.numBacktrackOccurrences); buf.Append(DataSeparator); buf.Append(s.numSemPredEvals); buf.Append(DataSeparator); buf.Append(s.couldBacktrack ? "1" : "0"); buf.Append(NewLine); } } return buf.ToString(); } protected virtual int[] Trim(int[] X, int n) { if (n < X.Length) { int[] trimmed = new int[n]; Array.Copy(X, 0, trimmed, 0, n); X = trimmed; } return X; } /** Get num hidden tokens between i..j inclusive */ public virtual int GetNumberOfHiddenTokens(int i, int j) { int n = 0; ITokenStream input = parser.TokenStream; for (int ti = i; ti < input.Count && ti <= j; ti++) { IToken t = input.Get(ti); if (t.Channel != TokenChannels.Default) { n++; } } return n; } protected virtual string LocationDescription() { return LocationDescription( currentGrammarFileName.Peek(), currentRuleName.Peek(), currentLine.Peek(), currentPos.Peek()); } protected virtual string LocationDescription(string file, string rule, int line, int pos) { return file + ":" + line + ":" + pos + "(" + rule + ")"; } public class ProfileStats { public string Version; public string name; public int numRuleInvocations; public int numUniqueRulesInvoked; public int numDecisionEvents; public int numDecisionsCovered; public int numDecisionsThatPotentiallyBacktrack; public int numDecisionsThatDoBacktrack; public int maxRuleInvocationDepth; public float avgkPerDecisionEvent; public float avgkPerBacktrackingDecisionEvent; public float averageDecisionPercentBacktracks; public int numBacktrackOccurrences; // doesn't count gated DFA edges public int numFixedDecisions; public int minDecisionMaxFixedLookaheads; public int maxDecisionMaxFixedLookaheads; public int avgDecisionMaxFixedLookaheads; public int stddevDecisionMaxFixedLookaheads; public int numCyclicDecisions; public int minDecisionMaxCyclicLookaheads; public int maxDecisionMaxCyclicLookaheads; public int avgDecisionMaxCyclicLookaheads; public int stddevDecisionMaxCyclicLookaheads; // int Stats.min(toArray(decisionMaxSynPredLookaheads); // int Stats.max(toArray(decisionMaxSynPredLookaheads); // int Stats.avg(toArray(decisionMaxSynPredLookaheads); // int Stats.stddev(toArray(decisionMaxSynPredLookaheads); public int numSemanticPredicates; public int numTokens; public int numHiddenTokens; public int numCharsMatched; public int numHiddenCharsMatched; public int numReportedErrors; public int numMemoizationCacheHits; public int numMemoizationCacheMisses; public int numGuessingRuleInvocations; public int numMemoizationCacheEntries; } public class DecisionDescriptor { public int decision; public string fileName; public string ruleName; public int line; public int pos; public bool couldBacktrack; public int n; public float avgk; // avg across all decision events public int maxk; public int numBacktrackOccurrences; public int numSemPredEvals; } // all about a specific exec of a single decision public class DecisionEvent { public DecisionDescriptor decision; public int startIndex; public int k; public bool backtracks; // doesn't count gated DFA edges public bool evalSemPred; public DateTime startTime; public DateTime stopTime; public int numMemoizationCacheHits; public int numMemoizationCacheMisses; } } }
// // 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. // #if !SILVERLIGHT namespace NLog.UnitTests { using System; using System.IO; using System.Threading; using System.Reflection; using Xunit; using NLog.Config; public class LogFactoryTests : NLogTestBase { [Fact] public void Flush_DoNotThrowExceptionsAndTimeout_DoesNotThrow() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='false'> <targets><target type='MethodCall' name='test' methodName='Throws' className='NLog.UnitTests.LogFactoryTests, NLog.UnitTests.netfx40' /></targets> <rules> <logger name='*' minlevel='Debug' writeto='test'></logger> </rules> </nlog>"); ILogger logger = LogManager.GetCurrentClassLogger(); logger.Factory.Flush(_ => { }, TimeSpan.FromMilliseconds(1)); } [Fact] public void InvalidXMLConfiguration_DoesNotThrowErrorWhen_ThrowExceptionFlagIsNotSet() { Boolean ExceptionThrown = false; try { LogManager.ThrowExceptions = false; LogManager.Configuration = CreateConfigurationFromString(@" <nlog internalLogToConsole='IamNotBooleanValue'> <targets><target type='MethodCall' name='test' methodName='Throws' className='NLog.UnitTests.LogFactoryTests, NLog.UnitTests.netfx40' /></targets> <rules> <logger name='*' minlevel='Debug' writeto='test'></logger> </rules> </nlog>"); } catch (Exception) { ExceptionThrown = true; } Assert.False(ExceptionThrown); } [Fact] public void InvalidXMLConfiguration_ThrowErrorWhen_ThrowExceptionFlagIsSet() { Boolean ExceptionThrown = false; try { LogManager.ThrowExceptions = true; LogManager.Configuration = CreateConfigurationFromString(@" <nlog internalLogToConsole='IamNotBooleanValue'> <targets><target type='MethodCall' name='test' methodName='Throws' className='NLog.UnitTests.LogFactoryTests, NLog.UnitTests.netfx40' /></targets> <rules> <logger name='*' minlevel='Debug' writeto='test'></logger> </rules> </nlog>"); } catch (Exception) { ExceptionThrown = true; } Assert.True(ExceptionThrown); } [Fact] public void SecondaryLogFactoryDoesNotTakePrimaryLogFactoryLock() { File.WriteAllText("NLog.config", "<nlog />"); try { bool threadTerminated; var primaryLogFactory = typeof(LogManager).GetField("factory", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null); var primaryLogFactoryLock = typeof(LogFactory).GetField("syncRoot", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(primaryLogFactory); // Simulate a potential deadlock. // If the creation of the new LogFactory takes the lock of the global LogFactory, the thread will deadlock. lock (primaryLogFactoryLock) { var thread = new Thread(() => { (new LogFactory()).GetCurrentClassLogger(); }); thread.Start(); threadTerminated = thread.Join(TimeSpan.FromSeconds(1)); } Assert.True(threadTerminated); } finally { try { File.Delete("NLog.config"); } catch { } } } [Fact] public void ReloadConfigOnTimer_DoesNotThrowConfigException_IfConfigChangedInBetween() { var loggingConfiguration = new LoggingConfiguration(); LogManager.Configuration = loggingConfiguration; var logFactory = new LogFactory(loggingConfiguration); var differentConfiguration = new LoggingConfiguration(); Assert.DoesNotThrow(() => logFactory.ReloadConfigOnTimer(differentConfiguration)); } private class ReloadNullConfiguration : LoggingConfiguration { public override LoggingConfiguration Reload() { return null; } } [Fact] public void ReloadConfigOnTimer_DoesNotThrowConfigException_IfConfigReloadReturnsNull() { var loggingConfiguration = new ReloadNullConfiguration(); LogManager.Configuration = loggingConfiguration; var logFactory = new LogFactory(loggingConfiguration); Assert.DoesNotThrow(() => logFactory.ReloadConfigOnTimer(loggingConfiguration)); } [Fact] public void ReloadConfigOnTimer_Raises_ConfigurationReloadedEvent() { var called = false; var loggingConfiguration = new LoggingConfiguration(); LogManager.Configuration = loggingConfiguration; var logFactory = new LogFactory(loggingConfiguration); logFactory.ConfigurationReloaded += (sender, args) => { called = true; }; logFactory.ReloadConfigOnTimer(loggingConfiguration); Assert.True(called); } [Fact] public void ReloadConfigOnTimer_When_No_Exception_Raises_ConfigurationReloadedEvent_With_Correct_Sender() { object calledBy = null; var loggingConfiguration = new LoggingConfiguration(); LogManager.Configuration = loggingConfiguration; var logFactory = new LogFactory(loggingConfiguration); logFactory.ConfigurationReloaded += (sender, args) => { calledBy = sender; }; logFactory.ReloadConfigOnTimer(loggingConfiguration); Assert.Same(calledBy, logFactory); } [Fact] public void ReloadConfigOnTimer_When_No_Exception_Raises_ConfigurationReloadedEvent_With_Argument_Indicating_Success() { LoggingConfigurationReloadedEventArgs arguments = null; var loggingConfiguration = new LoggingConfiguration(); LogManager.Configuration = loggingConfiguration; var logFactory = new LogFactory(loggingConfiguration); logFactory.ConfigurationReloaded += (sender, args) => { arguments = args; }; logFactory.ReloadConfigOnTimer(loggingConfiguration); Assert.True(arguments.Succeeded); } public static void Throws() { throw new Exception(); } /// <summary> /// We should be forward compatible so that we can add easily attributes in the future. /// </summary> [Fact] public void NewAttrOnNLogLevelShouldNotThrowError() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true' imAnewAttribute='noError'> <targets><target type='file' name='f1' filename='test.log' /></targets> <rules> <logger name='*' minlevel='Debug' writeto='f1'></logger> </rules> </nlog>"); } [Fact] public void EnableAndDisableLogging() { LogFactory factory = new LogFactory(); #pragma warning disable 618 // In order Suspend => Resume Assert.True(factory.IsLoggingEnabled()); factory.DisableLogging(); Assert.False(factory.IsLoggingEnabled()); factory.EnableLogging(); Assert.True(factory.IsLoggingEnabled()); #pragma warning restore 618 } [Fact] public void SuspendAndResumeLogging_InOrder() { LogFactory factory = new LogFactory(); // In order Suspend => Resume [Case 1] Assert.True(factory.IsLoggingEnabled()); factory.SuspendLogging(); Assert.False(factory.IsLoggingEnabled()); factory.ResumeLogging(); Assert.True(factory.IsLoggingEnabled()); // In order Suspend => Resume [Case 2] using (var factory2 = new LogFactory()) { Assert.True(factory.IsLoggingEnabled()); factory.SuspendLogging(); Assert.False(factory.IsLoggingEnabled()); factory.ResumeLogging(); Assert.True(factory.IsLoggingEnabled()); } } [Fact] public void SuspendAndResumeLogging_OutOfOrder() { LogFactory factory = new LogFactory(); // Out of order Resume => Suspend => (Suspend => Resume) factory.ResumeLogging(); Assert.True(factory.IsLoggingEnabled()); factory.SuspendLogging(); Assert.True(factory.IsLoggingEnabled()); factory.SuspendLogging(); Assert.False(factory.IsLoggingEnabled()); factory.ResumeLogging(); Assert.True(factory.IsLoggingEnabled()); } } } #endif
// Licensed to the Apache Software Foundation(ASF) under one // or more contributor license agreements.See the NOTICE file // distributed with this work for additional information // regarding copyright ownership.The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace Thrift.Transport.Client { // ReSharper disable once InconsistentNaming public class THttpTransport : TEndpointTransport { private readonly X509Certificate[] _certificates; private readonly Uri _uri; private int _connectTimeout = 30000; // Timeouts in milliseconds private HttpClient _httpClient; private Stream _inputStream; private MemoryStream _outputStream = new MemoryStream(); private bool _isDisposed; public THttpTransport(Uri uri, TConfiguration config, IDictionary<string, string> customRequestHeaders = null, string userAgent = null) : this(uri, config, Enumerable.Empty<X509Certificate>(), customRequestHeaders, userAgent) { } public THttpTransport(Uri uri, TConfiguration config, IEnumerable<X509Certificate> certificates, IDictionary<string, string> customRequestHeaders, string userAgent = null) : base(config) { _uri = uri; _certificates = (certificates ?? Enumerable.Empty<X509Certificate>()).ToArray(); if (!string.IsNullOrEmpty(userAgent)) UserAgent = userAgent; // due to current bug with performance of Dispose in netcore https://github.com/dotnet/corefx/issues/8809 // this can be switched to default way (create client->use->dispose per flush) later _httpClient = CreateClient(customRequestHeaders); ConfigureClient(_httpClient); } /// <summary> /// Constructor that takes a <c>HttpClient</c> instance to support using <c>IHttpClientFactory</c>. /// </summary> /// <remarks>As the <c>HttpMessageHandler</c> of the client must be configured at the time of creation, it /// is assumed that the consumer has already added any certificates and configured decompression methods. The /// consumer can use the <c>CreateHttpClientHandler</c> method to get a handler with these set.</remarks> /// <param name="httpClient">Client configured with the desired message handler, user agent, and URI if not /// specified in the <c>uri</c> parameter. A default user agent will be used if not set.</param> /// <param name="config">Thrift configuration object</param> /// <param name="uri">Optional URI to use for requests, if not specified the base address of <c>httpClient</c> /// is used.</param> public THttpTransport(HttpClient httpClient, TConfiguration config, Uri uri = null) : base(config) { _httpClient = httpClient; _uri = uri ?? httpClient.BaseAddress; httpClient.BaseAddress = _uri; var userAgent = _httpClient.DefaultRequestHeaders.UserAgent.ToString(); if (!string.IsNullOrEmpty(userAgent)) UserAgent = userAgent; ConfigureClient(_httpClient); } // According to RFC 2616 section 3.8, the "User-Agent" header may not carry a version number public readonly string UserAgent = "Thrift netstd THttpClient"; public override bool IsOpen => true; public HttpRequestHeaders RequestHeaders => _httpClient.DefaultRequestHeaders; public MediaTypeHeaderValue ContentType { get; set; } public override Task OpenAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public override void Close() { if (_inputStream != null) { _inputStream.Dispose(); _inputStream = null; } if (_outputStream != null) { _outputStream.Dispose(); _outputStream = null; } if (_httpClient != null) { _httpClient.Dispose(); _httpClient = null; } } public override async ValueTask<int> ReadAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (_inputStream == null) throw new TTransportException(TTransportException.ExceptionType.NotOpen, "No request has been sent"); CheckReadBytesAvailable(length); try { #if NETSTANDARD2_1 var ret = await _inputStream.ReadAsync(new Memory<byte>(buffer, offset, length), cancellationToken); #else var ret = await _inputStream.ReadAsync(buffer, offset, length, cancellationToken); #endif if (ret == -1) { throw new TTransportException(TTransportException.ExceptionType.EndOfFile, "No more data available"); } CountConsumedMessageBytes(ret); return ret; } catch (IOException iox) { throw new TTransportException(TTransportException.ExceptionType.Unknown, iox.ToString()); } } public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); await _outputStream.WriteAsync(buffer, offset, length, cancellationToken); } /// <summary> /// Get a client handler configured with recommended properties to use with the <c>HttpClient</c> constructor /// and an <c>IHttpClientFactory</c>. /// </summary> /// <param name="certificates">An optional array of client certificates to associate with the handler.</param> /// <returns> /// A client handler with deflate and gZip compression-decompression algorithms and any client /// certificates passed in via <c>certificates</c>. /// </returns> public virtual HttpClientHandler CreateHttpClientHandler(X509Certificate[] certificates = null) { var handler = new HttpClientHandler(); if (certificates != null) handler.ClientCertificates.AddRange(certificates); handler.AutomaticDecompression = System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip; return handler; } private HttpClient CreateClient(IDictionary<string, string> customRequestHeaders) { var handler = CreateHttpClientHandler(_certificates); var httpClient = new HttpClient(handler); if (customRequestHeaders != null) { foreach (var item in customRequestHeaders) { httpClient.DefaultRequestHeaders.Add(item.Key, item.Value); } } return httpClient; } private void ConfigureClient(HttpClient httpClient) { if (_connectTimeout > 0) { httpClient.Timeout = TimeSpan.FromMilliseconds(_connectTimeout); } httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-thrift")); // Clear any user agent values to avoid drift with the field value httpClient.DefaultRequestHeaders.UserAgent.Clear(); httpClient.DefaultRequestHeaders.UserAgent.TryParseAdd(UserAgent); httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate")); httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); } public override async Task FlushAsync(CancellationToken cancellationToken) { try { _outputStream.Seek(0, SeekOrigin.Begin); using (var contentStream = new StreamContent(_outputStream)) { contentStream.Headers.ContentType = ContentType ?? new MediaTypeHeaderValue(@"application/x-thrift"); var response = (await _httpClient.PostAsync(_uri, contentStream, cancellationToken)).EnsureSuccessStatusCode(); _inputStream?.Dispose(); _inputStream = await response.Content.ReadAsStreamAsync(); if (_inputStream.CanSeek) { _inputStream.Seek(0, SeekOrigin.Begin); } } } catch (IOException iox) { throw new TTransportException(TTransportException.ExceptionType.Unknown, iox.ToString()); } catch (HttpRequestException wx) { throw new TTransportException(TTransportException.ExceptionType.Unknown, "Couldn't connect to server: " + wx); } catch (Exception ex) { throw new TTransportException(TTransportException.ExceptionType.Unknown, ex.Message); } finally { _outputStream = new MemoryStream(); ResetConsumedMessageSize(); } } // IDisposable protected override void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { _inputStream?.Dispose(); _outputStream?.Dispose(); _httpClient?.Dispose(); } } _isDisposed = true; } } }
/* 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 AboutDialog { /// <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(AboutDialog)); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.m_versionLabel = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.linkLabel1 = new System.Windows.Forms.LinkLabel(); this.linkLabel2 = new System.Windows.Forms.LinkLabel(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.linkLabel4 = new System.Windows.Forms.LinkLabel(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.linkLabel3 = new System.Windows.Forms.LinkLabel(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(188, 9); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(52, 13); this.label1.TabIndex = 1; this.label1.Text = "Trizbort"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(188, 25); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(133, 13); this.label2.TabIndex = 2; this.label2.Text = "Interactive Fiction Mapper"; // // m_versionLabel // this.m_versionLabel.AutoSize = true; this.m_versionLabel.Location = new System.Drawing.Point(188, 53); this.m_versionLabel.Name = "m_versionLabel"; this.m_versionLabel.Size = new System.Drawing.Size(89, 13); this.m_versionLabel.TabIndex = 3; this.m_versionLabel.Text = "Version Unknown"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(188, 75); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(74, 13); this.label4.TabIndex = 4; this.label4.Text = "By Genstein"; // // linkLabel1 // this.linkLabel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.linkLabel1.LinkArea = new System.Windows.Forms.LinkArea(80, 16); this.linkLabel1.Location = new System.Drawing.Point(191, 275); this.linkLabel1.Name = "linkLabel1"; this.linkLabel1.Size = new System.Drawing.Size(309, 30); this.linkLabel1.TabIndex = 6; this.linkLabel1.TabStop = true; this.linkLabel1.Text = "Uses PDFsharp, copyright (c) 2005-2007 empira Software GmbH, Cologne (Germany), w" + "ww.pdfsharp.com\r\n"; this.linkLabel1.UseCompatibleTextRendering = true; this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.OnLinkClicked); // // linkLabel2 // this.linkLabel2.AutoSize = true; this.linkLabel2.Location = new System.Drawing.Point(188, 145); this.linkLabel2.Name = "linkLabel2"; this.linkLabel2.Size = new System.Drawing.Size(107, 13); this.linkLabel2.TabIndex = 8; this.linkLabel2.TabStop = true; this.linkLabel2.Text = "trizbort.genstein.net"; this.linkLabel2.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.OnLinkClicked); // // pictureBox1 // this.pictureBox1.Image = global::Trizbort.Properties.Resources.Wizard4; this.pictureBox1.Location = new System.Drawing.Point(0, 0); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(165, 314); this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; // // linkLabel4 // this.linkLabel4.AutoSize = true; this.linkLabel4.Location = new System.Drawing.Point(188, 88); this.linkLabel4.Name = "linkLabel4"; this.linkLabel4.Size = new System.Drawing.Size(144, 13); this.linkLabel4.TabIndex = 10; this.linkLabel4.TabStop = true; this.linkLabel4.Text = "github.com/genstein/trizbort"; this.linkLabel4.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.OnLinkClicked); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(191, 161); this.textBox1.Multiline = true; this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textBox1.Size = new System.Drawing.Size(309, 111); this.textBox1.TabIndex = 11; this.textBox1.Text = resources.GetString("textBox1.Text"); // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(188, 108); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(226, 13); this.label3.TabIndex = 12; this.label3.Text = "Enhancements by Jason Lautzenheiser"; // // linkLabel3 // this.linkLabel3.AutoSize = true; this.linkLabel3.Location = new System.Drawing.Point(188, 121); this.linkLabel3.Name = "linkLabel3"; this.linkLabel3.Size = new System.Drawing.Size(198, 13); this.linkLabel3.TabIndex = 13; this.linkLabel3.TabStop = true; this.linkLabel3.Text = "github.com/JasonLautzenheiser/trizbort"; this.linkLabel3.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.OnLinkClicked); // // AboutDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(512, 314); this.Controls.Add(this.linkLabel3); this.Controls.Add(this.label3); this.Controls.Add(this.textBox1); this.Controls.Add(this.linkLabel4); this.Controls.Add(this.linkLabel2); this.Controls.Add(this.linkLabel1); this.Controls.Add(this.label4); this.Controls.Add(this.m_versionLabel); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.pictureBox1); 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 = "AboutDialog"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "About"; ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label m_versionLabel; private System.Windows.Forms.Label label4; private System.Windows.Forms.LinkLabel linkLabel1; private System.Windows.Forms.LinkLabel linkLabel2; private System.Windows.Forms.LinkLabel linkLabel4; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label3; private System.Windows.Forms.LinkLabel linkLabel3; } }
// 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 Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal sealed partial class ExpressionBinder { // ---------------------------------------------------------------------------- // BindExplicitConversion // ---------------------------------------------------------------------------- private sealed class ExplicitConversion { private readonly ExpressionBinder _binder; private Expr _exprSrc; private readonly CType _typeSrc; private readonly CType _typeDest; private readonly ExprClass _exprTypeDest; // This is for lambda error reporting. The reason we have this is because we // store errors for lambda conversions, and then we don't bind the conversion // again to report errors. Consider the following case: // // int? x = () => null; // // When we try to convert the lambda to the nullable type int?, we first // attempt the conversion to int. If that fails, then we know there is no // conversion to int?, since int is a predef type. We then look for UserDefined // conversions, and fail. When we report the errors, we ask the lambda for its // conversion errors. But since we attempted its conversion to int and not int?, // we report the wrong error. This field is to keep track of the right type // to report the error on, so that when the lambda conversion fails, it reports // errors on the correct type. private readonly CType _pDestinationTypeForLambdaErrorReporting; private Expr _exprDest; private readonly bool _needsExprDest; private readonly CONVERTTYPE _flags; // ---------------------------------------------------------------------------- // BindExplicitConversion // ---------------------------------------------------------------------------- public ExplicitConversion(ExpressionBinder binder, Expr exprSrc, CType typeSrc, ExprClass typeDest, CType pDestinationTypeForLambdaErrorReporting, bool needsExprDest, CONVERTTYPE flags) { _binder = binder; _exprSrc = exprSrc; _typeSrc = typeSrc; _typeDest = typeDest.Type; _pDestinationTypeForLambdaErrorReporting = pDestinationTypeForLambdaErrorReporting; _exprTypeDest = typeDest; _needsExprDest = needsExprDest; _flags = flags; _exprDest = null; } public Expr ExprDest { get { return _exprDest; } } /* * BindExplicitConversion * * This is a complex routine with complex parameter. Generally, this should * be called through one of the helper methods that insulates you * from the complexity of the interface. This routine handles all the logic * associated with explicit conversions. * * Note that this function calls BindImplicitConversion first, so the main * logic is only concerned with conversions that can be made explicitly, but * not implicitly. */ public bool Bind() { // To test for a standard conversion, call canConvert(exprSrc, typeDest, STANDARDANDCONVERTTYPE.NOUDC) and // canConvert(typeDest, typeSrc, STANDARDANDCONVERTTYPE.NOUDC). Debug.Assert((_flags & CONVERTTYPE.STANDARD) == 0); // 13.2 Explicit conversions // // The following conversions are classified as explicit conversions: // // * All implicit conversions // * Explicit numeric conversions // * Explicit enumeration conversions // * Explicit reference conversions // * Explicit interface conversions // * Unboxing conversions // * Explicit type parameter conversions // * User-defined explicit conversions // * Explicit nullable conversions // * Lifted user-defined explicit conversions // // Explicit conversions can occur in cast expressions (14.6.6). // // The explicit conversions that are not implicit conversions are conversions that cannot be // proven always to succeed, conversions that are known possibly to lose information, and // conversions across domains of types sufficiently different to merit explicit notation. // The set of explicit conversions includes all implicit conversions. // Don't try user-defined conversions now because we'll try them again later. if (_binder.BindImplicitConversion(_exprSrc, _typeSrc, _exprTypeDest, _pDestinationTypeForLambdaErrorReporting, _needsExprDest, out _exprDest, _flags | CONVERTTYPE.ISEXPLICIT)) { return true; } if (_typeSrc == null || _typeDest == null || _typeSrc is ErrorType || _typeDest is ErrorType || _typeDest.IsNeverSameType()) { return false; } if (_typeDest is NullableType) { // This is handled completely by BindImplicitConversion. return false; } if (_typeSrc is NullableType) { return bindExplicitConversionFromNub(); } if (bindExplicitConversionFromArrayToIList()) { return true; } // if we were casting an integral constant to another constant type, // then, if the constant were in range, then the above call would have succeeded. // But it failed, and so we know that the constant is not in range switch (_typeDest.GetTypeKind()) { default: Debug.Fail($"Bad type kind: {_typeDest.GetTypeKind()}"); return false; case TypeKind.TK_VoidType: return false; // Can't convert to a method group or anon method. case TypeKind.TK_NullType: return false; // Can never convert TO the null type. case TypeKind.TK_ArrayType: if (bindExplicitConversionToArray((ArrayType)_typeDest)) { return true; } break; case TypeKind.TK_PointerType: if (bindExplicitConversionToPointer()) { return true; } break; case TypeKind.TK_AggregateType: { AggCastResult result = bindExplicitConversionToAggregate(_typeDest as AggregateType); if (result == AggCastResult.Success) { return true; } if (result == AggCastResult.Abort) { return false; } break; } } // No built-in conversion was found. Maybe a user-defined conversion? if (0 == (_flags & CONVERTTYPE.NOUDC)) { return _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, false); } return false; } private bool bindExplicitConversionFromNub() { Debug.Assert(_typeSrc != null); Debug.Assert(_typeDest != null); // If S and T are value types and there is a builtin conversion from S => T then there is an // explicit conversion from S? => T that throws on null. if (_typeDest.IsValType() && _binder.BindExplicitConversion(null, _typeSrc.StripNubs(), _exprTypeDest, _pDestinationTypeForLambdaErrorReporting, _flags | CONVERTTYPE.NOUDC)) { if (_needsExprDest) { Expr valueSrc = _exprSrc; if (valueSrc.Type is NullableType) { valueSrc = _binder.BindNubValue(valueSrc); } Debug.Assert(valueSrc.Type == _typeSrc.StripNubs()); if (!_binder.BindExplicitConversion(valueSrc, valueSrc.Type, _exprTypeDest, _pDestinationTypeForLambdaErrorReporting, _needsExprDest, out _exprDest, _flags | CONVERTTYPE.NOUDC)) { Debug.Fail("BindExplicitConversion failed unexpectedly"); return false; } if (_exprDest is ExprUserDefinedConversion udc) { udc.Argument = _exprSrc; } } return true; } if ((_flags & CONVERTTYPE.NOUDC) == 0) { return _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, false); } return false; } private bool bindExplicitConversionFromArrayToIList() { // 13.2.2 // // The explicit reference conversions are: // // * From a one-dimensional array-type S[] to System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> and // their base interfaces, provided there is an explicit reference conversion from S to T. Debug.Assert(_typeSrc != null); Debug.Assert(_typeDest != null); if (!(_typeSrc is ArrayType arrSrc) || !arrSrc.IsSZArray || !(_typeDest is AggregateType aggDest) || !aggDest.isInterfaceType() || aggDest.GetTypeArgsAll().Count != 1) { return false; } AggregateSymbol aggIList = GetSymbolLoader().GetPredefAgg(PredefinedType.PT_G_ILIST); AggregateSymbol aggIReadOnlyList = GetSymbolLoader().GetPredefAgg(PredefinedType.PT_G_IREADONLYLIST); if ((aggIList == null || !GetSymbolLoader().IsBaseAggregate(aggIList, aggDest.getAggregate())) && (aggIReadOnlyList == null || !GetSymbolLoader().IsBaseAggregate(aggIReadOnlyList, aggDest.getAggregate()))) { return false; } CType typeArr = arrSrc.GetElementType(); CType typeLst = aggDest.GetTypeArgsAll()[0]; if (!CConversions.FExpRefConv(GetSymbolLoader(), typeArr, typeLst)) { return false; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } private bool bindExplicitConversionFromIListToArray(ArrayType arrayDest) { // 13.2.2 // // The explicit reference conversions are: // // * From System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> and their base interfaces // to a one-dimensional array-type S[], provided there is an implicit or explicit reference conversion from // S[] to System.Collections.Generic.IList<T> or System.Collections.Generic.IReadOnlyList<T>. This is precisely when either S and T // are the same type or there is an implicit or explicit reference conversion from S to T. if (!arrayDest.IsSZArray || !(_typeSrc is AggregateType aggSrc) || !aggSrc.isInterfaceType() || aggSrc.GetTypeArgsAll().Count != 1) { return false; } AggregateSymbol aggIList = GetSymbolLoader().GetPredefAgg(PredefinedType.PT_G_ILIST); AggregateSymbol aggIReadOnlyList = GetSymbolLoader().GetPredefAgg(PredefinedType.PT_G_IREADONLYLIST); if ((aggIList == null || !GetSymbolLoader().IsBaseAggregate(aggIList, aggSrc.getAggregate())) && (aggIReadOnlyList == null || !GetSymbolLoader().IsBaseAggregate(aggIReadOnlyList, aggSrc.getAggregate()))) { return false; } CType typeArr = arrayDest.GetElementType(); CType typeLst = aggSrc.GetTypeArgsAll()[0]; Debug.Assert(!typeArr.IsNeverSameType()); if (typeArr != typeLst && !CConversions.FExpRefConv(GetSymbolLoader(), typeArr, typeLst)) { return false; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } private bool bindExplicitConversionFromArrayToArray(ArrayType arraySrc, ArrayType arrayDest) { // 13.2.2 // // The explicit reference conversions are: // // * From an array-type S with an element type SE to an array-type T with an element type // TE, provided all of the following are true: // // * S and T differ only in element type. (In other words, S and T have the same number // of dimensions.) // // * An explicit reference conversion exists from SE to TE. if (arraySrc.rank != arrayDest.rank || arraySrc.IsSZArray != arrayDest.IsSZArray) { return false; // Ranks do not match. } if (CConversions.FExpRefConv(GetSymbolLoader(), arraySrc.GetElementType(), arrayDest.GetElementType())) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } return false; } private bool bindExplicitConversionToArray(ArrayType arrayDest) { Debug.Assert(_typeSrc != null); Debug.Assert(arrayDest != null); if (_typeSrc is ArrayType arrSrc) { return bindExplicitConversionFromArrayToArray(arrSrc, arrayDest); } if (bindExplicitConversionFromIListToArray(arrayDest)) { return true; } // 13.2.2 // // The explicit reference conversions are: // // * From System.Array and the interfaces it implements, to any array-type. if (_binder.canConvert(_binder.GetPredefindType(PredefinedType.PT_ARRAY), _typeSrc, CONVERTTYPE.NOUDC)) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } return false; } private bool bindExplicitConversionToPointer() { // 27.4 Pointer conversions // // in an unsafe context, the set of available explicit conversions (13.2) is extended to // include the following explicit pointer conversions: // // * From any pointer-type to any other pointer-type. // * From sbyte, byte, short, ushort, int, uint, long, or ulong to any pointer-type. if (_typeSrc is PointerType || _typeSrc.fundType() <= FUNDTYPE.FT_LASTINTEGRAL && _typeSrc.isNumericType()) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return true; } return false; } // 13.2.2 Explicit enumeration conversions // // The explicit enumeration conversions are: // // * From sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or // decimal to any enum-type. // // * From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, char, // float, double, or decimal. // // * From any enum-type to any other enum-type. // // * An explicit enumeration conversion between two types is processed by treating any // participating enum-type as the underlying type of that enum-type, and then performing // an implicit or explicit numeric conversion between the resulting types. private AggCastResult bindExplicitConversionFromEnumToAggregate(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); if (!_typeSrc.isEnumType()) { return AggCastResult.Failure; } AggregateSymbol aggDest = aggTypeDest.getAggregate(); if (aggDest.isPredefAgg(PredefinedType.PT_DECIMAL)) { return bindExplicitConversionFromEnumToDecimal(aggTypeDest); } if (!aggDest.getThisType().isNumericType() && !aggDest.IsEnum() && !(aggDest.IsPredefined() && aggDest.GetPredefType() == PredefinedType.PT_CHAR)) { return AggCastResult.Failure; } if (_exprSrc.GetConst() != null) { ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; } else if (result == ConstCastResult.CheckFailure) { return AggCastResult.Abort; } } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return AggCastResult.Success; } private AggCastResult bindExplicitConversionFromDecimalToEnum(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(_typeSrc.isPredefType(PredefinedType.PT_DECIMAL)); // There is an explicit conversion from decimal to all integral types. if (_exprSrc.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; // else, don't fold and use a regular cast, below. } if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW)) { return AggCastResult.Abort; } } // All casts from decimal to integer types are bound as user-defined conversions. bool bIsConversionOK = true; if (_needsExprDest) { // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the CONVERTTYPE.NOUDC flag here. CType underlyingType = aggTypeDest.underlyingType(); bIsConversionOK = _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, underlyingType, _needsExprDest, out _exprDest, false); if (bIsConversionOK) { // upcast to the Enum type _binder.bindSimpleCast(_exprDest, _exprTypeDest, out _exprDest); } } return bIsConversionOK ? AggCastResult.Success : AggCastResult.Failure; } private AggCastResult bindExplicitConversionFromEnumToDecimal(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); Debug.Assert(aggTypeDest.isPredefType(PredefinedType.PT_DECIMAL)); AggregateType underlyingType = _typeSrc.underlyingType() as AggregateType; // Need to first cast the source expr to its underlying type. Expr exprCast; if (_exprSrc == null) { exprCast = null; } else { ExprClass underlyingExpr = GetExprFactory().CreateClass(underlyingType); _binder.bindSimpleCast(_exprSrc, underlyingExpr, out exprCast); } // There is always an implicit conversion from any integral type to decimal. if (exprCast.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(exprCast, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; // else, don't fold and use a regular cast, below. } if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW)) { return AggCastResult.Abort; } } // Conversions from integral types to decimal are always bound as a user-defined conversion. if (_needsExprDest) { // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the CONVERTTYPE.NOUDC flag here. bool ok = _binder.bindUserDefinedConversion(exprCast, underlyingType, aggTypeDest, _needsExprDest, out _exprDest, false); Debug.Assert(ok); } return AggCastResult.Success; } private AggCastResult bindExplicitConversionToEnum(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); AggregateSymbol aggDest = aggTypeDest.getAggregate(); if (!aggDest.IsEnum()) { return AggCastResult.Failure; } if (_typeSrc.isPredefType(PredefinedType.PT_DECIMAL)) { return bindExplicitConversionFromDecimalToEnum(aggTypeDest); } if (_typeSrc.isNumericType() || (_typeSrc.isPredefined() && _typeSrc.getPredefType() == PredefinedType.PT_CHAR)) { // Transform constant to constant. if (_exprSrc.GetConst() != null) { ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; } if (result == ConstCastResult.CheckFailure) { return AggCastResult.Abort; } } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return AggCastResult.Success; } else if (_typeSrc.isPredefined() && (_typeSrc.isPredefType(PredefinedType.PT_OBJECT) || _typeSrc.isPredefType(PredefinedType.PT_VALUE) || _typeSrc.isPredefType(PredefinedType.PT_ENUM))) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_UNBOX); return AggCastResult.Success; } return AggCastResult.Failure; } private AggCastResult bindExplicitConversionBetweenSimpleTypes(AggregateType aggTypeDest) { // 13.2.1 // // Because the explicit conversions include all implicit and explicit numeric conversions, // it is always possible to convert from any numeric-type to any other numeric-type using // a cast expression (14.6.6). Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); if (!_typeSrc.isSimpleType() || !aggTypeDest.isSimpleType()) { return AggCastResult.Failure; } AggregateSymbol aggDest = aggTypeDest.getAggregate(); Debug.Assert(_typeSrc.isPredefined() && aggDest.IsPredefined()); PredefinedType ptSrc = _typeSrc.getPredefType(); PredefinedType ptDest = aggDest.GetPredefType(); Debug.Assert((int)ptSrc < NUM_SIMPLE_TYPES && (int)ptDest < NUM_SIMPLE_TYPES); ConvKind convertKind = GetConvKind(ptSrc, ptDest); // Identity and implicit conversions should already have been handled. Debug.Assert(convertKind != ConvKind.Implicit); Debug.Assert(convertKind != ConvKind.Identity); if (convertKind != ConvKind.Explicit) { return AggCastResult.Failure; } if (_exprSrc.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; // else, don't fold and use a regular cast, below. } if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW)) { return AggCastResult.Abort; } } bool bConversionOk = true; if (_needsExprDest) { // Explicit conversions involving decimals are bound as user-defined conversions. if (isUserDefinedConversion(ptSrc, ptDest)) { // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the CONVERTTYPE.NOUDC flag here. bConversionOk = _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, aggTypeDest, _needsExprDest, out _exprDest, false); } else { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, (_flags & CONVERTTYPE.CHECKOVERFLOW) != 0 ? EXPRFLAG.EXF_CHECKOVERFLOW : 0); } } return bConversionOk ? AggCastResult.Success : AggCastResult.Failure; } private AggCastResult bindExplicitConversionBetweenAggregates(AggregateType aggTypeDest) { // 13.2.3 // // The explicit reference conversions are: // // * From object to any reference-type. // * From any class-type S to any class-type T, provided S is a base class of T. // * From any class-type S to any interface-type T, provided S is not sealed and // provided S does not implement T. // * From any interface-type S to any class-type T, provided T is not sealed or provided // T implements S. // * From any interface-type S to any interface-type T, provided S is not derived from T. Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); if (!(_typeSrc is AggregateType atSrc)) { return AggCastResult.Failure; } AggregateSymbol aggSrc = atSrc.getAggregate(); AggregateSymbol aggDest = aggTypeDest.getAggregate(); if (GetSymbolLoader().HasBaseConversion(aggTypeDest, atSrc)) { if (_needsExprDest) { if (aggDest.IsValueType() && aggSrc.getThisType().fundType() == FUNDTYPE.FT_REF) { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_UNBOX); } else { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK | (_exprSrc?.Flags & EXPRFLAG.EXF_CANTBENULL ?? 0)); } } return AggCastResult.Success; } if ((aggSrc.IsClass() && !aggSrc.IsSealed() && aggDest.IsInterface()) || (aggSrc.IsInterface() && aggDest.IsClass() && !aggDest.IsSealed()) || (aggSrc.IsInterface() && aggDest.IsInterface()) || CConversions.HasGenericDelegateExplicitReferenceConversion(GetSymbolLoader(), _typeSrc, aggTypeDest)) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK | (_exprSrc?.Flags & EXPRFLAG.EXF_CANTBENULL ?? 0)); return AggCastResult.Success; } return AggCastResult.Failure; } private AggCastResult bindExplicitConversionFromPointerToInt(AggregateType aggTypeDest) { // 27.4 Pointer conversions // in an unsafe context, the set of available explicit conversions (13.2) is extended to include // the following explicit pointer conversions: // // * From any pointer-type to sbyte, byte, short, ushort, int, uint, long, or ulong. if (!(_typeSrc is PointerType) || aggTypeDest.fundType() > FUNDTYPE.FT_LASTINTEGRAL || !aggTypeDest.isNumericType()) { return AggCastResult.Failure; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return AggCastResult.Success; } private AggCastResult bindExplicitConversionToAggregate(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); AggCastResult result = bindExplicitConversionFromEnumToAggregate(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionToEnum(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionBetweenSimpleTypes(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionBetweenAggregates(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionFromPointerToInt(aggTypeDest); if (result != AggCastResult.Failure) { return result; } if (_typeSrc is VoidType) { // No conversion is allowed to or from a void type (user defined or otherwise) // This is most likely the result of a failed anonymous method or member group conversion return AggCastResult.Abort; } return AggCastResult.Failure; } private SymbolLoader GetSymbolLoader() { return _binder.GetSymbolLoader(); } private ExprFactory GetExprFactory() { return _binder.GetExprFactory(); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using NDesk.Options; using Sep.Git.Tfs.Core; using StructureMap; using Sep.Git.Tfs.Util; using Sep.Git.Tfs.Core.TfsInterop; namespace Sep.Git.Tfs.Commands { public class InitBranch : GitTfsCommand { private readonly TextWriter _stdout; private readonly Globals _globals; private readonly Help _helper; private readonly AuthorsFile _authors; private RemoteOptions _remoteOptions; public string TfsUsername { get; set; } public string TfsPassword { get; set; } public string IgnoreRegex { get; set; } public string ExceptRegex { get; set; } public string ParentBranch { get; set; } public bool CloneAllBranches { get; set; } public bool NoFetch { get; set; } public bool DontCreateGitBranch { get; set; } public IGitTfsRemote RemoteCreated { get; private set; } public InitBranch(TextWriter stdout, Globals globals, Help helper, AuthorsFile authors) { _stdout = stdout; _globals = globals; _helper = helper; _authors = authors; } public OptionSet OptionSet { get { return new OptionSet { { "all", "Clone all the TFS branches (For TFS 2010 and later)", v => CloneAllBranches = (v.ToLower() == "all") }, { "b|tfs-parent-branch=", "TFS Parent branch of the TFS branch to clone (TFS 2008 only! And required!!) ex: $/Repository/ProjectParentBranch", v => ParentBranch = v }, { "u|username=", "TFS username", v => TfsUsername = v }, { "p|password=", "TFS password", v => TfsPassword = v }, { "ignore-regex=", "A regex of files to ignore", v => IgnoreRegex = v }, { "except-regex=", "A regex of exceptions to ignore-regex", v => ExceptRegex = v}, { "no-fetch", "Create the new TFS remote but don't fetch any changesets", v => NoFetch = (v != null) } }; } } public int Run() { return Run(null, null); } public int Run(string tfsBranchPath) { return Run(tfsBranchPath, null); } public int Run(string tfsBranchPath, string gitBranchNameExpected) { if (!CloneAllBranches && tfsBranchPath == null) { _helper.Run(this); return GitTfsExitCodes.Help; } if (CloneAllBranches) { // TODO: Remove this! //Debugger.Launch(); return CloneAll(tfsBranchPath); } else { return CloneBranch(tfsBranchPath, gitBranchNameExpected); } } private int CloneBranch(string tfsBranchPath, string gitBranchNameExpected) { var defaultRemote = InitFromDefaultRemote(); // TFS representations of repository paths do not have trailing slashes tfsBranchPath = (tfsBranchPath ?? string.Empty).TrimEnd('/'); if (!tfsBranchPath.IsValidTfsPath()) { var remotes = _globals.Repository.GetLastParentTfsCommits(tfsBranchPath); if (!remotes.Any()) { throw new Exception("error: No TFS branch found!"); } tfsBranchPath = remotes.First().Remote.TfsRepositoryPath; } tfsBranchPath.AssertValidTfsPath(); var allRemotes = _globals.Repository.ReadAllTfsRemotes(); var remote = allRemotes.FirstOrDefault(r => r.TfsRepositoryPath.ToLower() == tfsBranchPath.ToLower()); if (remote != null && remote.MaxChangesetId != 0) { _stdout.WriteLine("warning : There is already a remote for this tfs branch. Branch ignored!"); return GitTfsExitCodes.InvalidArguments; } IList<RootBranch> creationBranchData; if (ParentBranch == null) creationBranchData = defaultRemote.Tfs.GetRootChangesetForBranch(tfsBranchPath); else { var tfsRepositoryPathParentBranchFound = allRemotes.FirstOrDefault(r => r.TfsRepositoryPath.ToLower() == ParentBranch.ToLower()); if (tfsRepositoryPathParentBranchFound == null) throw new GitTfsException("error: The Tfs parent branch '" + ParentBranch + "' can not be found in the Git repository\nPlease init it first and try again...\n"); creationBranchData = defaultRemote.Tfs.GetRootChangesetForBranch(tfsBranchPath, -1, tfsRepositoryPathParentBranchFound.TfsRepositoryPath); } IFetchResult fetchResult; InitBranchSupportingRename(tfsBranchPath, gitBranchNameExpected, creationBranchData, defaultRemote, out fetchResult); return GitTfsExitCodes.OK; } private IGitTfsRemote InitBranchSupportingRename(string tfsBranchPath, string gitBranchNameExpected, IList<RootBranch> creationBranchData, IGitTfsRemote defaultRemote, out IFetchResult fetchResult) { fetchResult = null; RemoveAlreadyFetchedBranches(creationBranchData, defaultRemote); _stdout.WriteLine("Branches to Initialize successively :"); foreach (var branch in creationBranchData) { var outputMessage = "-" + branch.TfsBranchPath + " (Source C" + branch.SourceBranchChangesetId; if (branch.TargetBranchChangesetId > -1) outputMessage += " -> Target C" + branch.TargetBranchChangesetId; outputMessage += ")"; _stdout.WriteLine("-" + outputMessage); } IGitTfsRemote branchTfsRemote = null; var remoteToDelete = new List<IGitTfsRemote>(); foreach (var rootBranch in creationBranchData) { Trace.WriteLine("Processing " + (rootBranch.IsRenamedBranch ? "renamed " : string.Empty) + "branch :" + rootBranch.TfsBranchPath + " (" + rootBranch.SourceBranchChangesetId + ")"); var cbd = new BranchCreationDatas { RootChangesetId = rootBranch.SourceBranchChangesetId, TfsRepositoryPath = rootBranch.TfsBranchPath }; if (cbd.TfsRepositoryPath == tfsBranchPath) cbd.GitBranchNameExpected = gitBranchNameExpected; branchTfsRemote = defaultRemote.InitBranch(_remoteOptions, cbd.TfsRepositoryPath, cbd.RootChangesetId, !NoFetch, cbd.GitBranchNameExpected, fetchResult); if (branchTfsRemote == null) throw new GitTfsException("error: Couldn't fetch parent branch\n"); // If this branch's branch point is past the first commit, indicate this so Fetch can start from that point if (rootBranch.TargetBranchChangesetId > -1) branchTfsRemote.InitialChangeset = rootBranch.TargetBranchChangesetId; if (rootBranch.IsRenamedBranch || !NoFetch) { fetchResult = FetchRemote(branchTfsRemote, false, !DontCreateGitBranch && !rootBranch.IsRenamedBranch, fetchResult, rootBranch.TargetBranchChangesetId); if(fetchResult.IsSuccess && rootBranch.IsRenamedBranch) remoteToDelete.Add(branchTfsRemote); } else Trace.WriteLine("Not fetching changesets, --no-fetch option specified"); } foreach (var gitTfsRemote in remoteToDelete) { _globals.Repository.DeleteTfsRemote(gitTfsRemote); } return RemoteCreated = branchTfsRemote; } private static void RemoveAlreadyFetchedBranches(IList<RootBranch> creationBranchData, IGitTfsRemote defaultRemote) { for (int i = creationBranchData.Count - 1; i > 0; i--) { var branch = creationBranchData[i]; if (defaultRemote.Repository.FindCommitHashByChangesetId(branch.SourceBranchChangesetId) != null) { for (int j = 0; j < i; j++) { creationBranchData.RemoveAt(0); } break; } } } class BranchCreationDatas { public string TfsRepositoryPath { get; set; } public string GitBranchNameExpected { get; set; } public int RootChangesetId { get; set; } } [DebuggerDisplay("{TfsRepositoryPath} C{RootChangesetId}")] class BranchDatas { public string TfsRepositoryPath { get; set; } public IGitTfsRemote TfsRemote { get; set; } public bool IsEntirelyFetched { get; set; } public int RootChangesetId { get; set; } public IList<RootBranch> CreationBranchData { get; set; } public Exception Error { get; set; } } private int CloneAll(string gitRemote) { if (CloneAllBranches && NoFetch) throw new GitTfsException("error: --no-fetch cannot be used with --all"); _globals.Repository.SetConfig(GitTfsConstants.IgnoreBranches, false.ToString()); var defaultRemote = InitFromDefaultRemote(); List<BranchDatas> childBranchesToInit; if (gitRemote == null) { childBranchesToInit = GetChildBranchesToInit(defaultRemote); } else { var gitRepositoryBranchRemotes = defaultRemote.Repository.GetGitRepositoryBranchRemotes(gitRemote); var childBranchPaths = new Dictionary<string, BranchDatas>(); foreach (var branchRemote in gitRepositoryBranchRemotes) { var branchRemoteChangesetInfos = _globals.Repository.GetLastParentTfsCommits(branchRemote); var firstRemoteChangesetInfo = branchRemoteChangesetInfos.FirstOrDefault(); if (firstRemoteChangesetInfo == null) continue; var branchRemoteTfsPath = firstRemoteChangesetInfo.Remote.TfsRepositoryPath; if (!childBranchPaths.ContainsKey(branchRemoteTfsPath)) childBranchPaths.Add(branchRemoteTfsPath, new BranchDatas { TfsRepositoryPath = branchRemoteTfsPath }); } childBranchesToInit = childBranchPaths.Values.ToList(); } if (!childBranchesToInit.Any()) _stdout.WriteLine("No other Tfs branches found."); else InitializeBranches(defaultRemote, childBranchesToInit); return GitTfsExitCodes.OK; } private static List<BranchDatas> GetChildBranchesToInit(IGitTfsRemote defaultRemote) { var rootBranch = defaultRemote.Tfs.GetRootTfsBranchForRemotePath(defaultRemote.TfsRepositoryPath); if (rootBranch == null) throw new GitTfsException("error: The use of the option '--branches=all' to init all the branches is only possible when 'git tfs clone' was done from the trunk!!! '" + defaultRemote.TfsRepositoryPath + "' is not a TFS branch!"); return rootBranch.GetAllChildrenOfBranch(defaultRemote.TfsRepositoryPath).Select(b => new BranchDatas { TfsRepositoryPath = b.Path }).ToList(); } private void InitializeBranches(IGitTfsRemote defaultRemote, List<BranchDatas> childBranchPaths) { _stdout.WriteLine("Tfs branches found:"); var branchesToProcess = new List<BranchDatas>(); foreach (var childBranchPath in childBranchPaths) { _stdout.WriteLine("- " + childBranchPath.TfsRepositoryPath); var branchDatas = new BranchDatas { TfsRepositoryPath = childBranchPath.TfsRepositoryPath, TfsRemote = _globals.Repository.ReadAllTfsRemotes().FirstOrDefault(r => r.TfsRepositoryPath == childBranchPath.TfsRepositoryPath) }; try { branchDatas.CreationBranchData = defaultRemote.Tfs.GetRootChangesetForBranch(childBranchPath.TfsRepositoryPath); } catch (Exception ex) { branchDatas.Error = ex; } branchesToProcess.Add(branchDatas); } branchesToProcess.Add(new BranchDatas { TfsRepositoryPath = defaultRemote.TfsRepositoryPath, TfsRemote = defaultRemote, RootChangesetId = -1 }); bool isSomethingDone; do { isSomethingDone = false; var branchesToFetch = branchesToProcess.Where(b => !b.IsEntirelyFetched && b.Error == null).ToList(); foreach (var tfsBranch in branchesToFetch) { _stdout.WriteLine("=> Working on TFS branch : " + tfsBranch.TfsRepositoryPath); if (tfsBranch.TfsRemote == null || tfsBranch.TfsRemote.MaxChangesetId == 0) { try { IFetchResult fetchResult; tfsBranch.TfsRemote = InitBranchSupportingRename(tfsBranch.TfsRepositoryPath, null, tfsBranch.CreationBranchData, defaultRemote, out fetchResult); if (tfsBranch.TfsRemote != null) { tfsBranch.IsEntirelyFetched = fetchResult.IsSuccess; isSomethingDone = true; } } catch (Exception ex) { _stdout.WriteLine("error: an error occurs when initializing the branch. Branch is ignored and continuing..."); tfsBranch.Error = ex; } } else { try { var lastFetchedChangesetId = tfsBranch.TfsRemote.MaxChangesetId; Trace.WriteLine("Fetching remote :" + tfsBranch.TfsRemote.Id); var fetchResult = FetchRemote(tfsBranch.TfsRemote, true); tfsBranch.IsEntirelyFetched = fetchResult.IsSuccess; if (fetchResult.NewChangesetCount != 0) isSomethingDone = true; } catch (Exception ex) { _stdout.WriteLine("error: an error occurs when fetching changeset. Fetching is stopped and continuing..."); tfsBranch.Error = ex; } } } } while (branchesToProcess.Any(b => !b.IsEntirelyFetched && b.Error == null) && isSomethingDone); _globals.Repository.GarbageCollect(); if (branchesToProcess.Any(b => !b.IsEntirelyFetched)) { _stdout.WriteLine("warning: Some Tfs branches could not have been initialized:"); foreach (var branchNotInited in branchesToProcess.Where(b => !b.IsEntirelyFetched)) { _stdout.WriteLine("- " + branchNotInited.TfsRepositoryPath); } _stdout.WriteLine("\nPlease report this case to the git-tfs developers! (report here : https://github.com/git-tfs/git-tfs/issues/461 )"); } if (branchesToProcess.Any(b => b.Error != null)) { _stdout.WriteLine("warning: Some Tfs branches could not have been initialized or entirely fetched due to errors:"); foreach (var branchWithErrors in branchesToProcess.Where(b => b.Error != null)) { _stdout.WriteLine("- " + branchWithErrors.TfsRepositoryPath); if (_globals.DebugOutput) Trace.WriteLine(" =>error:" + branchWithErrors.Error); else _stdout.WriteLine(" =>error:" + branchWithErrors.Error.Message); } _stdout.WriteLine("\nPlease report this case to the git-tfs developers! (report here : https://github.com/git-tfs/git-tfs/issues )"); } } private IGitTfsRemote InitFromDefaultRemote() { IGitTfsRemote defaultRemote; if (_globals.Repository.HasRemote(GitTfsConstants.DefaultRepositoryId)) defaultRemote = _globals.Repository.ReadTfsRemote(GitTfsConstants.DefaultRepositoryId); else defaultRemote = _globals.Repository.ReadAllTfsRemotes() .Where(x => x != null && x.RemoteInfo != null && !string.IsNullOrEmpty(x.RemoteInfo.Url)) .OrderBy(x => x.RemoteInfo.Url.Length).FirstOrDefault(); if (defaultRemote == null) throw new GitTfsException("error: No git-tfs repository found. Please try to clone first...\n"); _remoteOptions = new RemoteOptions(); if (!string.IsNullOrWhiteSpace(TfsUsername)) { _remoteOptions.Username = TfsUsername; _remoteOptions.Password = TfsPassword; } else { _remoteOptions.Username = defaultRemote.TfsUsername; _remoteOptions.Password = defaultRemote.TfsPassword; } if (IgnoreRegex != null) _remoteOptions.IgnoreRegex = IgnoreRegex; else _remoteOptions.IgnoreRegex = defaultRemote.IgnoreRegexExpression; if (ExceptRegex != null) _remoteOptions.ExceptRegex = ExceptRegex; else _remoteOptions.ExceptRegex = defaultRemote.IgnoreExceptRegexExpression; return defaultRemote; } /// <summary> /// Fetch changesets from the given remote, optionally stopping on failed merge commits. /// This will default to creating a local Git branch (createBranch = true) and starting from the earliest possible changeset in the given remote (startingChangesetId = -1) - /// both options may be overridden. /// </summary> /// <param name="tfsRemote"></param> /// <param name="stopOnFailMergeCommit"></param> /// <param name="createBranch"></param> /// <param name="renameResult"></param> /// <param name="startingChangesetId"></param> /// <returns></returns> private IFetchResult FetchRemote(IGitTfsRemote tfsRemote, bool stopOnFailMergeCommit, bool createBranch = true, IRenameResult renameResult = null, int startingChangesetId = -1) { try { Trace.WriteLine("Try fetching changesets..."); var fetchResult = tfsRemote.Fetch(stopOnFailMergeCommit, renameResult: renameResult); Trace.WriteLine("Changesets fetched!"); if (fetchResult.IsSuccess && createBranch && tfsRemote.Id != GitTfsConstants.DefaultRepositoryId) { Trace.WriteLine("Try creating the local branch..."); var branchRef = tfsRemote.Id.ToLocalGitRef(); if (!_globals.Repository.HasRef(branchRef)) { if (!_globals.Repository.CreateBranch(branchRef, tfsRemote.MaxCommitHash)) _stdout.WriteLine("warning: Fail to create local branch ref file!"); else Trace.WriteLine("Local branch created!"); } else { _stdout.WriteLine("info: local branch ref already exists!"); } } return fetchResult; } finally { Trace.WriteLine("Cleaning..."); tfsRemote.CleanupWorkspaceDirectory(); } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the RisEstudioItemDesaprobado class. /// </summary> [Serializable] public partial class RisEstudioItemDesaprobadoCollection : ActiveList<RisEstudioItemDesaprobado, RisEstudioItemDesaprobadoCollection> { public RisEstudioItemDesaprobadoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>RisEstudioItemDesaprobadoCollection</returns> public RisEstudioItemDesaprobadoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { RisEstudioItemDesaprobado o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the RIS_EstudioItemDesaprobado table. /// </summary> [Serializable] public partial class RisEstudioItemDesaprobado : ActiveRecord<RisEstudioItemDesaprobado>, IActiveRecord { #region .ctors and Default Settings public RisEstudioItemDesaprobado() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public RisEstudioItemDesaprobado(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public RisEstudioItemDesaprobado(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public RisEstudioItemDesaprobado(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("RIS_EstudioItemDesaprobado", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdEstudioItemDesarpobado = new TableSchema.TableColumn(schema); colvarIdEstudioItemDesarpobado.ColumnName = "idEstudioItemDesarpobado"; colvarIdEstudioItemDesarpobado.DataType = DbType.Int32; colvarIdEstudioItemDesarpobado.MaxLength = 0; colvarIdEstudioItemDesarpobado.AutoIncrement = true; colvarIdEstudioItemDesarpobado.IsNullable = false; colvarIdEstudioItemDesarpobado.IsPrimaryKey = true; colvarIdEstudioItemDesarpobado.IsForeignKey = false; colvarIdEstudioItemDesarpobado.IsReadOnly = false; colvarIdEstudioItemDesarpobado.DefaultSetting = @""; colvarIdEstudioItemDesarpobado.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEstudioItemDesarpobado); TableSchema.TableColumn colvarIdEstudio = new TableSchema.TableColumn(schema); colvarIdEstudio.ColumnName = "idEstudio"; colvarIdEstudio.DataType = DbType.Int32; colvarIdEstudio.MaxLength = 0; colvarIdEstudio.AutoIncrement = false; colvarIdEstudio.IsNullable = false; colvarIdEstudio.IsPrimaryKey = false; colvarIdEstudio.IsForeignKey = false; colvarIdEstudio.IsReadOnly = false; colvarIdEstudio.DefaultSetting = @""; colvarIdEstudio.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEstudio); TableSchema.TableColumn colvarIdItemDesaprobado = new TableSchema.TableColumn(schema); colvarIdItemDesaprobado.ColumnName = "idItemDesaprobado"; colvarIdItemDesaprobado.DataType = DbType.Int32; colvarIdItemDesaprobado.MaxLength = 0; colvarIdItemDesaprobado.AutoIncrement = false; colvarIdItemDesaprobado.IsNullable = false; colvarIdItemDesaprobado.IsPrimaryKey = false; colvarIdItemDesaprobado.IsForeignKey = false; colvarIdItemDesaprobado.IsReadOnly = false; colvarIdItemDesaprobado.DefaultSetting = @""; colvarIdItemDesaprobado.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdItemDesaprobado); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("RIS_EstudioItemDesaprobado",schema); } } #endregion #region Props [XmlAttribute("IdEstudioItemDesarpobado")] [Bindable(true)] public int IdEstudioItemDesarpobado { get { return GetColumnValue<int>(Columns.IdEstudioItemDesarpobado); } set { SetColumnValue(Columns.IdEstudioItemDesarpobado, value); } } [XmlAttribute("IdEstudio")] [Bindable(true)] public int IdEstudio { get { return GetColumnValue<int>(Columns.IdEstudio); } set { SetColumnValue(Columns.IdEstudio, value); } } [XmlAttribute("IdItemDesaprobado")] [Bindable(true)] public int IdItemDesaprobado { get { return GetColumnValue<int>(Columns.IdItemDesaprobado); } set { SetColumnValue(Columns.IdItemDesaprobado, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdEstudio,int varIdItemDesaprobado) { RisEstudioItemDesaprobado item = new RisEstudioItemDesaprobado(); item.IdEstudio = varIdEstudio; item.IdItemDesaprobado = varIdItemDesaprobado; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdEstudioItemDesarpobado,int varIdEstudio,int varIdItemDesaprobado) { RisEstudioItemDesaprobado item = new RisEstudioItemDesaprobado(); item.IdEstudioItemDesarpobado = varIdEstudioItemDesarpobado; item.IdEstudio = varIdEstudio; item.IdItemDesaprobado = varIdItemDesaprobado; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdEstudioItemDesarpobadoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdEstudioColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdItemDesaprobadoColumn { get { return Schema.Columns[2]; } } #endregion #region Columns Struct public struct Columns { public static string IdEstudioItemDesarpobado = @"idEstudioItemDesarpobado"; public static string IdEstudio = @"idEstudio"; public static string IdItemDesaprobado = @"idItemDesaprobado"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using FunWithSqlServer.Data; namespace FunWithSqlServer.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("00000000000000_CreateIdentitySchema")] partial class CreateIdentitySchema { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.0.2"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.HasIndex("UserId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("FunWithSqlServer.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.HasOne("FunWithSqlServer.Models.ApplicationUser") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.HasOne("FunWithSqlServer.Models.ApplicationUser") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany("Users") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("FunWithSqlServer.Models.ApplicationUser") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
using Lucene.Net.Util; using System; using System.Collections.Generic; using System.IO; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Analysis { /* * 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. */ /// <summary> /// An <see cref="Analyzer"/> builds <see cref="Analysis.TokenStream"/>s, which analyze text. It thus represents a /// policy for extracting index terms from text. /// <para/> /// In order to define what analysis is done, subclasses must define their /// <see cref="TokenStreamComponents"/> in <see cref="CreateComponents(string, TextReader)"/>. /// The components are then reused in each call to <see cref="GetTokenStream(string, TextReader)"/>. /// <para/> /// Simple example: /// <code> /// Analyzer analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) => /// { /// Tokenizer source = new FooTokenizer(reader); /// TokenStream filter = new FooFilter(source); /// filter = new BarFilter(filter); /// return new TokenStreamComponents(source, filter); /// }); /// </code> /// For more examples, see the <see cref="Lucene.Net.Analysis"/> namespace documentation. /// <para/> /// For some concrete implementations bundled with Lucene, look in the analysis modules: /// <list type="bullet"> /// <item><description>Common: /// Analyzers for indexing content in different languages and domains.</description></item> /// <item><description>ICU: /// Exposes functionality from ICU to Apache Lucene.</description></item> /// <item><description>Kuromoji: /// Morphological analyzer for Japanese text.</description></item> /// <item><description>Morfologik: /// Dictionary-driven lemmatization for the Polish language.</description></item> /// <item><description>Phonetic: /// Analysis for indexing phonetic signatures (for sounds-alike search).</description></item> /// <item><description>Smart Chinese: /// Analyzer for Simplified Chinese, which indexes words.</description></item> /// <item><description>Stempel: /// Algorithmic Stemmer for the Polish Language.</description></item> /// <item><description>UIMA: /// Analysis integration with Apache UIMA.</description></item> /// </list> /// </summary> public abstract class Analyzer : IDisposable { private readonly ReuseStrategy reuseStrategy; // non readonly as it gets nulled if closed; internal for access by ReuseStrategy's final helper methods: internal DisposableThreadLocal<object> storedValue = new DisposableThreadLocal<object>(); /// <summary> /// Create a new <see cref="Analyzer"/>, reusing the same set of components per-thread /// across calls to <see cref="GetTokenStream(string, TextReader)"/>. /// </summary> public Analyzer() : this(GLOBAL_REUSE_STRATEGY) { } /// <summary> /// Expert: create a new Analyzer with a custom <see cref="ReuseStrategy"/>. /// <para/> /// NOTE: if you just want to reuse on a per-field basis, its easier to /// use a subclass of <see cref="AnalyzerWrapper"/> such as /// <c>Lucene.Net.Analysis.Common.Miscellaneous.PerFieldAnalyzerWrapper</c> /// instead. /// </summary> public Analyzer(ReuseStrategy reuseStrategy) { this.reuseStrategy = reuseStrategy; } /// <summary> /// Creates a new instance with the ability to specify the body of the <see cref="CreateComponents(string, TextReader)"/> /// method through the <paramref name="createComponents"/> parameter. /// Simple example: /// <code> /// var analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) => /// { /// Tokenizer source = new FooTokenizer(reader); /// TokenStream filter = new FooFilter(source); /// filter = new BarFilter(filter); /// return new TokenStreamComponents(source, filter); /// }); /// </code> /// <para/> /// LUCENENET specific /// </summary> /// <param name="createComponents"> /// A delegate method that represents (is called by) the <see cref="CreateComponents(string, TextReader)"/> /// method. It accepts a <see cref="string"/> fieldName and a <see cref="TextReader"/> reader and /// returns the <see cref="TokenStreamComponents"/> for this analyzer. /// </param> /// <returns> A new <see cref="AnonymousAnalyzer"/> instance.</returns> public static Analyzer NewAnonymous(Func<string, TextReader, TokenStreamComponents> createComponents) { return NewAnonymous(createComponents, GLOBAL_REUSE_STRATEGY); } /// <summary> /// Creates a new instance with the ability to specify the body of the <see cref="CreateComponents(string, TextReader)"/> /// method through the <paramref name="createComponents"/> parameter and allows the use of a <see cref="ReuseStrategy"/>. /// Simple example: /// <code> /// var analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) => /// { /// Tokenizer source = new FooTokenizer(reader); /// TokenStream filter = new FooFilter(source); /// filter = new BarFilter(filter); /// return new TokenStreamComponents(source, filter); /// }, reuseStrategy); /// </code> /// <para/> /// LUCENENET specific /// </summary> /// <param name="createComponents"> /// An delegate method that represents (is called by) the <see cref="CreateComponents(string, TextReader)"/> /// method. It accepts a <see cref="string"/> fieldName and a <see cref="TextReader"/> reader and /// returns the <see cref="TokenStreamComponents"/> for this analyzer. /// </param> /// <param name="reuseStrategy">A custom <see cref="ReuseStrategy"/> instance.</param> /// <returns> A new <see cref="AnonymousAnalyzer"/> instance.</returns> public static Analyzer NewAnonymous(Func<string, TextReader, TokenStreamComponents> createComponents, ReuseStrategy reuseStrategy) { return NewAnonymous(createComponents, null, reuseStrategy); } /// <summary> /// Creates a new instance with the ability to specify the body of the <see cref="CreateComponents(string, TextReader)"/> /// method through the <paramref name="createComponents"/> parameter and the body of the <see cref="InitReader(string, TextReader)"/> /// method through the <paramref name="initReader"/> parameter. /// Simple example: /// <code> /// var analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) => /// { /// Tokenizer source = new FooTokenizer(reader); /// TokenStream filter = new FooFilter(source); /// filter = new BarFilter(filter); /// return new TokenStreamComponents(source, filter); /// }, initReader: (fieldName, reader) => /// { /// return new HTMLStripCharFilter(reader); /// }); /// </code> /// <para/> /// LUCENENET specific /// </summary> /// <param name="createComponents"> /// A delegate method that represents (is called by) the <see cref="CreateComponents(string, TextReader)"/> /// method. It accepts a <see cref="string"/> fieldName and a <see cref="TextReader"/> reader and /// returns the <see cref="TokenStreamComponents"/> for this analyzer. /// </param> /// <param name="initReader">A delegate method that represents (is called by) the <see cref="InitReader(string, TextReader)"/> /// method. It accepts a <see cref="string"/> fieldName and a <see cref="TextReader"/> reader and /// returns the <see cref="TextReader"/> that can be modified or wrapped by the <paramref name="initReader"/> method.</param> /// <returns> A new <see cref="AnonymousAnalyzer"/> instance.</returns> public static Analyzer NewAnonymous(Func<string, TextReader, TokenStreamComponents> createComponents, Func<string, TextReader, TextReader> initReader) { return NewAnonymous(createComponents, initReader, GLOBAL_REUSE_STRATEGY); } /// <summary> /// Creates a new instance with the ability to specify the body of the <see cref="CreateComponents(string, TextReader)"/> /// method through the <paramref name="createComponents"/> parameter, the body of the <see cref="InitReader(string, TextReader)"/> /// method through the <paramref name="initReader"/> parameter, and allows the use of a <see cref="ReuseStrategy"/>. /// Simple example: /// <code> /// var analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) => /// { /// Tokenizer source = new FooTokenizer(reader); /// TokenStream filter = new FooFilter(source); /// filter = new BarFilter(filter); /// return new TokenStreamComponents(source, filter); /// }, initReader: (fieldName, reader) => /// { /// return new HTMLStripCharFilter(reader); /// }, reuseStrategy); /// </code> /// <para/> /// LUCENENET specific /// </summary> /// <param name="createComponents"> /// A delegate method that represents (is called by) the <see cref="CreateComponents(string, TextReader)"/> /// method. It accepts a <see cref="string"/> fieldName and a <see cref="TextReader"/> reader and /// returns the <see cref="TokenStreamComponents"/> for this analyzer. /// </param> /// <param name="initReader">A delegate method that represents (is called by) the <see cref="InitReader(string, TextReader)"/> /// method. It accepts a <see cref="string"/> fieldName and a <see cref="TextReader"/> reader and /// returns the <see cref="TextReader"/> that can be modified or wrapped by the <paramref name="initReader"/> method.</param> /// <param name="reuseStrategy">A custom <see cref="ReuseStrategy"/> instance.</param> /// <returns> A new <see cref="AnonymousAnalyzer"/> instance.</returns> public static Analyzer NewAnonymous(Func<string, TextReader, TokenStreamComponents> createComponents, Func<string, TextReader, TextReader> initReader, ReuseStrategy reuseStrategy) { return new AnonymousAnalyzer(createComponents, initReader, reuseStrategy); } /// <summary> /// Creates a new <see cref="TokenStreamComponents"/> instance for this analyzer. /// </summary> /// <param name="fieldName"> /// the name of the fields content passed to the /// <see cref="TokenStreamComponents"/> sink as a reader </param> /// <param name="reader"> /// the reader passed to the <see cref="Tokenizer"/> constructor </param> /// <returns> the <see cref="TokenStreamComponents"/> for this analyzer. </returns> protected internal abstract TokenStreamComponents CreateComponents(string fieldName, TextReader reader); /// <summary> /// Returns a <see cref="TokenStream"/> suitable for <paramref name="fieldName"/>, tokenizing /// the contents of <c>text</c>. /// <para/> /// This method uses <see cref="CreateComponents(string, TextReader)"/> to obtain an /// instance of <see cref="TokenStreamComponents"/>. It returns the sink of the /// components and stores the components internally. Subsequent calls to this /// method will reuse the previously stored components after resetting them /// through <see cref="TokenStreamComponents.SetReader(TextReader)"/>. /// <para/> /// <b>NOTE:</b> After calling this method, the consumer must follow the /// workflow described in <see cref="Analysis.TokenStream"/> to properly consume its contents. /// See the <see cref="Lucene.Net.Analysis"/> namespace documentation for /// some examples demonstrating this. /// </summary> /// <param name="fieldName"> the name of the field the created <see cref="Analysis.TokenStream"/> is used for </param> /// <param name="reader"> the reader the streams source reads from </param> /// <returns> <see cref="Analysis.TokenStream"/> for iterating the analyzed content of <see cref="TextReader"/> </returns> /// <exception cref="ObjectDisposedException"> if the Analyzer is disposed. </exception> /// <exception cref="IOException"> if an i/o error occurs (may rarely happen for strings). </exception> /// <seealso cref="GetTokenStream(string, string)"/> public TokenStream GetTokenStream(string fieldName, TextReader reader) { TokenStreamComponents components = reuseStrategy.GetReusableComponents(this, fieldName); TextReader r = InitReader(fieldName, reader); if (components == null) { components = CreateComponents(fieldName, r); reuseStrategy.SetReusableComponents(this, fieldName, components); } else { components.SetReader(r); } return components.TokenStream; } /// <summary> /// Returns a <see cref="Analysis.TokenStream"/> suitable for <paramref name="fieldName"/>, tokenizing /// the contents of <paramref name="text"/>. /// <para/> /// This method uses <see cref="CreateComponents(string, TextReader)"/> to obtain an /// instance of <see cref="TokenStreamComponents"/>. It returns the sink of the /// components and stores the components internally. Subsequent calls to this /// method will reuse the previously stored components after resetting them /// through <see cref="TokenStreamComponents.SetReader(TextReader)"/>. /// <para/> /// <b>NOTE:</b> After calling this method, the consumer must follow the /// workflow described in <see cref="Analysis.TokenStream"/> to properly consume its contents. /// See the <see cref="Lucene.Net.Analysis"/> namespace documentation for /// some examples demonstrating this. /// </summary> /// <param name="fieldName">the name of the field the created <see cref="Analysis.TokenStream"/> is used for</param> /// <param name="text">the <see cref="string"/> the streams source reads from </param> /// <returns><see cref="Analysis.TokenStream"/> for iterating the analyzed content of <c>reader</c></returns> /// <exception cref="ObjectDisposedException"> if the Analyzer is disposed. </exception> /// <exception cref="IOException"> if an i/o error occurs (may rarely happen for strings). </exception> /// <seealso cref="GetTokenStream(string, TextReader)"/> public TokenStream GetTokenStream(string fieldName, string text) { TokenStreamComponents components = reuseStrategy.GetReusableComponents(this, fieldName); ReusableStringReader strReader = (components == null || components.reusableStringReader == null) ? new ReusableStringReader() : components.reusableStringReader; strReader.SetValue(text); var r = InitReader(fieldName, strReader); if (components == null) { components = CreateComponents(fieldName, r); reuseStrategy.SetReusableComponents(this, fieldName, components); } else { components.SetReader(r); } components.reusableStringReader = strReader; return components.TokenStream; } /// <summary> /// Override this if you want to add a <see cref="CharFilter"/> chain. /// <para/> /// The default implementation returns <paramref name="reader"/> /// unchanged. /// </summary> /// <param name="fieldName"> <see cref="Index.IIndexableField"/> name being indexed </param> /// <param name="reader"> original <see cref="TextReader"/> </param> /// <returns> reader, optionally decorated with <see cref="CharFilter"/>(s) </returns> protected internal virtual TextReader InitReader(string fieldName, TextReader reader) { return reader; } /// <summary> /// Invoked before indexing a <see cref="Index.IIndexableField"/> instance if /// terms have already been added to that field. This allows custom /// analyzers to place an automatic position increment gap between /// <see cref="Index.IIndexableField"/> instances using the same field name. The default value /// position increment gap is 0. With a 0 position increment gap and /// the typical default token position increment of 1, all terms in a field, /// including across <see cref="Index.IIndexableField"/> instances, are in successive positions, allowing /// exact <see cref="Search.PhraseQuery"/> matches, for instance, across <see cref="Index.IIndexableField"/> instance boundaries. /// </summary> /// <param name="fieldName"> <see cref="Index.IIndexableField"/> name being indexed. </param> /// <returns> position increment gap, added to the next token emitted from <see cref="GetTokenStream(string, TextReader)"/>. /// this value must be <c>&gt;= 0</c>.</returns> public virtual int GetPositionIncrementGap(string fieldName) { return 0; } /// <summary> /// Just like <see cref="GetPositionIncrementGap"/>, except for /// <see cref="Token"/> offsets instead. By default this returns 1. /// this method is only called if the field /// produced at least one token for indexing. /// </summary> /// <param name="fieldName"> the field just indexed </param> /// <returns> offset gap, added to the next token emitted from <see cref="GetTokenStream(string, TextReader)"/>. /// this value must be <c>&gt;= 0</c>. </returns> public virtual int GetOffsetGap(string fieldName) { return 1; } /// <summary> /// Returns the used <see cref="ReuseStrategy"/>. /// </summary> public ReuseStrategy Strategy => reuseStrategy; /// <summary> /// Frees persistent resources used by this <see cref="Analyzer"/> /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Frees persistent resources used by this <see cref="Analyzer"/> /// </summary> protected virtual void Dispose(bool disposing) { if (disposing) { if (storedValue != null) { storedValue.Dispose(); storedValue = null; } } } // LUCENENET specific - de-nested TokenStreamComponents and ReuseStrategy // so they don't need to be qualified when used outside of Analyzer subclasses. /// <summary> /// A predefined <see cref="ReuseStrategy"/> that reuses the same components for /// every field. /// </summary> public static readonly ReuseStrategy GLOBAL_REUSE_STRATEGY = #pragma warning disable 612, 618 new GlobalReuseStrategy(); #pragma warning restore 612, 618 /// <summary> /// Implementation of <see cref="ReuseStrategy"/> that reuses the same components for /// every field. </summary> [Obsolete("this implementation class will be hidden in Lucene 5.0. Use Analyzer.GLOBAL_REUSE_STRATEGY instead!")] public sealed class GlobalReuseStrategy : ReuseStrategy { /// <summary> /// Sole constructor. (For invocation by subclass constructors, typically implicit.) </summary> [Obsolete("Don't create instances of this class, use Analyzer.GLOBAL_REUSE_STRATEGY")] public GlobalReuseStrategy() { } public override TokenStreamComponents GetReusableComponents(Analyzer analyzer, string fieldName) { return (TokenStreamComponents)GetStoredValue(analyzer); } public override void SetReusableComponents(Analyzer analyzer, string fieldName, TokenStreamComponents components) { SetStoredValue(analyzer, components); } } /// <summary> /// A predefined <see cref="ReuseStrategy"/> that reuses components per-field by /// maintaining a Map of <see cref="TokenStreamComponents"/> per field name. /// </summary> public static readonly ReuseStrategy PER_FIELD_REUSE_STRATEGY = #pragma warning disable 612, 618 new PerFieldReuseStrategy(); #pragma warning restore 612, 618 /// <summary> /// Implementation of <see cref="ReuseStrategy"/> that reuses components per-field by /// maintaining a Map of <see cref="TokenStreamComponents"/> per field name. /// </summary> [Obsolete("this implementation class will be hidden in Lucene 5.0. Use Analyzer.PER_FIELD_REUSE_STRATEGY instead!")] public class PerFieldReuseStrategy : ReuseStrategy { /// <summary> /// Sole constructor. (For invocation by subclass constructors, typically implicit.) /// </summary> [Obsolete("Don't create instances of this class, use Analyzer.PER_FIELD_REUSE_STRATEGY")] public PerFieldReuseStrategy() { } public override TokenStreamComponents GetReusableComponents(Analyzer analyzer, string fieldName) { var componentsPerField = (IDictionary<string, TokenStreamComponents>)GetStoredValue(analyzer); if (componentsPerField != null) { TokenStreamComponents ret; componentsPerField.TryGetValue(fieldName, out ret); return ret; } return null; } public override void SetReusableComponents(Analyzer analyzer, string fieldName, TokenStreamComponents components) { var componentsPerField = (IDictionary<string, TokenStreamComponents>)GetStoredValue(analyzer); if (componentsPerField == null) { // LUCENENET-615: This needs to support nullable keys componentsPerField = new JCG.Dictionary<string, TokenStreamComponents>(); SetStoredValue(analyzer, componentsPerField); } componentsPerField[fieldName] = components; } } /// <summary> /// LUCENENET specific helper class to mimick Java's ability to create anonymous classes. /// Clearly, the design of <see cref="Analyzer"/> took this feature of Java into consideration. /// Since it doesn't exist in .NET, we can use a delegate method to call the constructor of /// this concrete instance to fake it (by calling an overload of /// <see cref="Analyzer.NewAnonymous(Func{string, TextReader, TokenStreamComponents})"/>). /// </summary> private class AnonymousAnalyzer : Analyzer { private readonly Func<string, TextReader, TokenStreamComponents> createComponents; private readonly Func<string, TextReader, TextReader> initReader; public AnonymousAnalyzer(Func<string, TextReader, TokenStreamComponents> createComponents, Func<string, TextReader, TextReader> initReader, ReuseStrategy reuseStrategy) : base(reuseStrategy) { if (createComponents == null) throw new ArgumentNullException("createComponents"); this.createComponents = createComponents; this.initReader = initReader; } protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { return this.createComponents(fieldName, reader); } protected internal override TextReader InitReader(string fieldName, TextReader reader) { if (this.initReader != null) { return this.initReader(fieldName, reader); } return base.InitReader(fieldName, reader); } } } /// <summary> /// This class encapsulates the outer components of a token stream. It provides /// access to the source (<see cref="Analysis.Tokenizer"/>) and the outer end (sink), an /// instance of <see cref="TokenFilter"/> which also serves as the /// <see cref="Analysis.TokenStream"/> returned by /// <see cref="Analyzer.GetTokenStream(string, TextReader)"/>. /// </summary> public class TokenStreamComponents { /// <summary> /// Original source of the tokens. /// </summary> protected readonly Tokenizer m_source; /// <summary> /// Sink tokenstream, such as the outer tokenfilter decorating /// the chain. This can be the source if there are no filters. /// </summary> protected readonly TokenStream m_sink; /// <summary> /// Internal cache only used by <see cref="Analyzer.GetTokenStream(string, string)"/>. </summary> internal ReusableStringReader reusableStringReader; /// <summary> /// Creates a new <see cref="TokenStreamComponents"/> instance. /// </summary> /// <param name="source"> /// the analyzer's tokenizer </param> /// <param name="result"> /// the analyzer's resulting token stream </param> public TokenStreamComponents(Tokenizer source, TokenStream result) { this.m_source = source; this.m_sink = result; } /// <summary> /// Creates a new <see cref="TokenStreamComponents"/> instance. /// </summary> /// <param name="source"> /// the analyzer's tokenizer </param> public TokenStreamComponents(Tokenizer source) { this.m_source = source; this.m_sink = source; } /// <summary> /// Resets the encapsulated components with the given reader. If the components /// cannot be reset, an Exception should be thrown. /// </summary> /// <param name="reader"> /// a reader to reset the source component </param> /// <exception cref="IOException"> /// if the component's reset method throws an <seealso cref="IOException"/> </exception> protected internal virtual void SetReader(TextReader reader) { m_source.SetReader(reader); } /// <summary> /// Returns the sink <see cref="Analysis.TokenStream"/> /// </summary> /// <returns> the sink <see cref="Analysis.TokenStream"/> </returns> public virtual TokenStream TokenStream => m_sink; /// <summary> /// Returns the component's <see cref="Analysis.Tokenizer"/> /// </summary> /// <returns> Component's <see cref="Analysis.Tokenizer"/> </returns> public virtual Tokenizer Tokenizer => m_source; } /// <summary> /// Strategy defining how <see cref="TokenStreamComponents"/> are reused per call to /// <see cref="Analyzer.GetTokenStream(string, TextReader)"/>. /// </summary> public abstract class ReuseStrategy { /// <summary> /// Gets the reusable <see cref="TokenStreamComponents"/> for the field with the given name. /// </summary> /// <param name="analyzer"> <see cref="Analyzer"/> from which to get the reused components. Use /// <see cref="GetStoredValue(Analyzer)"/> and <see cref="SetStoredValue(Analyzer, object)"/> /// to access the data on the <see cref="Analyzer"/>. </param> /// <param name="fieldName"> Name of the field whose reusable <see cref="TokenStreamComponents"/> /// are to be retrieved </param> /// <returns> Reusable <see cref="TokenStreamComponents"/> for the field, or <c>null</c> /// if there was no previous components for the field </returns> public abstract TokenStreamComponents GetReusableComponents(Analyzer analyzer, string fieldName); /// <summary> /// Stores the given <see cref="TokenStreamComponents"/> as the reusable components for the /// field with the give name. /// </summary> /// <param name="analyzer"> Analyzer </param> /// <param name="fieldName"> Name of the field whose <see cref="TokenStreamComponents"/> are being set </param> /// <param name="components"> <see cref="TokenStreamComponents"/> which are to be reused for the field </param> public abstract void SetReusableComponents(Analyzer analyzer, string fieldName, TokenStreamComponents components); /// <summary> /// Returns the currently stored value. /// </summary> /// <returns> Currently stored value or <c>null</c> if no value is stored </returns> /// <exception cref="ObjectDisposedException"> if the <see cref="Analyzer"/> is closed. </exception> protected internal object GetStoredValue(Analyzer analyzer) { if (analyzer.storedValue == null) { throw new ObjectDisposedException(this.GetType().FullName, "this Analyzer is closed"); } return analyzer.storedValue.Get(); } /// <summary> /// Sets the stored value. /// </summary> /// <param name="analyzer"> Analyzer </param> /// <param name="storedValue"> Value to store </param> /// <exception cref="ObjectDisposedException"> if the <see cref="Analyzer"/> is closed. </exception> protected internal void SetStoredValue(Analyzer analyzer, object storedValue) { if (analyzer.storedValue == null) { throw new ObjectDisposedException("this Analyzer is closed"); } analyzer.storedValue.Set(storedValue); } } }
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 VentudaVibexDemo.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; } } }
using System; using System.Collections.Generic; using System.Globalization; using NUnit.Framework; using ServiceStack.ServiceHost; using ServiceStack.ServiceInterface.Auth; using ServiceStack.Text; namespace ServiceStack.Common.Tests.OAuth { [TestFixture] public class OAuthUserSessionTests : OAuthUserSessionTestsBase { [Test, TestCaseSource("UserAuthRepositorys")] public void Does_persist_TwitterOAuth(IUserAuthRepository userAuthRepository) { InitTest(userAuthRepository); MockAuthHttpGateway.Tokens = twitterGatewayTokens; var authInfo = new Dictionary<string, string> { {"user_id", "133371690876022785"}, {"screen_name", "demisbellot"}, }; var oAuthUserSession = requestContext.ReloadSession(); var twitterAuth = GetTwitterAuthProvider(); twitterAuth.OnAuthenticated(service, oAuthUserSession, twitterAuthTokens, authInfo); oAuthUserSession = requestContext.ReloadSession(); Assert.That(oAuthUserSession.UserAuthId, Is.Not.Null); var userAuth = userAuthRepository.GetUserAuth(oAuthUserSession.UserAuthId); Assert.That(userAuth.Id.ToString(CultureInfo.InvariantCulture), Is.EqualTo(oAuthUserSession.UserAuthId)); Assert.That(userAuth.DisplayName, Is.EqualTo("Demis Bellot TW")); var authProviders = userAuthRepository.GetUserOAuthProviders(oAuthUserSession.UserAuthId); Assert.That(authProviders.Count, Is.EqualTo(1)); var authProvider = authProviders[0]; Assert.That(authProvider.UserAuthId, Is.EqualTo(userAuth.Id)); Assert.That(authProvider.DisplayName, Is.EqualTo("Demis Bellot TW")); Assert.That(authProvider.FirstName, Is.Null); Assert.That(authProvider.LastName, Is.Null); Assert.That(authProvider.RequestToken, Is.EqualTo(twitterAuthTokens.RequestToken)); Assert.That(authProvider.RequestTokenSecret, Is.EqualTo(twitterAuthTokens.RequestTokenSecret)); Console.WriteLine(authProviders.Dump()); } [Test, TestCaseSource("UserAuthRepositorys")] public void Does_persist_FacebookOAuth(IUserAuthRepository userAuthRepository) { InitTest(userAuthRepository); var serviceTokens = MockAuthHttpGateway.Tokens = facebookGatewayTokens; var oAuthUserSession = requestContext.ReloadSession(); var authInfo = new Dictionary<string, string> { }; var facebookAuth = GetFacebookAuthProvider(); facebookAuth.OnAuthenticated(service, oAuthUserSession, facebookAuthTokens, authInfo); oAuthUserSession = requestContext.ReloadSession(); Assert.That(oAuthUserSession.FacebookUserId, Is.EqualTo(serviceTokens.UserId)); Assert.That(oAuthUserSession.UserAuthId, Is.Not.Null); var userAuth = userAuthRepository.GetUserAuth(oAuthUserSession.UserAuthId); Assert.That(userAuth.Id.ToString(CultureInfo.InvariantCulture), Is.EqualTo(oAuthUserSession.UserAuthId)); Assert.That(userAuth.DisplayName, Is.EqualTo(serviceTokens.DisplayName)); Assert.That(userAuth.FirstName, Is.EqualTo(serviceTokens.FirstName)); Assert.That(userAuth.LastName, Is.EqualTo(serviceTokens.LastName)); Assert.That(userAuth.PrimaryEmail, Is.EqualTo(serviceTokens.Email)); var authProviders = userAuthRepository.GetUserOAuthProviders(oAuthUserSession.UserAuthId); Assert.That(authProviders.Count, Is.EqualTo(1)); var authProvider = authProviders[0]; Assert.That(authProvider.UserAuthId, Is.EqualTo(userAuth.Id)); Assert.That(authProvider.DisplayName, Is.EqualTo(serviceTokens.DisplayName)); Assert.That(authProvider.FirstName, Is.EqualTo(serviceTokens.FirstName)); Assert.That(authProvider.LastName, Is.EqualTo(serviceTokens.LastName)); Assert.That(authProvider.Email, Is.EqualTo(serviceTokens.Email)); Assert.That(authProvider.RequestToken, Is.Null); Assert.That(authProvider.RequestTokenSecret, Is.Null); Assert.That(authProvider.AccessToken, Is.Null); Assert.That(authProvider.AccessTokenSecret, Is.EqualTo(facebookAuthTokens.AccessTokenSecret)); Console.WriteLine(authProviders.Dump()); } [Test, TestCaseSource("UserAuthRepositorys")] public void Does_merge_FacebookOAuth_TwitterOAuth(IUserAuthRepository userAuthRepository) { InitTest(userAuthRepository); var serviceTokensFb = MockAuthHttpGateway.Tokens = facebookGatewayTokens; var oAuthUserSession = requestContext.ReloadSession(); var facebookAuth = GetFacebookAuthProvider(); facebookAuth.OnAuthenticated(service, oAuthUserSession, facebookAuthTokens, new Dictionary<string, string>()); oAuthUserSession = requestContext.ReloadSession(); var serviceTokensTw = MockAuthHttpGateway.Tokens = twitterGatewayTokens; var authInfo = new Dictionary<string, string> { {"user_id", "133371690876022785"}, {"screen_name", "demisbellot"}, }; var twitterAuth = GetTwitterAuthProvider(); twitterAuth.OnAuthenticated(service, oAuthUserSession, twitterAuthTokens, authInfo); oAuthUserSession = requestContext.ReloadSession(); Assert.That(oAuthUserSession.TwitterUserId, Is.EqualTo(authInfo["user_id"])); Assert.That(oAuthUserSession.TwitterScreenName, Is.EqualTo(authInfo["screen_name"])); var userAuth = userAuthRepository.GetUserAuth(oAuthUserSession.UserAuthId); Assert.That(userAuth.Id.ToString(CultureInfo.InvariantCulture), Is.EqualTo(oAuthUserSession.UserAuthId)); Assert.That(userAuth.DisplayName, Is.EqualTo(serviceTokensTw.DisplayName)); Assert.That(userAuth.FirstName, Is.EqualTo(serviceTokensFb.FirstName)); Assert.That(userAuth.LastName, Is.EqualTo(serviceTokensFb.LastName)); Assert.That(userAuth.PrimaryEmail, Is.EqualTo(serviceTokensFb.Email)); var authProviders = userAuthRepository.GetUserOAuthProviders(oAuthUserSession.UserAuthId); Assert.That(authProviders.Count, Is.EqualTo(2)); Console.WriteLine(userAuth.Dump()); Console.WriteLine(authProviders.Dump()); } [Test, TestCaseSource("UserAuthRepositorys")] public void Can_login_with_user_created_CreateUserAuth(IUserAuthRepository userAuthRepository) { InitTest(userAuthRepository); var registrationService = GetRegistrationService(userAuthRepository); var responseObj = registrationService.Post(registrationDto); var httpResult = responseObj as IHttpResult; if (httpResult != null) { Assert.Fail("HttpResult found: " + httpResult.Dump()); } var response = (RegistrationResponse)responseObj; Assert.That(response.UserId, Is.Not.Null); var userAuth = userAuthRepository.GetUserAuth(response.UserId); AssertEqual(userAuth, registrationDto); userAuth = userAuthRepository.GetUserAuthByUserName(registrationDto.UserName); AssertEqual(userAuth, registrationDto); userAuth = userAuthRepository.GetUserAuthByUserName(registrationDto.Email); AssertEqual(userAuth, registrationDto); UserAuth userId; var success = userAuthRepository.TryAuthenticate(registrationDto.UserName, registrationDto.Password, out userId); Assert.That(success, Is.True); Assert.That(userId, Is.Not.Null); success = userAuthRepository.TryAuthenticate(registrationDto.Email, registrationDto.Password, out userId); Assert.That(success, Is.True); Assert.That(userId, Is.Not.Null); success = userAuthRepository.TryAuthenticate(registrationDto.UserName, "Bad Password", out userId); Assert.That(success, Is.False); Assert.That(userId, Is.Null); } [Test, TestCaseSource("UserAuthRepositorys")] public void Logging_in_pulls_all_AuthInfo_from_repo_after_logging_in_all_AuthProviders(IUserAuthRepository userAuthRepository) { InitTest(userAuthRepository); var oAuthUserSession = requestContext.ReloadSession(); //Facebook LoginWithFacebook(oAuthUserSession); //Twitter MockAuthHttpGateway.Tokens = twitterGatewayTokens; var authInfo = new Dictionary<string, string> { {"user_id", "133371690876022785"}, {"screen_name", "demisbellot"}, }; var twitterAuth = GetTwitterAuthProvider(); twitterAuth.OnAuthenticated(service, oAuthUserSession, twitterAuthTokens, authInfo); Console.WriteLine("UserId: " + oAuthUserSession.UserAuthId); //Register var registrationService = GetRegistrationService(userAuthRepository, oAuthUserSession, requestContext); var responseObj = registrationService.Post(registrationDto); Assert.That(responseObj as IHttpError, Is.Null, responseObj.ToString()); Console.WriteLine("UserId: " + oAuthUserSession.UserAuthId); var credentialsAuth = GetCredentialsAuthConfig(); var loginResponse = credentialsAuth.Authenticate(service, oAuthUserSession, new Auth { provider = CredentialsAuthProvider.Name, UserName = registrationDto.UserName, Password = registrationDto.Password, }); loginResponse.PrintDump(); oAuthUserSession = requestContext.ReloadSession(); Assert.That(oAuthUserSession.TwitterUserId, Is.EqualTo(authInfo["user_id"])); Assert.That(oAuthUserSession.TwitterScreenName, Is.EqualTo(authInfo["screen_name"])); var userAuth = userAuthRepository.GetUserAuth(oAuthUserSession.UserAuthId); Assert.That(userAuth.Id.ToString(CultureInfo.InvariantCulture), Is.EqualTo(oAuthUserSession.UserAuthId)); Assert.That(userAuth.DisplayName, Is.EqualTo(registrationDto.DisplayName)); Assert.That(userAuth.FirstName, Is.EqualTo(registrationDto.FirstName)); Assert.That(userAuth.LastName, Is.EqualTo(registrationDto.LastName)); Assert.That(userAuth.Email, Is.EqualTo(registrationDto.Email)); Console.WriteLine(oAuthUserSession.Dump()); Assert.That(oAuthUserSession.ProviderOAuthAccess.Count, Is.EqualTo(2)); Assert.That(oAuthUserSession.IsAuthenticated, Is.True); var authProviders = userAuthRepository.GetUserOAuthProviders(oAuthUserSession.UserAuthId); Assert.That(authProviders.Count, Is.EqualTo(2)); Console.WriteLine(userAuth.Dump()); Console.WriteLine(authProviders.Dump()); } [Test, TestCaseSource("UserAuthRepositorys")] public void Registering_twice_creates_two_registrations(IUserAuthRepository userAuthRepository) { InitTest(userAuthRepository); var oAuthUserSession = requestContext.ReloadSession(); RegisterAndLogin(userAuthRepository, oAuthUserSession); requestContext.RemoveSession(); var userName1 = registrationDto.UserName; var userName2 = "UserName2"; registrationDto.UserName = userName2; registrationDto.Email = "as@if2.com"; var userAuth1 = userAuthRepository.GetUserAuthByUserName(userName1); Assert.That(userAuth1, Is.Not.Null); Register(userAuthRepository, oAuthUserSession, registrationDto); userAuth1 = userAuthRepository.GetUserAuthByUserName(userName1); var userAuth2 = userAuthRepository.GetUserAuthByUserName(userName2); Assert.That(userAuth1, Is.Not.Null); Assert.That(userAuth2, Is.Not.Null); } [Test, TestCaseSource("UserAuthRepositorys")] public void Registering_twice_in_same_session_updates_registration(IUserAuthRepository userAuthRepository) { InitTest(userAuthRepository); var oAuthUserSession = requestContext.ReloadSession(); oAuthUserSession = RegisterAndLogin(userAuthRepository, oAuthUserSession); var userName1 = registrationDto.UserName; var userName2 = "UserName2"; registrationDto.UserName = userName2; Register(userAuthRepository, oAuthUserSession, registrationDto); var userAuth1 = userAuthRepository.GetUserAuthByUserName(userName1); var userAuth2 = userAuthRepository.GetUserAuthByUserName(userName2); Assert.That(userAuth1, Is.Null); Assert.That(userAuth2, Is.Not.Null); } [Test, TestCaseSource("UserAuthRepositorys")] public void Connecting_to_facebook_whilst_authenticated_connects_account(IUserAuthRepository userAuthRepository) { InitTest(userAuthRepository); var oAuthUserSession = requestContext.ReloadSession(); oAuthUserSession = RegisterAndLogin(userAuthRepository, oAuthUserSession); LoginWithFacebook(oAuthUserSession); var userAuth = userAuthRepository.GetUserAuthByUserName(registrationDto.UserName); Assert.That(userAuth.UserName, Is.EqualTo(registrationDto.UserName)); var userAuthProviders = userAuthRepository.GetUserOAuthProviders(userAuth.Id.ToString(CultureInfo.InvariantCulture)); Assert.That(userAuthProviders.Count, Is.EqualTo(1)); } [Test, TestCaseSource("UserAuthRepositorys")] public void Can_AutoLogin_whilst_Registering(IUserAuthRepository userAuthRepository) { InitTest(userAuthRepository); var oAuthUserSession = requestContext.ReloadSession(); registrationDto.AutoLogin = true; Register(userAuthRepository, oAuthUserSession, registrationDto); oAuthUserSession = requestContext.ReloadSession(); Assert.That(oAuthUserSession.IsAuthenticated, Is.True); } } }
using FluentAssertions; using Microsoft.EntityFrameworkCore; using Moq; using Ritter.Domain; using Ritter.Infra.Crosscutting.Specifications; using Ritter.Infra.Data.Tests.Extensions; using Ritter.Infra.Data.Tests.Mocks; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Ritter.Infra.Data.Tests.Repositories { public class Repository_Any { [Fact] public void ReturnsTrueGivenAnyEntity() { List<Test> mockedTests = MockTests(); Mock<DbSet<Test>> mockDbSet = mockedTests.AsQueryable().BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); bool any = testRepository.Any(); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); any.Should().BeTrue(); } [Fact] public void ReturnsTrueGivenAnyEntityAsync() { List<Test> mockedTests = MockTests(); Mock<DbSet<Test>> mockDbSet = mockedTests.AsQueryable().BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); bool any = testRepository.AnyAsync().GetAwaiter().GetResult(); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); any.Should().BeTrue(); } [Fact] public void ReturnsFalseGivenNoneEntity() { List<Test> mockedTests = MockTests(0); Mock<DbSet<Test>> mockDbSet = mockedTests.AsQueryable().BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); bool any = testRepository.Any(); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); any.Should().BeFalse(); } [Fact] public void ReturnsFalseGivenNoneEntityAsync() { List<Test> mockedTests = MockTests(0); Mock<DbSet<Test>> mockDbSet = mockedTests.AsQueryable().BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); bool any = testRepository.AnyAsync().GetAwaiter().GetResult(); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); any.Should().BeFalse(); } [Fact] public void ReturnsTrueGivenAnyActiveEntity() { List<Test> mockedTests = MockTests(); mockedTests.First().Deactivate(); Mock<DbSet<Test>> mockDbSet = mockedTests.AsQueryable().BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); ISpecification<Test> spec = new DirectSpecification<Test>(t => t.Active); IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); bool any = testRepository.Any(spec); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); any.Should().BeTrue(); } [Fact] public void ReturnsTrueGivenAnyActiveEntityAsync() { List<Test> mockedTests = MockTests(); mockedTests.First().Deactivate(); Mock<DbSet<Test>> mockDbSet = mockedTests.AsQueryable().BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); ISpecification<Test> spec = new DirectSpecification<Test>(t => t.Active); IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); bool any = testRepository.AnyAsync(spec).GetAwaiter().GetResult(); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); any.Should().BeTrue(); } [Fact] public void ReturnsFalseGivenNoneActiveEntity() { List<Test> mockedTests = MockTests(1); mockedTests.First().Deactivate(); Mock<DbSet<Test>> mockDbSet = mockedTests.AsQueryable().BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); ISpecification<Test> spec = new DirectSpecification<Test>(t => t.Active); IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); bool any = testRepository.Any(spec); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); any.Should().BeFalse(); } [Fact] public void ReturnsFalseGivenNoneActiveEntityAsync() { List<Test> mockedTests = MockTests(1); mockedTests.First().Deactivate(); Mock<DbSet<Test>> mockDbSet = mockedTests.AsQueryable().BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); ISpecification<Test> spec = new DirectSpecification<Test>(t => t.Active); IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); bool any = testRepository.AnyAsync(spec).GetAwaiter().GetResult(); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); any.Should().BeFalse(); } [Fact] public void ThrowsArgumentNullExceptionGivenNullSpecification() { Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); Action act = () => { ISpecification<Test> spec = null; IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); testRepository.Any(spec); }; act.Should().Throw<ArgumentNullException>().And.ParamName.Should().Be("specification"); } [Fact] public void ThrowsArgumentNullExceptionGivenNullSpecificationAsync() { Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); Action act = () => { ISpecification<Test> spec = null; IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); testRepository.AnyAsync(spec).GetAwaiter().GetResult(); }; act.Should().Throw<ArgumentNullException>().And.ParamName.Should().Be("specification"); } private static List<Test> MockTests(int count) { List<Test> tests = new List<Test>(); for (int i = 1; i <= count; i++) { tests.Add(new Test(i)); } return tests; } private static List<Test> MockTests() { return MockTests(5); } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Archiver.Codecs { public class FindLastMatchingRecordingRequestEncoder { public const ushort BLOCK_LENGTH = 32; public const ushort TEMPLATE_ID = 16; public const ushort SCHEMA_ID = 101; public const ushort SCHEMA_VERSION = 6; private FindLastMatchingRecordingRequestEncoder _parentMessage; private IMutableDirectBuffer _buffer; protected int _offset; protected int _limit; public FindLastMatchingRecordingRequestEncoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IMutableDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public FindLastMatchingRecordingRequestEncoder Wrap(IMutableDirectBuffer buffer, int offset) { this._buffer = buffer; this._offset = offset; Limit(offset + BLOCK_LENGTH); return this; } public FindLastMatchingRecordingRequestEncoder WrapAndApplyHeader( IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder) { headerEncoder .Wrap(buffer, offset) .BlockLength(BLOCK_LENGTH) .TemplateId(TEMPLATE_ID) .SchemaId(SCHEMA_ID) .Version(SCHEMA_VERSION); return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH); } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int ControlSessionIdEncodingOffset() { return 0; } public static int ControlSessionIdEncodingLength() { return 8; } public static long ControlSessionIdNullValue() { return -9223372036854775808L; } public static long ControlSessionIdMinValue() { return -9223372036854775807L; } public static long ControlSessionIdMaxValue() { return 9223372036854775807L; } public FindLastMatchingRecordingRequestEncoder ControlSessionId(long value) { _buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian); return this; } public static int CorrelationIdEncodingOffset() { return 8; } public static int CorrelationIdEncodingLength() { return 8; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public FindLastMatchingRecordingRequestEncoder CorrelationId(long value) { _buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian); return this; } public static int MinRecordingIdEncodingOffset() { return 16; } public static int MinRecordingIdEncodingLength() { return 8; } public static long MinRecordingIdNullValue() { return -9223372036854775808L; } public static long MinRecordingIdMinValue() { return -9223372036854775807L; } public static long MinRecordingIdMaxValue() { return 9223372036854775807L; } public FindLastMatchingRecordingRequestEncoder MinRecordingId(long value) { _buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian); return this; } public static int SessionIdEncodingOffset() { return 24; } public static int SessionIdEncodingLength() { return 4; } public static int SessionIdNullValue() { return -2147483648; } public static int SessionIdMinValue() { return -2147483647; } public static int SessionIdMaxValue() { return 2147483647; } public FindLastMatchingRecordingRequestEncoder SessionId(int value) { _buffer.PutInt(_offset + 24, value, ByteOrder.LittleEndian); return this; } public static int StreamIdEncodingOffset() { return 28; } public static int StreamIdEncodingLength() { return 4; } public static int StreamIdNullValue() { return -2147483648; } public static int StreamIdMinValue() { return -2147483647; } public static int StreamIdMaxValue() { return 2147483647; } public FindLastMatchingRecordingRequestEncoder StreamId(int value) { _buffer.PutInt(_offset + 28, value, ByteOrder.LittleEndian); return this; } public static int ChannelId() { return 6; } public static string ChannelCharacterEncoding() { return "US-ASCII"; } public static string ChannelMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int ChannelHeaderLength() { return 4; } public FindLastMatchingRecordingRequestEncoder PutChannel(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public FindLastMatchingRecordingRequestEncoder PutChannel(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public FindLastMatchingRecordingRequestEncoder Channel(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { FindLastMatchingRecordingRequestDecoder writer = new FindLastMatchingRecordingRequestDecoder(); writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION); return writer.AppendTo(builder); } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; using System.Windows.Forms.VisualStyles; namespace WeifenLuo.WinFormsUI.Docking { internal class VS2005DockPaneCaption : DockPaneCaptionBase { public bool BlueSkin = true; private sealed class InertButton : InertButtonBase { private Bitmap m_image, m_imageAutoHide; public InertButton(VS2005DockPaneCaption dockPaneCaption, Bitmap image, Bitmap imageAutoHide) : base() { m_dockPaneCaption = dockPaneCaption; m_image = image; m_imageAutoHide = imageAutoHide; RefreshChanges(); } private VS2005DockPaneCaption m_dockPaneCaption; private VS2005DockPaneCaption DockPaneCaption { get { return m_dockPaneCaption; } } public bool IsAutoHide { get { return DockPaneCaption.DockPane.IsAutoHide; } } public override Bitmap Image { get { return IsAutoHide ? m_imageAutoHide : m_image; } } protected override void OnRefreshChanges() { if (DockPaneCaption.DockPane.DockPanel != null) { if (DockPaneCaption.TextColor != ForeColor) { ForeColor = DockPaneCaption.TextColor; Invalidate(); } } } } #region consts private const int _TextGapTop = 2; private const int _TextGapBottom = 0; private const int _TextGapLeft = 3; private const int _TextGapRight = 3; private const int _ButtonGapTop = 2; private const int _ButtonGapBottom = 1; private const int _ButtonGapBetween = 1; private const int _ButtonGapLeft = 1; private const int _ButtonGapRight = 2; #endregion private static Bitmap _imageButtonClose; private static Bitmap ImageButtonClose { get { if (_imageButtonClose == null) _imageButtonClose = Resources.DockPane_Close; return _imageButtonClose; } } private InertButton m_buttonClose; private InertButton ButtonClose { get { if (m_buttonClose == null) { m_buttonClose = new InertButton(this, ImageButtonClose, ImageButtonClose); m_toolTip.SetToolTip(m_buttonClose, ToolTipClose); m_buttonClose.Click += new EventHandler(Close_Click); Controls.Add(m_buttonClose); } return m_buttonClose; } } private static Bitmap _imageButtonAutoHide; private static Bitmap ImageButtonAutoHide { get { if (_imageButtonAutoHide == null) _imageButtonAutoHide = Resources.DockPane_AutoHide; return _imageButtonAutoHide; } } private static Bitmap _imageButtonDock; private static Bitmap ImageButtonDock { get { if (_imageButtonDock == null) _imageButtonDock = Resources.DockPane_Dock; return _imageButtonDock; } } private InertButton m_buttonAutoHide; private InertButton ButtonAutoHide { get { if (m_buttonAutoHide == null) { m_buttonAutoHide = new InertButton(this, ImageButtonDock, ImageButtonAutoHide); m_toolTip.SetToolTip(m_buttonAutoHide, ToolTipAutoHide); m_buttonAutoHide.Click += new EventHandler(AutoHide_Click); Controls.Add(m_buttonAutoHide); } return m_buttonAutoHide; } } private static Bitmap _imageButtonOptions; private static Bitmap ImageButtonOptions { get { if (_imageButtonOptions == null) _imageButtonOptions = Resources.DockPane_Option; return _imageButtonOptions; } } private InertButton m_buttonOptions; private InertButton ButtonOptions { get { if (m_buttonOptions == null) { m_buttonOptions = new InertButton(this, ImageButtonOptions, ImageButtonOptions); m_toolTip.SetToolTip(m_buttonOptions, ToolTipOptions); m_buttonOptions.Click += new EventHandler(Options_Click); Controls.Add(m_buttonOptions); } return m_buttonOptions; } } private IContainer m_components; private IContainer Components { get { return m_components; } } private ToolTip m_toolTip; public VS2005DockPaneCaption(DockPane pane) : base(pane) { SuspendLayout(); m_components = new Container(); m_toolTip = new ToolTip(Components); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) Components.Dispose(); base.Dispose(disposing); } private static int TextGapTop { get { return _TextGapTop; } } private static Font TextFont { get { return SystemInformation.MenuFont; } } private static int TextGapBottom { get { return _TextGapBottom; } } private static int TextGapLeft { get { return _TextGapLeft; } } private static int TextGapRight { get { return _TextGapRight; } } private static int ButtonGapTop { get { return _ButtonGapTop; } } private static int ButtonGapBottom { get { return _ButtonGapBottom; } } private static int ButtonGapLeft { get { return _ButtonGapLeft; } } private static int ButtonGapRight { get { return _ButtonGapRight; } } private static int ButtonGapBetween { get { return _ButtonGapBetween; } } private static string _toolTipClose; private static string ToolTipClose { get { if (_toolTipClose == null) _toolTipClose = Strings.DockPaneCaption_ToolTipClose; return _toolTipClose; } } private static string _toolTipOptions; private static string ToolTipOptions { get { if (_toolTipOptions == null) _toolTipOptions = Strings.DockPaneCaption_ToolTipOptions; return _toolTipOptions; } } private static string _toolTipAutoHide; private static string ToolTipAutoHide { get { if (_toolTipAutoHide == null) _toolTipAutoHide = Strings.DockPaneCaption_ToolTipAutoHide; return _toolTipAutoHide; } } private static Blend _activeBackColorGradientBlend; private static Blend ActiveBackColorGradientBlend { get { if (_activeBackColorGradientBlend == null) { Blend blend = new Blend(2); blend.Factors = new float[]{0.5F, 1.0F}; blend.Positions = new float[]{0.0F, 1.0F}; _activeBackColorGradientBlend = blend; } return _activeBackColorGradientBlend; } } private Color TextColor { get { if (DockPane.IsActivated) return DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor; else return DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor; } } private static TextFormatFlags _textFormat = TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis | TextFormatFlags.VerticalCenter; private TextFormatFlags TextFormat { get { if (RightToLeft == RightToLeft.No) return _textFormat; else return _textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right; } } protected internal override int MeasureHeight() { int height = TextFont.Height + TextGapTop + TextGapBottom; if (height < ButtonClose.Image.Height + ButtonGapTop + ButtonGapBottom) height = ButtonClose.Image.Height + ButtonGapTop + ButtonGapBottom; return height; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint (e); DrawCaption(e.Graphics); } /* * private void DrawCaption(Graphics g) { if (ClientRectangle.Width == 0 || ClientRectangle.Height == 0) return; if (DockPane.IsActivated) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode)) { Rectangle rect = ClientRectangle; rect.Height = rect.Height / 2; brush.Blend = ActiveBackColorGradientBlend; g.FillRectangle(brush, rect); } } else { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode)) { g.FillRectangle(brush, ClientRectangle); } } Rectangle rectCaption = ClientRectangle; Rectangle rectCaptionText = rectCaption; rectCaptionText.X += TextGapLeft; rectCaptionText.Width -= TextGapLeft + TextGapRight; rectCaptionText.Width -= ButtonGapLeft + ButtonClose.Width + ButtonGapRight; if (ShouldShowAutoHideButton) rectCaptionText.Width -= ButtonAutoHide.Width + ButtonGapBetween; if (HasTabPageContextMenu) rectCaptionText.Width -= ButtonOptions.Width + ButtonGapBetween; rectCaptionText.Y += TextGapTop; rectCaptionText.Height -= TextGapTop + TextGapBottom; Color colorText; if (DockPane.IsActivated) colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor; else colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor; TextRenderer.DrawText(g, DockPane.CaptionText, TextFont, DrawHelper.RtlTransform(this, rectCaptionText), colorText, TextFormat); } * */ #region ActiveSphere modified private void DrawCaption(Graphics g) { if (ClientRectangle.Width == 0 || ClientRectangle.Height == 0) return; if (DockPane.IsActivated) { //TopBorder Color startColorTopBorder = Color.FromArgb(255, 216, 202, 149); Color endColorTopBorder = Color.FromArgb(255, 216, 194, 120); LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode; Rectangle borderRect = ClientRectangle; borderRect.Height = (borderRect.Height / 2) -1; using (LinearGradientBrush brush = new LinearGradientBrush(borderRect, startColorTopBorder, endColorTopBorder, gradientMode)) { brush.Blend = ActiveBackColorGradientBlend; g.FillRectangle(brush, borderRect); } //Bottom Border Color startColorBottomBorder = Color.FromArgb(255, 216, 194, 120); Color endColorBottomBorder = Color.FromArgb(255, 216, 202, 149); Rectangle bottomBorderRect = borderRect; bottomBorderRect.Y = borderRect.Height; bottomBorderRect.Height += 2; using (LinearGradientBrush brush = new LinearGradientBrush(bottomBorderRect, startColorBottomBorder, endColorBottomBorder, gradientMode)) { brush.Blend = ActiveBackColorGradientBlend; g.FillRectangle(brush, bottomBorderRect); } //TopBorderSecond Color startColorBorderSecond = Color.FromArgb(255, 255, 255, 249); Color endColorBorderSecond = Color.FromArgb(255, 255, 250, 231); Rectangle borderRectSecond = borderRect; borderRectSecond.Height = borderRect.Height; borderRectSecond.Width -= 2; borderRectSecond.Y += 1; borderRectSecond.X += 1; using (LinearGradientBrush brush = new LinearGradientBrush(borderRectSecond, startColorBorderSecond, endColorBorderSecond, gradientMode)) { brush.Blend = ActiveBackColorGradientBlend; g.FillRectangle(brush, borderRectSecond); } //Bottom Border Second Color startColorBottomBorderSecond = Color.FromArgb(255, 255, 242, 200); Color endColorBottomBorderSecond = Color.FromArgb(255, 255, 247, 185); Rectangle bottomBorderRectSecond = borderRect; bottomBorderRectSecond.Y = borderRect.Height +1; bottomBorderRectSecond.X += 1; bottomBorderRectSecond.Width -= 2; using (LinearGradientBrush brush = new LinearGradientBrush(bottomBorderRectSecond, startColorBottomBorderSecond, endColorBottomBorderSecond, gradientMode)) { brush.Blend = ActiveBackColorGradientBlend; g.FillRectangle(brush, bottomBorderRectSecond); } Color startColorFirst = Color.FromArgb(255, 255, 249, 218); Color endColorFirst = Color.FromArgb(255, 255, 238, 177); Rectangle rect = ClientRectangle; rect.Height = (rect.Height / 2) -1; rect.Width -= 3; rect.X += 2; rect.Y += 2; using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColorFirst, endColorFirst, gradientMode)) { brush.Blend = ActiveBackColorGradientBlend; g.FillRectangle(brush, rect); } Color startColorSecond = Color.FromArgb(255, 255, 214, 107); Color endColorSecond = Color.FromArgb(255, 255, 224, 135); Rectangle rectSecond = rect; rectSecond.Y = rect.Height +1; rectSecond.Height = rect.Height -1; using (LinearGradientBrush brush = new LinearGradientBrush(rectSecond, startColorSecond, endColorSecond, gradientMode)) { brush.Blend = ActiveBackColorGradientBlend; g.FillRectangle(brush, rectSecond); } } else { Color startColorBorder; Color endColorBorder; Color startColorBottomBorder; Color endColorBottomBorder; Color startColorBorderSecond; Color endColorBorderSecond; Color startColorBottomBorderSecond; Color endColorBottomBorderSecond; Color startColorFirst; Color endColorFirst; Color startColorSecond; Color endColorSecond; if (DockPane.DockPanel.Skin.BlueSkin) { //TopBorder startColorBorder = Color.FromArgb(255, 111, 157, 217); endColorBorder = Color.FromArgb(255, 111, 157, 217); //Bottom Border startColorBottomBorder = Color.FromArgb(255, 111, 157, 217); endColorBottomBorder = Color.FromArgb(255, 111, 157, 217); //TopBorderSecond startColorBorderSecond = Color.FromArgb(255, 241, 247, 255); endColorBorderSecond = Color.FromArgb(255, 241, 247, 255); //Bottom Border Second startColorBottomBorderSecond = Color.FromArgb(200, 191, 219, 255); endColorBottomBorderSecond = Color.FromArgb(255, 191, 219, 255); startColorFirst = Color.FromArgb(255, 227, 239, 255); endColorFirst = Color.FromArgb(255, 227, 239, 255); startColorSecond = Color.FromArgb(255, 223, 237, 255); endColorSecond = Color.FromArgb(255, 181, 213, 255); } else { //TopBorder //startColorBorder = Color.FromArgb(255, 124, 124, 148); //endColorBorder = Color.FromArgb(255, 124, 124, 148); startColorBorder = Color.FromArgb(255, 182, 188, 204); endColorBorder = Color.FromArgb(255, 182, 188, 204); //Bottom Border startColorBottomBorder = Color.FromArgb(255, 182, 188, 204); endColorBottomBorder = Color.FromArgb(255, 182, 188, 204); //TopBorderSecond startColorBorderSecond = Color.FromArgb(255, 241, 247, 255); endColorBorderSecond = Color.FromArgb(255, 241, 247, 255); //Bottom Border Second startColorBottomBorderSecond = Color.FromArgb(255, 241, 247, 255); endColorBottomBorderSecond = Color.FromArgb(255, 241, 247, 255); //startColorFirst = Color.FromArgb(255, 243, 244, 250); //endColorFirst = Color.FromArgb(255, 227, 228, 227); startColorFirst = Color.FromArgb(255, 255, 255, 255); endColorFirst = Color.FromArgb(255, 227, 232, 244); //startColorSecond = Color.FromArgb(255, 178, 177, 199); //endColorSecond = Color.FromArgb(255, 227, 228, 227); startColorSecond = Color.FromArgb(255, 208, 215, 236); endColorSecond = Color.FromArgb(255, 233, 236, 250); } LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode; Rectangle borderRect = ClientRectangle; borderRect.Height = (borderRect.Height / 2) - 1; using (LinearGradientBrush brush = new LinearGradientBrush(borderRect, startColorBorder, endColorBorder, gradientMode)) { brush.Blend = ActiveBackColorGradientBlend; g.FillRectangle(brush, borderRect); } Rectangle bottomBorderRect = borderRect; bottomBorderRect.Y = borderRect.Height; bottomBorderRect.Height += 2; using (LinearGradientBrush brush = new LinearGradientBrush(bottomBorderRect, startColorBottomBorder, endColorBottomBorder, gradientMode)) { brush.Blend = ActiveBackColorGradientBlend; g.FillRectangle(brush, bottomBorderRect); } Rectangle borderRectSecond = borderRect; borderRectSecond.Height = borderRect.Height; borderRectSecond.Width -= 2; borderRectSecond.Y += 1; borderRectSecond.X += 1; using (LinearGradientBrush brush = new LinearGradientBrush(borderRectSecond, startColorBorderSecond, endColorBorderSecond, gradientMode)) { brush.Blend = ActiveBackColorGradientBlend; g.FillRectangle(brush, borderRectSecond); } Rectangle bottomBorderRectSecond = borderRect; bottomBorderRectSecond.Y = borderRect.Height + 1; bottomBorderRectSecond.X += 1; bottomBorderRectSecond.Width -= 2; using (LinearGradientBrush brush = new LinearGradientBrush(bottomBorderRectSecond, startColorBottomBorderSecond, endColorBottomBorderSecond, gradientMode)) { brush.Blend = ActiveBackColorGradientBlend; g.FillRectangle(brush, bottomBorderRectSecond); } Rectangle rect = ClientRectangle; rect.Height = (rect.Height / 2) - 1; rect.Width -= 3; rect.X += 2; rect.Y += 2; using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColorFirst, endColorFirst, gradientMode)) { brush.Blend = ActiveBackColorGradientBlend; g.FillRectangle(brush, rect); } Rectangle rectSecond = rect; rectSecond.Y = rect.Height + 1; rectSecond.Height = rect.Height - 1; using (LinearGradientBrush brush = new LinearGradientBrush(rectSecond, startColorSecond, endColorSecond, gradientMode)) { brush.Blend = ActiveBackColorGradientBlend; g.FillRectangle(brush, rectSecond); } } Rectangle rectCaption = ClientRectangle; Rectangle rectCaptionText = rectCaption; rectCaptionText.X += TextGapLeft; rectCaptionText.Width -= TextGapLeft + TextGapRight; rectCaptionText.Width -= ButtonGapLeft + ButtonClose.Width + ButtonGapRight; if (ShouldShowAutoHideButton) rectCaptionText.Width -= ButtonAutoHide.Width + ButtonGapBetween; if (HasTabPageContextMenu) rectCaptionText.Width -= ButtonOptions.Width + ButtonGapBetween; rectCaptionText.Y += TextGapTop; rectCaptionText.Height -= TextGapTop + TextGapBottom; Color colorText; if (DockPane.IsActivated) colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor; else colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor; TextRenderer.DrawText(g, DockPane.CaptionText, TextFont, DrawHelper.RtlTransform(this, rectCaptionText), colorText, TextFormat); } #endregion protected override void OnLayout(LayoutEventArgs levent) { SetButtonsPosition(); base.OnLayout (levent); } protected override void OnRefreshChanges() { SetButtons(); Invalidate(); } private bool CloseButtonEnabled { get { return (DockPane.ActiveContent != null)? DockPane.ActiveContent.DockHandler.CloseButton : false; } } /// <summary> /// Determines whether the close button is visible on the content /// </summary> private bool CloseButtonVisible { get { return (DockPane.ActiveContent != null) ? DockPane.ActiveContent.DockHandler.CloseButtonVisible : false; } } private bool ShouldShowAutoHideButton { get { return !DockPane.IsFloat; } } private void SetButtons() { ButtonClose.Enabled = CloseButtonEnabled; ButtonClose.Visible = CloseButtonVisible; ButtonAutoHide.Visible = ShouldShowAutoHideButton; ButtonOptions.Visible = HasTabPageContextMenu; ButtonClose.RefreshChanges(); ButtonAutoHide.RefreshChanges(); ButtonOptions.RefreshChanges(); SetButtonsPosition(); } private void SetButtonsPosition() { // set the size and location for close and auto-hide buttons Rectangle rectCaption = ClientRectangle; int buttonWidth = ButtonClose.Image.Width; int buttonHeight = ButtonClose.Image.Height; int height = rectCaption.Height - ButtonGapTop - ButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } Size buttonSize = new Size(buttonWidth, buttonHeight); int x = rectCaption.X + rectCaption.Width - 1 - ButtonGapRight - m_buttonClose.Width; int y = rectCaption.Y + ButtonGapTop; Point point = new Point(x, y); ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); // If the close button is not visible draw the auto hide button overtop. // Otherwise it is drawn to the left of the close button. if (CloseButtonVisible) point.Offset(-(buttonWidth + ButtonGapBetween), 0); ButtonAutoHide.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); if (ShouldShowAutoHideButton) point.Offset(-(buttonWidth + ButtonGapBetween), 0); ButtonOptions.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); } private void AutoHide_Click(object sender, EventArgs e) { DockPane.DockState = DockHelper.ToggleAutoHideState(DockPane.DockState); if (DockHelper.IsDockStateAutoHide(DockPane.DockState)) DockPane.DockPanel.ActiveAutoHideContent = null; } private void Options_Click(object sender, EventArgs e) { ShowTabPageContextMenu(PointToClient(Control.MousePosition)); } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); PerformLayout(); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.dll // Description: The core libraries for the DotSpatial project. // // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 2/19/2008 4:16:01 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using DotSpatial.Serialization; namespace DotSpatial.Symbology { /// <summary> /// ColorCategory /// </summary> [ToolboxItem(false), Serializable] public class ColorCategory : Category, IColorCategory { #region Events /// <summary> /// Occurs when this ColorBreak received instructions to show an editor. If this is /// handled, then no action will be taken. /// </summary> public event HandledEventHandler EditItem; #endregion #region Private Variables private readonly List<SymbologyMenuItem> _contextMenuItems; GradientModel _gradientModel; Color _highColor; Color _lowColor; #endregion #region Constructors /// <summary> /// Creates a new instance of ColorCategory /// </summary> public ColorCategory() { _contextMenuItems = new List<SymbologyMenuItem> { new SymbologyMenuItem("Remove Break", Remove_Break), new SymbologyMenuItem("Edit Break", Edit_Break) }; } /// <summary> /// Creates a ColorBreak that has a single value, which can be an object of any type. /// The LowValue field will contain this single value. /// </summary> /// <param name="value">The value to test.</param> public ColorCategory(double value) : base(value) { Configure(); } /// <summary> /// Creates a ColorBreak that has a single value, which can be an object of any type. /// The LowValue field will contain this single value. /// </summary> /// <param name="value">The value to test.</param> /// <param name="color">The color to use as the low value.</param> public ColorCategory(double value, Color color) : base(value) { _lowColor = color; _highColor = color; Configure(); } /// <summary> /// Creates a new color category, but doesn't specify the colors themselves. /// </summary> /// <param name="startValue">The start value</param> /// <param name="endValue">The end value</param> public ColorCategory(double? startValue, double? endValue) : base(startValue, endValue) { } /// <summary> /// Creates a bi-valued colorbreak that will automatically test which of the specified values is higher /// and use that as the high value. The other will become the low value. This will be set to a /// bi-value colorbreak. /// </summary> /// <param name="startValue">One of the values to use in this colorbreak.</param> /// <param name="endValue">The other value to use in this colorbreak.</param> /// <param name="lowColor">The color to assign to the higher of the two values</param> /// <param name="highColor">The color to assign to the lower of the two values</param> public ColorCategory(double? startValue, double? endValue, Color lowColor, Color highColor) : base(startValue, endValue) { _highColor = highColor; _lowColor = lowColor; Configure(); } /// <summary> /// Fires the EditItem event. If e returns handled, then this will not launch the default editor /// </summary> /// <param name="e">The HandledEventArgs</param> protected virtual void OnEditItem(HandledEventArgs e) { if (EditItem != null) EditItem(this, e); } private void Edit_Break(object sender, EventArgs e) { // Allow this action to be overridden by the event var result = new HandledEventArgs(false); OnEditItem(result); if (result.Handled) return; var cca = ColorCategoryActions; if (cca != null) { cca.ShowEdit(this); } } /// <summary> /// Gets or sets custom actions for ColorCategory /// </summary> [Browsable(false)] public IColorCategoryActions ColorCategoryActions { get; set; } /// <inheritdocs/> protected override void OnCopyProperties(object source) { base.OnCopyProperties(source); OnItemChanged(this); } private void Remove_Break(object sender, EventArgs e) { OnRemoveItem(); } private void Configure() { base.LegendSymbolMode = SymbolMode.Symbol; LegendType = LegendType.Symbol; } #endregion #region Methods /// <summary> /// This is primarily used in the BiValue situation where a color needs to be generated /// somewhere between the start value and the end value. /// </summary> /// <param name="value">The value to be converted into a color from the range on this color break</param> /// <returns>A color that is selected from the range values.</returns> public virtual Color CalculateColor(double value) { if (!Range.Contains(value)) return Color.Transparent; if (Minimum == null || Maximum == null) { return Range.Minimum == null ? HighColor : LowColor; } // From here on we have a double that falls in the range somewhere double lowVal = Minimum.Value; double range = Math.Abs(Maximum.Value - lowVal); double p = 0; // the portion of the range, where 0 is LowValue & 1 is HighValue double ht; switch (GradientModel) { case GradientModel.Linear: p = (value - lowVal) / range; break; case GradientModel.Exponential: ht = value; if (ht < 1) ht = 1.0; if (range > 1) { p = (Math.Pow(ht - lowVal, 2) / Math.Pow(range, 2)); } else { return LowColor; } break; case GradientModel.Logarithmic: ht = value; if (ht < 1) ht = 1.0; if (range > 1.0 && ht - lowVal > 1.0) { p = Math.Log(ht - lowVal) / Math.Log(range); } else { return LowColor; } break; } int alpha = ByteRange(LowColor.A + Math.Round((HighColor.A - LowColor.A) * p)); int red = ByteRange(LowColor.R + Math.Round((HighColor.R - LowColor.R) * p)); int green = ByteRange(LowColor.G + Math.Round((HighColor.G - LowColor.G) * p)); int blue = ByteRange(LowColor.B + Math.Round((HighColor.B - LowColor.B) * p)); return Color.FromArgb(alpha, red, green, blue); } #endregion #region Properties /// <summary> /// Gets or sets how the color changes are distributed across the /// BiValued range. If IsBiValue is false, this does nothing. /// </summary> [Serialize("GradientModel")] public virtual GradientModel GradientModel { get { return _gradientModel; } set { _gradientModel = value; } } /// <summary> /// Gets or sets the second of two colors to be used. /// This is only used for BiValued breaks. /// </summary> [Serialize("HighColor")] public virtual Color HighColor { get { return _highColor; } set { _highColor = value; } } /// <summary> /// This not only indicates that there are two values, /// but that the values are also different from one another. /// </summary> public virtual bool IsBiValue { get { if (Range.Minimum == null || Range.Maximum == null) return false; return true; } } /// <summary> /// Gets or sets the color to be used for this break. For /// BiValued breaks, this only sets one of the colors. If /// this is higher than the high value, both are set to this. /// If this equals the high value, IsBiValue will be false. /// </summary> [Serialize("LowColor")] public virtual Color LowColor { get { return _lowColor; } set { _lowColor = value; } } /// <summary> /// Gets or sets the opacity for the low color. This was added to save opacity to dspx. /// </summary> [Serialize("LowColorOpacity")] public float LowColorOpacity { get { return _lowColor.GetOpacity(); } set { _lowColor = _lowColor.ToTransparent(value); } } /// <summary> /// Gets or sets the opacity for the high color. This was added to save opacity to dspx. /// </summary> [Serialize("HighColorOpacity")] public float HighColorOpacity { get { return _highColor.GetOpacity(); } set { _highColor = _highColor.ToTransparent(value); } } #endregion #region IColorCategory Members /// <summary> /// Paints legend symbol /// </summary> /// <param name="g"></param> /// <param name="box"></param> public override void LegendSymbol_Painted(Graphics g, Rectangle box) { if (box.Height == 0) return; Brush b = new LinearGradientBrush(box, _lowColor, _highColor, LinearGradientMode.Horizontal); g.FillRectangle(b, box); g.DrawRectangle(Pens.Black, box); } #endregion } }
/* * 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.Binary { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.Serialization; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Affinity; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Binary.Metadata; using Apache.Ignite.Core.Impl.Cache; using Apache.Ignite.Core.Impl.Cache.Query.Continuous; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Compute; using Apache.Ignite.Core.Impl.Compute.Closure; using Apache.Ignite.Core.Impl.Datastream; using Apache.Ignite.Core.Impl.Deployment; using Apache.Ignite.Core.Impl.Messaging; using Apache.Ignite.Core.Log; /// <summary> /// Marshaller implementation. /// </summary> internal class Marshaller { /** Binary configuration. */ private readonly BinaryConfiguration _cfg; /** Type to descriptor map. */ private readonly CopyOnWriteConcurrentDictionary<Type, BinaryFullTypeDescriptor> _typeToDesc = new CopyOnWriteConcurrentDictionary<Type, BinaryFullTypeDescriptor>(); /** Type name to descriptor map. */ private readonly CopyOnWriteConcurrentDictionary<string, BinaryFullTypeDescriptor> _typeNameToDesc = new CopyOnWriteConcurrentDictionary<string, BinaryFullTypeDescriptor>(); /** ID to descriptor map. */ private readonly CopyOnWriteConcurrentDictionary<long, BinaryFullTypeDescriptor> _idToDesc = new CopyOnWriteConcurrentDictionary<long, BinaryFullTypeDescriptor>(); /** Cached binary types. */ private volatile IDictionary<int, BinaryTypeHolder> _metas = new Dictionary<int, BinaryTypeHolder>(); /** */ private volatile IIgniteInternal _ignite; /** */ private readonly ILogger _log; /// <summary> /// Constructor. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="log"></param> public Marshaller(BinaryConfiguration cfg, ILogger log = null) { _cfg = cfg ?? new BinaryConfiguration(); _log = log; CompactFooter = _cfg.CompactFooter; if (_cfg.TypeConfigurations == null) _cfg.TypeConfigurations = new List<BinaryTypeConfiguration>(); foreach (BinaryTypeConfiguration typeCfg in _cfg.TypeConfigurations) { if (string.IsNullOrEmpty(typeCfg.TypeName)) throw new BinaryObjectException("Type name cannot be null or empty: " + typeCfg); } // Define system types. They use internal reflective stuff, so configuration doesn't affect them. AddSystemTypes(); // 2. Define user types. var typeResolver = new TypeResolver(); ICollection<BinaryTypeConfiguration> typeCfgs = _cfg.TypeConfigurations; if (typeCfgs != null) foreach (BinaryTypeConfiguration typeCfg in typeCfgs) AddUserType(typeCfg, typeResolver); var typeNames = _cfg.Types; if (typeNames != null) foreach (string typeName in typeNames) AddUserType(new BinaryTypeConfiguration(typeName), typeResolver); } /// <summary> /// Gets or sets the backing grid. /// </summary> public IIgniteInternal Ignite { get { return _ignite; } set { Debug.Assert(value != null); _ignite = value; } } /// <summary> /// Gets the compact footer flag. /// </summary> public bool CompactFooter { get; set; } /// <summary> /// Gets or sets a value indicating whether type registration is disabled. /// This may be desirable for static system marshallers where everything is written in unregistered mode. /// </summary> public bool RegistrationDisabled { get; set; } /// <summary> /// Marshal object. /// </summary> /// <param name="val">Value.</param> /// <returns>Serialized data as byte array.</returns> public byte[] Marshal<T>(T val) { using (var stream = new BinaryHeapStream(128)) { Marshal(val, stream); return stream.GetArrayCopy(); } } /// <summary> /// Marshals an object. /// </summary> /// <param name="val">Value.</param> /// <param name="stream">Output stream.</param> private void Marshal<T>(T val, IBinaryStream stream) { BinaryWriter writer = StartMarshal(stream); writer.Write(val); FinishMarshal(writer); } /// <summary> /// Start marshal session. /// </summary> /// <param name="stream">Stream.</param> /// <returns>Writer.</returns> public BinaryWriter StartMarshal(IBinaryStream stream) { return new BinaryWriter(this, stream); } /// <summary> /// Finish marshal session. /// </summary> /// <param name="writer">Writer.</param> /// <returns>Dictionary with metadata.</returns> public void FinishMarshal(BinaryWriter writer) { var metas = writer.GetBinaryTypes(); var ignite = Ignite; if (ignite != null && metas != null && metas.Count > 0) { ignite.BinaryProcessor.PutBinaryTypes(metas); OnBinaryTypesSent(metas); } } /// <summary> /// Unmarshal object. /// </summary> /// <param name="data">Data array.</param> /// <param name="mode">The mode.</param> /// <returns> /// Object. /// </returns> public T Unmarshal<T>(byte[] data, BinaryMode mode = BinaryMode.Deserialize) { using (var stream = new BinaryHeapStream(data)) { return Unmarshal<T>(stream, mode); } } /// <summary> /// Unmarshal object. /// </summary> /// <param name="stream">Stream over underlying byte array with correct position.</param> /// <param name="keepBinary">Whether to keep binary objects in binary form.</param> /// <returns> /// Object. /// </returns> public T Unmarshal<T>(IBinaryStream stream, bool keepBinary) { return Unmarshal<T>(stream, keepBinary ? BinaryMode.KeepBinary : BinaryMode.Deserialize, null); } /// <summary> /// Unmarshal object. /// </summary> /// <param name="stream">Stream over underlying byte array with correct position.</param> /// <param name="mode">The mode.</param> /// <returns> /// Object. /// </returns> public T Unmarshal<T>(IBinaryStream stream, BinaryMode mode = BinaryMode.Deserialize) { return Unmarshal<T>(stream, mode, null); } /// <summary> /// Unmarshal object. /// </summary> /// <param name="stream">Stream over underlying byte array with correct position.</param> /// <param name="mode">The mode.</param> /// <param name="builder">Builder.</param> /// <returns> /// Object. /// </returns> public T Unmarshal<T>(IBinaryStream stream, BinaryMode mode, BinaryObjectBuilder builder) { return new BinaryReader(this, stream, mode, builder).Deserialize<T>(); } /// <summary> /// Start unmarshal session. /// </summary> /// <param name="stream">Stream.</param> /// <param name="keepBinary">Whether to keep binarizable as binary.</param> /// <returns> /// Reader. /// </returns> public BinaryReader StartUnmarshal(IBinaryStream stream, bool keepBinary) { return new BinaryReader(this, stream, keepBinary ? BinaryMode.KeepBinary : BinaryMode.Deserialize, null); } /// <summary> /// Start unmarshal session. /// </summary> /// <param name="stream">Stream.</param> /// <param name="mode">The mode.</param> /// <returns>Reader.</returns> public BinaryReader StartUnmarshal(IBinaryStream stream, BinaryMode mode = BinaryMode.Deserialize) { return new BinaryReader(this, stream, mode, null); } /// <summary> /// Gets metadata for the given type ID. /// </summary> /// <param name="typeId">Type ID.</param> /// <returns>Metadata or null.</returns> public BinaryType GetBinaryType(int typeId) { if (Ignite != null) { var meta = Ignite.BinaryProcessor.GetBinaryType(typeId); if (meta != null) { return meta; } } return BinaryType.Empty; } /// <summary> /// Puts the binary type metadata to Ignite. /// </summary> /// <param name="desc">Descriptor.</param> public void PutBinaryType(IBinaryTypeDescriptor desc) { Debug.Assert(desc != null); GetBinaryTypeHandler(desc); // ensure that handler exists if (Ignite != null) { var metas = new[] {new BinaryType(desc, this)}; Ignite.BinaryProcessor.PutBinaryTypes(metas); OnBinaryTypesSent(metas); } } /// <summary> /// Gets binary type handler for the given type ID. /// </summary> /// <param name="desc">Type descriptor.</param> /// <returns>Binary type handler.</returns> public IBinaryTypeHandler GetBinaryTypeHandler(IBinaryTypeDescriptor desc) { BinaryTypeHolder holder; if (!_metas.TryGetValue(desc.TypeId, out holder)) { lock (this) { if (!_metas.TryGetValue(desc.TypeId, out holder)) { IDictionary<int, BinaryTypeHolder> metas0 = new Dictionary<int, BinaryTypeHolder>(_metas); holder = new BinaryTypeHolder(desc.TypeId, desc.TypeName, desc.AffinityKeyFieldName, desc.IsEnum, this); metas0[desc.TypeId] = holder; _metas = metas0; } } } if (holder != null) { ICollection<int> ids = holder.GetFieldIds(); bool newType = ids.Count == 0 && !holder.Saved(); return new BinaryTypeHashsetHandler(ids, newType); } return null; } /// <summary> /// Callback invoked when metadata has been sent to the server and acknowledged by it. /// </summary> /// <param name="newMetas">Binary types.</param> private void OnBinaryTypesSent(IEnumerable<BinaryType> newMetas) { foreach (var meta in newMetas) { _metas[meta.TypeId].Merge(meta); } } /// <summary> /// Gets descriptor for type. /// </summary> /// <param name="type">Type.</param> /// <returns> /// Descriptor. /// </returns> public IBinaryTypeDescriptor GetDescriptor(Type type) { BinaryFullTypeDescriptor desc; if (!_typeToDesc.TryGetValue(type, out desc) || !desc.IsRegistered) { desc = RegisterType(type, desc); } return desc; } /// <summary> /// Gets descriptor for type name. /// </summary> /// <param name="typeName">Type name.</param> /// <returns>Descriptor.</returns> public IBinaryTypeDescriptor GetDescriptor(string typeName) { BinaryFullTypeDescriptor desc; if (_typeNameToDesc.TryGetValue(typeName, out desc)) { return desc; } var typeId = GetTypeId(typeName, _cfg.IdMapper); return GetDescriptor(true, typeId, typeName: typeName); } /// <summary> /// Gets descriptor for a type id. /// </summary> /// <param name="userType">User type flag.</param> /// <param name="typeId">Type id.</param> /// <param name="requiresType">If set to true, resulting descriptor must have Type property populated. /// <para /> /// When working in binary mode, we don't need Type. And there is no Type at all in some cases. /// So we should not attempt to call BinaryProcessor right away. /// Only when we really deserialize the value, requiresType is set to true /// and we attempt to resolve the type by all means.</param> /// <param name="typeName">Known type name.</param> /// <param name="knownType">Optional known type.</param> /// <returns> /// Descriptor. /// </returns> public IBinaryTypeDescriptor GetDescriptor(bool userType, int typeId, bool requiresType = false, string typeName = null, Type knownType = null) { BinaryFullTypeDescriptor desc; var typeKey = BinaryUtils.TypeKey(userType, typeId); if (_idToDesc.TryGetValue(typeKey, out desc) && (!requiresType || desc.Type != null)) return desc; if (!userType) return null; if (requiresType && _ignite != null) { // Check marshaller context for dynamically registered type. var type = knownType; if (type == null && _ignite != null) { typeName = typeName ?? _ignite.BinaryProcessor.GetTypeName(typeId); if (typeName != null) { type = ResolveType(typeName); if (type == null) { // Type is registered, but assembly is not present. return new BinarySurrogateTypeDescriptor(_cfg, typeId, typeName); } } } if (type != null) { return AddUserType(type, typeId, GetTypeName(type), true, desc); } } var meta = GetBinaryType(typeId); if (meta != BinaryType.Empty) { var typeCfg = new BinaryTypeConfiguration(meta.TypeName) { IsEnum = meta.IsEnum, AffinityKeyFieldName = meta.AffinityKeyFieldName }; return AddUserType(typeCfg, new TypeResolver()); } return new BinarySurrogateTypeDescriptor(_cfg, typeId, typeName); } /// <summary> /// Registers the type. /// </summary> /// <param name="type">The type.</param> /// <param name="desc">Existing descriptor.</param> private BinaryFullTypeDescriptor RegisterType(Type type, BinaryFullTypeDescriptor desc) { Debug.Assert(type != null); var typeName = GetTypeName(type); var typeId = GetTypeId(typeName, _cfg.IdMapper); var registered = _ignite != null && _ignite.BinaryProcessor.RegisterType(typeId, typeName); return AddUserType(type, typeId, typeName, registered, desc); } /// <summary> /// Add user type. /// </summary> /// <param name="type">The type.</param> /// <param name="typeId">The type id.</param> /// <param name="typeName">Name of the type.</param> /// <param name="registered">Registered flag.</param> /// <param name="desc">Existing descriptor.</param> /// <returns>Descriptor.</returns> private BinaryFullTypeDescriptor AddUserType(Type type, int typeId, string typeName, bool registered, BinaryFullTypeDescriptor desc) { Debug.Assert(type != null); Debug.Assert(typeName != null); var ser = GetSerializer(_cfg, null, type, typeId, null, null, _log); desc = desc == null ? new BinaryFullTypeDescriptor(type, typeId, typeName, true, _cfg.NameMapper, _cfg.IdMapper, ser, false, AffinityKeyMappedAttribute.GetFieldNameFromAttribute(type), BinaryUtils.IsIgniteEnum(type), registered) : new BinaryFullTypeDescriptor(desc, type, ser, registered); if (RegistrationDisabled) { return desc; } var typeKey = BinaryUtils.TypeKey(true, typeId); var desc0 = _idToDesc.GetOrAdd(typeKey, x => desc); if (desc0.Type != null && desc0.TypeName != typeName) { ThrowConflictingTypeError(type, desc0.Type, typeId); } desc0 = _typeNameToDesc.GetOrAdd(typeName, x => desc); if (desc0.Type != null && desc0.TypeName != typeName) { ThrowConflictingTypeError(type, desc0.Type, typeId); } _typeToDesc.Set(type, desc); return desc; } /// <summary> /// Throws the conflicting type error. /// </summary> private static void ThrowConflictingTypeError(object type1, object type2, int typeId) { throw new BinaryObjectException(string.Format("Conflicting type IDs [type1='{0}', " + "type2='{1}', typeId={2}]", type1, type2, typeId)); } /// <summary> /// Add user type. /// </summary> /// <param name="typeCfg">Type configuration.</param> /// <param name="typeResolver">The type resolver.</param> /// <exception cref="BinaryObjectException"></exception> private BinaryFullTypeDescriptor AddUserType(BinaryTypeConfiguration typeCfg, TypeResolver typeResolver) { // Get converter/mapper/serializer. IBinaryNameMapper nameMapper = typeCfg.NameMapper ?? _cfg.NameMapper ?? GetDefaultNameMapper(); IBinaryIdMapper idMapper = typeCfg.IdMapper ?? _cfg.IdMapper; bool keepDeserialized = typeCfg.KeepDeserialized ?? _cfg.KeepDeserialized; // Try resolving type. Type type = typeResolver.ResolveType(typeCfg.TypeName); if (type != null) { ValidateUserType(type); if (typeCfg.IsEnum != BinaryUtils.IsIgniteEnum(type)) { throw new BinaryObjectException( string.Format( "Invalid IsEnum flag in binary type configuration. " + "Configuration value: IsEnum={0}, actual type: IsEnum={1}, type={2}", typeCfg.IsEnum, type.IsEnum, type)); } // Type is found. var typeName = GetTypeName(type, nameMapper); int typeId = GetTypeId(typeName, idMapper); var affKeyFld = typeCfg.AffinityKeyFieldName ?? AffinityKeyMappedAttribute.GetFieldNameFromAttribute(type); var serializer = GetSerializer(_cfg, typeCfg, type, typeId, nameMapper, idMapper, _log); return AddType(type, typeId, typeName, true, keepDeserialized, nameMapper, idMapper, serializer, affKeyFld, BinaryUtils.IsIgniteEnum(type)); } else { // Type is not found. string typeName = GetTypeName(typeCfg.TypeName, nameMapper); int typeId = GetTypeId(typeName, idMapper); return AddType(null, typeId, typeName, true, keepDeserialized, nameMapper, idMapper, null, typeCfg.AffinityKeyFieldName, typeCfg.IsEnum); } } /// <summary> /// Gets the serializer. /// </summary> private static IBinarySerializerInternal GetSerializer(BinaryConfiguration cfg, BinaryTypeConfiguration typeCfg, Type type, int typeId, IBinaryNameMapper nameMapper, IBinaryIdMapper idMapper, ILogger log) { var serializer = (typeCfg != null ? typeCfg.Serializer : null) ?? (cfg != null ? cfg.Serializer : null); if (serializer == null) { if (type.GetInterfaces().Contains(typeof(IBinarizable))) return BinarizableSerializer.Instance; if (type.GetInterfaces().Contains(typeof(ISerializable))) { LogSerializableWarning(type, log); return new SerializableSerializer(type); } serializer = new BinaryReflectiveSerializer(); } var refSerializer = serializer as BinaryReflectiveSerializer; return refSerializer != null ? refSerializer.Register(type, typeId, nameMapper, idMapper) : new UserSerializerProxy(serializer); } /// <summary> /// Add type. /// </summary> /// <param name="type">Type.</param> /// <param name="typeId">Type ID.</param> /// <param name="typeName">Type name.</param> /// <param name="userType">User type flag.</param> /// <param name="keepDeserialized">Whether to cache deserialized value in IBinaryObject</param> /// <param name="nameMapper">Name mapper.</param> /// <param name="idMapper">ID mapper.</param> /// <param name="serializer">Serializer.</param> /// <param name="affKeyFieldName">Affinity key field name.</param> /// <param name="isEnum">Enum flag.</param> private BinaryFullTypeDescriptor AddType(Type type, int typeId, string typeName, bool userType, bool keepDeserialized, IBinaryNameMapper nameMapper, IBinaryIdMapper idMapper, IBinarySerializerInternal serializer, string affKeyFieldName, bool isEnum) { Debug.Assert(!string.IsNullOrEmpty(typeName)); long typeKey = BinaryUtils.TypeKey(userType, typeId); BinaryFullTypeDescriptor conflictingType; if (_idToDesc.TryGetValue(typeKey, out conflictingType) && conflictingType.TypeName != typeName) { ThrowConflictingTypeError(typeName, conflictingType.TypeName, typeId); } var descriptor = new BinaryFullTypeDescriptor(type, typeId, typeName, userType, nameMapper, idMapper, serializer, keepDeserialized, affKeyFieldName, isEnum); if (RegistrationDisabled) { return descriptor; } if (type != null) { _typeToDesc.Set(type, descriptor); } if (userType) { _typeNameToDesc.Set(typeName, descriptor); } _idToDesc.Set(typeKey, descriptor); return descriptor; } /// <summary> /// Adds a predefined system type. /// </summary> private void AddSystemType<T>(int typeId, Func<BinaryReader, T> ctor, string affKeyFldName = null, IBinarySerializerInternal serializer = null) where T : IBinaryWriteAware { var type = typeof(T); serializer = serializer ?? new BinarySystemTypeSerializer<T>(ctor); // System types always use simple name mapper. var typeName = type.Name; if (typeId == 0) { typeId = BinaryUtils.GetStringHashCodeLowerCase(typeName); } AddType(type, typeId, typeName, false, false, null, null, serializer, affKeyFldName, false); } /// <summary> /// Adds predefined system types. /// </summary> private void AddSystemTypes() { AddSystemType(BinaryTypeId.NativeJobHolder, r => new ComputeJobHolder(r)); AddSystemType(BinaryTypeId.ComputeJobWrapper, r => new ComputeJobWrapper(r)); AddSystemType(BinaryTypeId.ComputeOutFuncJob, r => new ComputeOutFuncJob(r)); AddSystemType(BinaryTypeId.ComputeOutFuncWrapper, r => new ComputeOutFuncWrapper(r)); AddSystemType(BinaryTypeId.ComputeFuncWrapper, r => new ComputeFuncWrapper(r)); AddSystemType(BinaryTypeId.ComputeFuncJob, r => new ComputeFuncJob(r)); AddSystemType(BinaryTypeId.ComputeActionJob, r => new ComputeActionJob(r)); AddSystemType(BinaryTypeId.ContinuousQueryRemoteFilterHolder, r => new ContinuousQueryFilterHolder(r)); AddSystemType(BinaryTypeId.CacheEntryProcessorHolder, r => new CacheEntryProcessorHolder(r)); AddSystemType(BinaryTypeId.CacheEntryPredicateHolder, r => new CacheEntryFilterHolder(r)); AddSystemType(BinaryTypeId.MessageListenerHolder, r => new MessageListenerHolder(r)); AddSystemType(BinaryTypeId.StreamReceiverHolder, r => new StreamReceiverHolder(r)); AddSystemType(0, r => new AffinityKey(r), "affKey"); AddSystemType(BinaryTypeId.PlatformJavaObjectFactoryProxy, r => new PlatformJavaObjectFactoryProxy()); AddSystemType(0, r => new ObjectInfoHolder(r)); AddSystemType(BinaryTypeId.IgniteUuid, r => new IgniteGuid(r)); AddSystemType(0, r => new GetAssemblyFunc()); AddSystemType(0, r => new AssemblyRequest(r)); AddSystemType(0, r => new AssemblyRequestResult(r)); AddSystemType<PeerLoadingObjectHolder>(0, null, serializer: new PeerLoadingObjectHolderSerializer()); AddSystemType<MultidimensionalArrayHolder>(0, null, serializer: new MultidimensionalArraySerializer()); } /// <summary> /// Logs the warning about ISerializable pitfalls. /// </summary> private static void LogSerializableWarning(Type type, ILogger log) { if (log == null) return; log.GetLogger(typeof(Marshaller).Name) .Warn("Type '{0}' implements '{1}'. It will be written in Ignite binary format, however, " + "the following limitations apply: " + "DateTime fields would not work in SQL; " + "sbyte, ushort, uint, ulong fields would not work in DML.", type, typeof(ISerializable)); } /// <summary> /// Validates binary type. /// </summary> // ReSharper disable once UnusedParameter.Local private static void ValidateUserType(Type type) { Debug.Assert(type != null); if (type.IsGenericTypeDefinition) { throw new BinaryObjectException( "Open generic types (Type.IsGenericTypeDefinition == true) are not allowed " + "in BinaryConfiguration: " + type.AssemblyQualifiedName); } if (type.IsAbstract) { throw new BinaryObjectException( "Abstract types and interfaces are not allowed in BinaryConfiguration: " + type.AssemblyQualifiedName); } } /// <summary> /// Resolves the type (opposite of <see cref="GetTypeName(Type, IBinaryNameMapper)"/>). /// </summary> public Type ResolveType(string typeName) { return new TypeResolver().ResolveType(typeName, nameMapper: _cfg.NameMapper ?? GetDefaultNameMapper()); } /// <summary> /// Gets the name of the type according to current name mapper. /// See also <see cref="ResolveType"/>. /// </summary> public string GetTypeName(Type type, IBinaryNameMapper mapper = null) { return GetTypeName(type.AssemblyQualifiedName, mapper); } /// <summary> /// Called when local client node has been reconnected to the cluster. /// </summary> /// <param name="clusterRestarted">Cluster restarted flag.</param> public void OnClientReconnected(bool clusterRestarted) { if (!clusterRestarted) return; // Reset all binary structures. Metadata must be sent again. // _idToDesc enumerator is thread-safe (returns a snapshot). // If there are new descriptors added concurrently, they are fine (we are already connected). // Race is possible when serialization is started before reconnect (or even before disconnect) // and finished after reconnect, meta won't be sent to cluster because it is assumed to be known, // but operation will succeed. // We don't support this use case. Users should handle reconnect events properly when cluster is restarted. // Supporting this very rare use case will complicate the code a lot with little benefit. foreach (var desc in _idToDesc) { desc.Value.ResetWriteStructure(); } } /// <summary> /// Gets the name of the type. /// </summary> private string GetTypeName(string fullTypeName, IBinaryNameMapper mapper = null) { mapper = mapper ?? _cfg.NameMapper ?? GetDefaultNameMapper(); var typeName = mapper.GetTypeName(fullTypeName); if (typeName == null) { throw new BinaryObjectException("IBinaryNameMapper returned null name for type [typeName=" + fullTypeName + ", mapper=" + mapper + "]"); } return typeName; } /// <summary> /// Resolve type ID. /// </summary> /// <param name="typeName">Type name.</param> /// <param name="idMapper">ID mapper.</param> private static int GetTypeId(string typeName, IBinaryIdMapper idMapper) { Debug.Assert(typeName != null); int id = 0; if (idMapper != null) { try { id = idMapper.GetTypeId(typeName); } catch (Exception e) { throw new BinaryObjectException("Failed to resolve type ID due to ID mapper exception " + "[typeName=" + typeName + ", idMapper=" + idMapper + ']', e); } } if (id == 0) { id = BinaryUtils.GetStringHashCodeLowerCase(typeName); } return id; } /// <summary> /// Gets the default name mapper. /// </summary> private static IBinaryNameMapper GetDefaultNameMapper() { return BinaryBasicNameMapper.FullNameInstance; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Globalization { /// <remarks> /// Calendar support range: /// Calendar Minimum Maximum /// ========== ========== ========== /// Gregorian 1912/02/18 2051/02/10 /// TaiwanLunisolar 1912/01/01 2050/13/29 /// </remarks> public class TaiwanLunisolarCalendar : EastAsianLunisolarCalendar { // Since // Gregorian Year = Era Year + yearOffset // When Gregorian Year 1912 is year 1, so that // 1912 = 1 + yearOffset // So yearOffset = 1911 private static readonly EraInfo[] s_taiwanLunisolarEraInfo = new EraInfo[] { new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear }; private readonly GregorianCalendarHelper _helper; private const int MinLunisolarYear = 1912; private const int MaxLunisolarYear = 2050; private static readonly DateTime s_minDate = new DateTime(1912, 2, 18); private static readonly DateTime s_maxDate = new DateTime((new DateTime(2051, 2, 10, 23, 59, 59, 999)).Ticks + 9999); public override DateTime MinSupportedDateTime => s_minDate; public override DateTime MaxSupportedDateTime => s_maxDate; protected override int DaysInYearBeforeMinSupportedYear { get { // 1911 from ChineseLunisolarCalendar return 384; } } private static readonly int[,] s_yinfo = { /*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days 1912 */ { 0 , 2 , 18 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 1913 */{ 0 , 2 , 6 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 1914 */{ 5 , 1 , 26 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384 1915 */{ 0 , 2 , 14 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 1916 */{ 0 , 2 , 3 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355 1917 */{ 2 , 1 , 23 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 1918 */{ 0 , 2 , 11 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1919 */{ 7 , 2 , 1 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384 1920 */{ 0 , 2 , 20 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1921 */{ 0 , 2 , 8 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 1922 */{ 5 , 1 , 28 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 1923 */{ 0 , 2 , 16 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 1924 */{ 0 , 2 , 5 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 1925 */{ 4 , 1 , 24 , 44456 },/* 30 29 30 29 30 30 29 30 30 29 30 29 30 385 1926 */{ 0 , 2 , 13 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1927 */{ 0 , 2 , 2 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355 1928 */{ 2 , 1 , 23 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384 1929 */{ 0 , 2 , 10 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1930 */{ 6 , 1 , 30 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 29 383 1931 */{ 0 , 2 , 17 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 1932 */{ 0 , 2 , 6 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 1933 */{ 5 , 1 , 26 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384 1934 */{ 0 , 2 , 14 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355 1935 */{ 0 , 2 , 4 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1936 */{ 3 , 1 , 24 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384 1937 */{ 0 , 2 , 11 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 1938 */{ 7 , 1 , 31 , 51560 },/* 30 30 29 29 30 29 29 30 29 30 30 29 30 384 1939 */{ 0 , 2 , 19 , 51536 },/* 30 30 29 29 30 29 29 30 29 30 29 30 0 354 1940 */{ 0 , 2 , 8 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 1941 */{ 6 , 1 , 27 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 29 384 1942 */{ 0 , 2 , 15 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 1943 */{ 0 , 2 , 5 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 1944 */{ 4 , 1 , 25 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 1945 */{ 0 , 2 , 13 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 1946 */{ 0 , 2 , 2 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 1947 */{ 2 , 1 , 22 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 1948 */{ 0 , 2 , 10 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 1949 */{ 7 , 1 , 29 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384 1950 */{ 0 , 2 , 17 , 27808 },/* 29 30 30 29 30 30 29 29 30 29 30 29 0 354 1951 */{ 0 , 2 , 6 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 1952 */{ 5 , 1 , 27 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 1953 */{ 0 , 2 , 14 , 19872 },/* 29 30 29 29 30 30 29 30 30 29 30 29 0 354 1954 */{ 0 , 2 , 3 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 1955 */{ 3 , 1 , 24 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 1956 */{ 0 , 2 , 12 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 1957 */{ 8 , 1 , 31 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 29 383 1958 */{ 0 , 2 , 18 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 0 355 1959 */{ 0 , 2 , 8 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 1960 */{ 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384 1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355 1962 */{ 0 , 2 , 5 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 1965 */{ 0 , 2 , 2 , 21088 },/* 29 30 29 30 29 29 30 29 29 30 30 29 0 353 1966 */{ 3 , 1 , 21 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384 1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355 1968 */{ 7 , 1 , 30 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 1970 */{ 0 , 2 , 6 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 1972 */{ 0 , 2 , 15 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354 1973 */{ 0 , 2 , 3 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 1976 */{ 8 , 1 , 31 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384 1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 1978 */{ 0 , 2 , 7 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355 1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 1982 */{ 4 , 1 , 25 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 1987 */{ 6 , 1 , 29 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 29 384 1988 */{ 0 , 2 , 17 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355 1989 */{ 0 , 2 , 6 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355 1990 */{ 5 , 1 , 27 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384 1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354 1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383 1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 1995 */{ 8 , 1 , 31 , 27432 },/* 29 30 30 29 30 29 30 30 29 29 30 29 30 384 1996 */{ 0 , 2 , 19 , 23232 },/* 29 30 29 30 30 29 30 29 30 30 29 29 0 354 1997 */{ 0 , 2 , 7 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355 1998 */{ 5 , 1 , 28 , 37736 },/* 30 29 29 30 29 29 30 30 29 30 30 29 30 384 1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354 2001 */{ 4 , 1 , 24 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384 2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355 2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 2005 */{ 0 , 2 , 9 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354 2012 */{ 4 , 1 , 23 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384 2013 */{ 0 , 2 , 10 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354 2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 2017 */{ 6 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 2019 */{ 0 , 2 , 5 , 43312 },/* 30 29 30 29 30 29 29 30 29 29 30 30 0 354 2020 */{ 4 , 1 , 25 , 29864 },/* 29 30 30 30 29 30 29 29 30 29 30 29 30 384 2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 2023 */{ 2 , 1 , 22 , 19880 },/* 29 30 29 29 30 30 29 30 30 29 30 29 30 384 2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 2026 */{ 0 , 2 , 17 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354 2027 */{ 0 , 2 , 6 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354 2028 */{ 5 , 1 , 26 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384 2029 */{ 0 , 2 , 13 , 54576 },/* 30 30 29 30 29 30 29 30 29 29 30 30 0 355 2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354 2031 */{ 3 , 1 , 23 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 29 384 2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 2034 */{ 0 , 2 , 19 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354 2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 2036 */{ 6 , 1 , 28 , 53848 },/* 30 30 29 30 29 29 30 29 29 30 29 30 30 384 2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354 2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384 2040 */{ 0 , 2 , 12 , 46496 },/* 30 29 30 30 29 30 29 30 30 29 30 29 0 355 2041 */{ 0 , 2 , 1 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355 2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384 2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 2046 */{ 0 , 2 , 6 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354 2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384 2048 */{ 0 , 2 , 14 , 27936 },/* 29 30 30 29 30 30 29 30 29 29 30 29 0 354 2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355 2050 */{ 3 , 1 , 23 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384 */}; internal override int MinCalendarYear => MinLunisolarYear; internal override int MaxCalendarYear => MaxLunisolarYear; internal override DateTime MinDate => s_minDate; internal override DateTime MaxDate => s_maxDate; internal override EraInfo[]? CalEraInfo => s_taiwanLunisolarEraInfo; internal override int GetYearInfo(int lunarYear, int index) { if ((lunarYear < MinLunisolarYear) || (lunarYear > MaxLunisolarYear)) { throw new ArgumentOutOfRangeException( "year", lunarYear, SR.Format(SR.ArgumentOutOfRange_Range, MinLunisolarYear, MaxLunisolarYear)); } return s_yinfo[lunarYear - MinLunisolarYear, index]; } internal override int GetYear(int year, DateTime time) { return _helper.GetYear(year, time); } internal override int GetGregorianYear(int year, int era) { return _helper.GetGregorianYear(year, era); } public TaiwanLunisolarCalendar() { _helper = new GregorianCalendarHelper(this, s_taiwanLunisolarEraInfo); } public override int GetEra(DateTime time) => _helper.GetEra(time); internal override CalendarId BaseCalendarID => CalendarId.TAIWAN; internal override CalendarId ID => CalendarId.TAIWANLUNISOLAR; public override int[] Eras => _helper.Eras; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CocosSharp; namespace tests { public class RendererTestScene : TestScene { static int sceneIdx = -1; static int MAX_LAYER = 0; public RendererTestScene () : base() { MAX_LAYER = rendererCreateFunctions.Length; } protected override void NextTestCase() { nextRendererAction(); } protected override void PreviousTestCase() { backRendererAction(); } protected override void RestTestCase() { restartRendererAction(); } public static CCLayer nextRendererAction() { sceneIdx++; sceneIdx = sceneIdx % MAX_LAYER; CCLayer pLayer = CreateRendererLayer(sceneIdx); return pLayer; } public static CCLayer backRendererAction() { sceneIdx--; int total = MAX_LAYER; if (sceneIdx < 0) sceneIdx += total; CCLayer pLayer = CreateRendererLayer(sceneIdx); return pLayer; } public static CCLayer restartRendererAction() { CCLayer pLayer = CreateRendererLayer(sceneIdx); return pLayer; } static Func<CCLayer>[] rendererCreateFunctions = { () => new RendererSpriteLabelTest(), () => new NewSpriteTest(), () => new NewDrawNodeTest(), () => new RendererBufferOverflowTest(), () => new CaptureScreenTest(), () => new RendererSpriteLabelTest(), }; public static CCLayer CreateRendererLayer(int index) { return rendererCreateFunctions[index](); } public override void runThisTest() { CCLayer pLayer = nextRendererAction(); AddChild(pLayer); Scene.Director.ReplaceScene(this); } } public class RendererDemo : TestNavigationLayer { //protected: public RendererDemo() { } public override string Title { get { return "No title"; } } public override string Subtitle { get { return string.Empty; } } public override void RestartCallback(object sender) { base.RestartCallback(sender); CCScene s = new RendererTestScene(); s.AddChild(RendererTestScene.restartRendererAction()); Director.ReplaceScene(s); } public override void NextCallback(object sender) { base.NextCallback(sender); CCScene s = new RendererTestScene(); s.AddChild(RendererTestScene.nextRendererAction()); Director.ReplaceScene(s); } public override void BackCallback(object sender) { base.BackCallback(sender); CCScene s = new RendererTestScene(); s.AddChild(RendererTestScene.backRendererAction()); Director.ReplaceScene(s); } } public class NewSpriteTest : RendererDemo { public NewSpriteTest() { } protected override void AddedToScene() { base.AddedToScene(); var visibleRect = VisibleBoundsWorldspace; createSpriteTest(); createNewSpriteTest(); } void createSpriteTest() { var winSize = VisibleBoundsWorldspace.Size; var parent = new CCSprite("Images/grossini"); parent.Position = new CCPoint(winSize.Width / 4, winSize.Height / 2); var child1 = new CCSprite("Images/grossinis_sister1.png"); child1.Position = new CCPoint(0.0f, -20.0f); var child2 = new CCSprite("Images/grossinis_sister2.png"); child2.Position = new CCPoint(20.0f, -20.0f); var child3 = new CCSprite("Images/grossinis_sister1.png"); child3.Position = new CCPoint(40.0f, -20.0f); var child4 = new CCSprite("Images/grossinis_sister2.png"); child4.Position = new CCPoint(60.0f, -20.0f); var child5 = new CCSprite("Images/grossinis_sister2.png"); child5.Position = new CCPoint(80.0f, -20.0f); var child6 = new CCSprite("Images/grossinis_sister2.png"); child6.Position = new CCPoint(100.0f, -20.0f); var child7 = new CCSprite("Images/grossinis_sister2.png"); child7.Position = new CCPoint(120.0f, -20.0f); parent.AddChild(child1); parent.AddChild(child2); parent.AddChild(child3); parent.AddChild(child4); parent.AddChild(child5); parent.AddChild(child6); parent.AddChild(child7); AddChild(parent); } void createNewSpriteTest() { var winSize = VisibleBoundsWorldspace.Size; var parent = new CCSprite("Images/grossini.png"); parent.Position = new CCPoint(winSize.Width * 2 / 3, winSize.Height / 2); var child1 = new CCSprite("Images/grossinis_sister1.png"); child1.Position = new CCPoint(0.0f, -20.0f); var child2 = new CCSprite("Images/grossinis_sister2.png"); child2.Position = new CCPoint(20.0f, -20.0f); var child3 = new CCSprite("Images/grossinis_sister1.png"); child3.Position = new CCPoint(40.0f, -20.0f); var child4 = new CCSprite("Images/grossinis_sister2.png"); child4.Position = new CCPoint(60.0f, -20.0f); var child5 = new CCSprite("Images/grossinis_sister2.png"); child5.Position = new CCPoint(80.0f, -20.0f); var child6 = new CCSprite("Images/grossinis_sister2.png"); child6.Position = new CCPoint(100.0f, -20.0f); var child7 = new CCSprite("Images/grossinis_sister2.png"); child7.Position = new CCPoint(120.0f, -20.0f); parent.AddChild(child1); parent.AddChild(child2); parent.AddChild(child3); parent.AddChild(child4); parent.AddChild(child5); parent.AddChild(child6); parent.AddChild(child7); AddChild(parent); } public override string Title { get { return "Renderer"; } } public override string Subtitle { get { return "SpriteTest"; } } } public class NewDrawNodeTest : RendererDemo { public NewDrawNodeTest() { } protected override void AddedToScene() { base.AddedToScene(); var s = VisibleBoundsWorldspace.Size; var parent = new CCNode(); parent.Position = new CCPoint(s.Width / 2, s.Height / 2); AddChild(parent); var rectNode = new CCDrawNode(); CCPoint[] rectangle = new CCPoint [] { new CCPoint(-50, -50), new CCPoint(50, -50), new CCPoint(50, 50), new CCPoint(-50, 50) }; var white = new CCColor4F(1, 1, 1, 1); rectNode.DrawPolygon(rectangle, 4, white, 1, white); parent.AddChild(rectNode); } public override string Title { get { return "Renderer"; } } public override string Subtitle { get { return "DrawNode"; } } } public class RendererBufferOverflowTest : RendererDemo { public RendererBufferOverflowTest() { } protected override void AddedToScene() { base.AddedToScene(); var s = VisibleBoundsWorldspace.Size; var parent = new CCNode(); parent.Position = new CCPoint(0, 0); AddChild(parent); for (int i = 0; i < 10000 / 3.9; ++i) { var sprite = new CCSprite("Images/grossini_dance_01.png"); sprite.Scale = 0.1f; sprite.Position = new CCPoint(CCMacros.CCRandomBetween0And1() * s.Width, CCMacros.CCRandomBetween0And1() * s.Height); parent.AddChild(sprite); } } public override string Title { get { return "Renderer"; } } public override string Subtitle { get { return "Buffer overflow"; } } } public class CaptureScreenTest : RendererDemo { public CaptureScreenTest() { } protected override void AddedToScene() { base.AddedToScene(); var s = VisibleBoundsWorldspace.Size; var left = new CCPoint (s.Width / 4, s.Height / 2); var right = new CCPoint (s.Width / 4 * 3, s.Height / 2); var sp1 = new CCSprite("Images/grossini.png"); sp1.Position = new CCPoint(left); var move1 = new CCMoveBy(1, new CCPoint(s.Width / 2, 0)); AddChild(sp1); sp1.RepeatForever(move1, move1.Reverse()); var sp2 = new CCSprite("Images/grossinis_sister1.png"); sp2.Position = new CCPoint(right); var move2 = new CCMoveBy(1, new CCPoint(-s.Width / 2, 0)); AddChild(sp2); sp2.RepeatForever(move2, move2.Reverse()); var label1 = new CCLabel("capture all", "fonts/arial", 24, CCLabelFormat.SpriteFont); var mi1 = new CCMenuItemLabel(label1, OnCapture); var menu = new CCMenu(mi1); AddChild(menu); menu.Position = new CCPoint(s.Width / 2, s.Height / 4); } CCRenderTexture target; int childTag = 1001; void OnCapture(object sender) { RemoveChildByTag(childTag); var windowSize = VisibleBoundsWorldspace.Size; // create a render texture, this is what we are going to draw into target = new CCRenderTexture(windowSize, windowSize, CCSurfaceFormat.Color, CCDepthFormat.None, CCRenderTargetUsage.PreserveContents); target.Sprite.Position = windowSize.Center; target.Sprite.AnchorPoint = CCPoint.AnchorMiddle; // begin drawing to the render texture target.BeginWithClear(CCColor4B.Blue); Layer.Visit(); // finish drawing and return context back to the screen target.End(); AddChild(target.Sprite, 0, childTag); target.Sprite.Scale = 0.25f; } public override string Title { get { return "Renderer"; } } public override string Subtitle { get { return "Capture screen test, press the menu item to capture the screen"; } } } public class RendererSpriteLabelTest : RendererDemo { class Button : CCNode { CCSprite buttonSprite; public event TriggeredHandler Triggered; // A delegate type for hooking up button triggered events public delegate void TriggeredHandler(object sender, EventArgs e); private Button() { AttachListener(); } public Button(CCSprite sprite, CCLabel label) : this() { this.ContentSize = sprite.ScaledContentSize; sprite.AnchorPoint = CCPoint.AnchorLowerLeft; label.Position = sprite.ContentSize.Center; // Create the render texture to draw to. It will be the size of the button background sprite var render = new CCRenderTexture(sprite.ContentSize, sprite.ContentSize); // Clear it to any background color you want render.BeginWithClear(CCColor4B.Transparent); // Render the background sprite to the render texture sprite.Visit(); // Render the label to the render texture label.Visit(); // End the rendering render.End(); // Add the button sprite to this node so it can be rendered buttonSprite = render.Sprite; buttonSprite.AnchorPoint = CCPoint.AnchorMiddle; AddChild(this.buttonSprite); } void AttachListener() { // Register Touch Event var listener = new CCEventListenerTouchOneByOne(); listener.IsSwallowTouches = true; listener.OnTouchBegan = OnTouchBegan; listener.OnTouchEnded = OnTouchEnded; listener.OnTouchCancelled = OnTouchCancelled; AddEventListener(listener, this); } bool touchHits(CCTouch touch) { var location = touch.Location; var area = buttonSprite.BoundingBox; return area.ContainsPoint(buttonSprite.WorldToParentspace(location)); } bool OnTouchBegan(CCTouch touch, CCEvent touchEvent) { bool hits = touchHits(touch); if (hits) { // undo the rotation that was applied by the action attached. Rotation = 0; scaleButtonTo(0.9f); } return hits; } void OnTouchEnded(CCTouch touch, CCEvent touchEvent) { bool hits = touchHits(touch); if (hits && Triggered != null) Triggered(this, EventArgs.Empty); scaleButtonTo(1); } void OnTouchCancelled(CCTouch touch, CCEvent touchEvent) { scaleButtonTo(1); } void scaleButtonTo(float scale) { var action = new CCScaleTo(0.1f, scale); action.Tag = 900; StopAction(900); RunAction(action); } } public RendererSpriteLabelTest() { } protected override void AddedToScene() { base.AddedToScene(); var winSize = VisibleBoundsWorldspace.Size; var moveTo = new CCMoveBy(1.0f, new CCPoint(30, 0)); var moveBack = moveTo.Reverse(); var rotateBy = new CCRotateBy(1.0f, 180); var scaleBy = new CCScaleTo(1.0f, -2.0f); var action = new CCSequence(moveTo, moveBack, rotateBy, scaleBy); var buttonNormal = new CCSprite("Images/animationbuttonnormal.png"); var button1 = new Button(buttonNormal, new CCLabel("Click", "fonts/arial", 20, CCLabelFormat.SpriteFont)); button1.Position = winSize.Center; button1.PositionX -= 100; button1.PositionY += 100; AddChild(button1); button1.RunAction(action); var button2 = new Button(buttonNormal, new CCLabel("Me", "fonts/arial", 20, CCLabelFormat.SpriteFont)); button2.Position = winSize.Center; button2.PositionX += 100; button2.PositionY += 100; AddChild(button2); button2.RunAction(action); var button3 = new Button(buttonNormal, new CCLabel("Ple", "fonts/arial", 20, CCLabelFormat.SpriteFont)); button3.Position = winSize.Center; button3.PositionX -= 100; button3.PositionY -= 100; AddChild(button3); button3.RunAction(action); var button4 = new Button(buttonNormal, new CCLabel("ase", "fonts/arial", 20, CCLabelFormat.SpriteFont)); button4.Position = winSize.Center; button4.PositionX += 100; button4.PositionY -= 100; AddChild(button4); button4.RunAction(action); } public override string Title { get { return "Renderer"; } } public override string Subtitle { get { return "Render Sprite Label Test"; } } } }
#if !EXCLUDE_CODEGEN #pragma warning disable 162 #pragma warning disable 219 #pragma warning disable 414 #pragma warning disable 649 #pragma warning disable 693 #pragma warning disable 1591 #pragma warning disable 1998 [assembly: global::System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.2.0.0")] [assembly: global::Orleans.CodeGeneration.OrleansCodeGenerationTargetAttribute("Raft.Interfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")] namespace Raft.Interfaces { using global::Orleans.Async; using global::Orleans; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.2.0.0"), global::System.SerializableAttribute, global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute, global::Orleans.CodeGeneration.GrainReferenceAttribute(typeof (global::Raft.Interfaces.ISafetyMonitor))] internal class OrleansCodeGenSafetyMonitorReference : global::Orleans.Runtime.GrainReference, global::Raft.Interfaces.ISafetyMonitor { protected @OrleansCodeGenSafetyMonitorReference(global::Orleans.Runtime.GrainReference @other): base (@other) { } protected @OrleansCodeGenSafetyMonitorReference(global::System.Runtime.Serialization.SerializationInfo @info, global::System.Runtime.Serialization.StreamingContext @context): base (@info, @context) { } protected override global::System.Int32 InterfaceId { get { return -30188181; } } public override global::System.String InterfaceName { get { return "global::Raft.Interfaces.ISafetyMonitor"; } } public override global::System.Boolean @IsCompatible(global::System.Int32 @interfaceId) { return @interfaceId == -30188181; } protected override global::System.String @GetMethodName(global::System.Int32 @interfaceId, global::System.Int32 @methodId) { switch (@interfaceId) { case -30188181: switch (@methodId) { case 1518790450: return "NotifyLeaderElected"; default: throw new global::System.NotImplementedException("interfaceId=" + -30188181 + ",methodId=" + @methodId); } default: throw new global::System.NotImplementedException("interfaceId=" + @interfaceId); } } public global::System.Threading.Tasks.Task @NotifyLeaderElected(global::System.Int32 @term) { return base.@InvokeMethodAsync<global::System.Object>(1518790450, new global::System.Object[]{@term}); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.2.0.0"), global::Orleans.CodeGeneration.MethodInvokerAttribute("global::Raft.Interfaces.ISafetyMonitor", -30188181, typeof (global::Raft.Interfaces.ISafetyMonitor)), global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] internal class OrleansCodeGenSafetyMonitorMethodInvoker : global::Orleans.CodeGeneration.IGrainMethodInvoker { public global::System.Threading.Tasks.Task<global::System.Object> @Invoke(global::Orleans.Runtime.IAddressable @grain, global::Orleans.CodeGeneration.InvokeMethodRequest @request) { global::System.Int32 interfaceId = @request.@InterfaceId; global::System.Int32 methodId = @request.@MethodId; global::System.Object[] arguments = @request.@Arguments; try { if (@grain == null) throw new global::System.ArgumentNullException("grain"); switch (interfaceId) { case -30188181: switch (methodId) { case 1518790450: return ((global::Raft.Interfaces.ISafetyMonitor)@grain).@NotifyLeaderElected((global::System.Int32)arguments[0]).@Box(); default: throw new global::System.NotImplementedException("interfaceId=" + -30188181 + ",methodId=" + methodId); } default: throw new global::System.NotImplementedException("interfaceId=" + interfaceId); } } catch (global::System.Exception exception) { return global::Orleans.Async.TaskUtility.@Faulted(exception); } } public global::System.Int32 InterfaceId { get { return -30188181; } } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.2.0.0"), global::System.SerializableAttribute, global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute, global::Orleans.CodeGeneration.GrainReferenceAttribute(typeof (global::Raft.Interfaces.IClient))] internal class OrleansCodeGenClientReference : global::Orleans.Runtime.GrainReference, global::Raft.Interfaces.IClient { protected @OrleansCodeGenClientReference(global::Orleans.Runtime.GrainReference @other): base (@other) { } protected @OrleansCodeGenClientReference(global::System.Runtime.Serialization.SerializationInfo @info, global::System.Runtime.Serialization.StreamingContext @context): base (@info, @context) { } protected override global::System.Int32 InterfaceId { get { return 108865850; } } public override global::System.String InterfaceName { get { return "global::Raft.Interfaces.IClient"; } } public override global::System.Boolean @IsCompatible(global::System.Int32 @interfaceId) { return @interfaceId == 108865850; } protected override global::System.String @GetMethodName(global::System.Int32 @interfaceId, global::System.Int32 @methodId) { switch (@interfaceId) { case 108865850: switch (@methodId) { case -1605520623: return "Configure"; case -1339241695: return "ProcessResponse"; default: throw new global::System.NotImplementedException("interfaceId=" + 108865850 + ",methodId=" + @methodId); } default: throw new global::System.NotImplementedException("interfaceId=" + @interfaceId); } } public global::System.Threading.Tasks.Task @Configure(global::System.Int32 @clusterId) { return base.@InvokeMethodAsync<global::System.Object>(-1605520623, new global::System.Object[]{@clusterId}); } public global::System.Threading.Tasks.Task @ProcessResponse() { return base.@InvokeMethodAsync<global::System.Object>(-1339241695, null); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.2.0.0"), global::Orleans.CodeGeneration.MethodInvokerAttribute("global::Raft.Interfaces.IClient", 108865850, typeof (global::Raft.Interfaces.IClient)), global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] internal class OrleansCodeGenClientMethodInvoker : global::Orleans.CodeGeneration.IGrainMethodInvoker { public global::System.Threading.Tasks.Task<global::System.Object> @Invoke(global::Orleans.Runtime.IAddressable @grain, global::Orleans.CodeGeneration.InvokeMethodRequest @request) { global::System.Int32 interfaceId = @request.@InterfaceId; global::System.Int32 methodId = @request.@MethodId; global::System.Object[] arguments = @request.@Arguments; try { if (@grain == null) throw new global::System.ArgumentNullException("grain"); switch (interfaceId) { case 108865850: switch (methodId) { case -1605520623: return ((global::Raft.Interfaces.IClient)@grain).@Configure((global::System.Int32)arguments[0]).@Box(); case -1339241695: return ((global::Raft.Interfaces.IClient)@grain).@ProcessResponse().@Box(); default: throw new global::System.NotImplementedException("interfaceId=" + 108865850 + ",methodId=" + methodId); } default: throw new global::System.NotImplementedException("interfaceId=" + interfaceId); } } catch (global::System.Exception exception) { return global::Orleans.Async.TaskUtility.@Faulted(exception); } } public global::System.Int32 InterfaceId { get { return 108865850; } } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.2.0.0"), global::System.SerializableAttribute, global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute, global::Orleans.CodeGeneration.GrainReferenceAttribute(typeof (global::Raft.Interfaces.IClusterManager))] internal class OrleansCodeGenClusterManagerReference : global::Orleans.Runtime.GrainReference, global::Raft.Interfaces.IClusterManager { protected @OrleansCodeGenClusterManagerReference(global::Orleans.Runtime.GrainReference @other): base (@other) { } protected @OrleansCodeGenClusterManagerReference(global::System.Runtime.Serialization.SerializationInfo @info, global::System.Runtime.Serialization.StreamingContext @context): base (@info, @context) { } protected override global::System.Int32 InterfaceId { get { return 2139488188; } } public override global::System.String InterfaceName { get { return "global::Raft.Interfaces.IClusterManager"; } } public override global::System.Boolean @IsCompatible(global::System.Int32 @interfaceId) { return @interfaceId == 2139488188; } protected override global::System.String @GetMethodName(global::System.Int32 @interfaceId, global::System.Int32 @methodId) { switch (@interfaceId) { case 2139488188: switch (@methodId) { case -227017028: return "Configure"; case 1647346573: return "NotifyLeaderUpdate"; case -1686842035: return "RelayClientRequest"; case -1360605994: return "RedirectClientRequest"; default: throw new global::System.NotImplementedException("interfaceId=" + 2139488188 + ",methodId=" + @methodId); } default: throw new global::System.NotImplementedException("interfaceId=" + @interfaceId); } } public global::System.Threading.Tasks.Task @Configure() { return base.@InvokeMethodAsync<global::System.Object>(-227017028, null); } public global::System.Threading.Tasks.Task @NotifyLeaderUpdate(global::System.Int32 @leaderId, global::System.Int32 @term) { return base.@InvokeMethodAsync<global::System.Object>(1647346573, new global::System.Object[]{@leaderId, @term}); } public global::System.Threading.Tasks.Task @RelayClientRequest(global::System.Int32 @clientId, global::System.Int32 @command) { return base.@InvokeMethodAsync<global::System.Object>(-1686842035, new global::System.Object[]{@clientId, @command}); } public global::System.Threading.Tasks.Task @RedirectClientRequest(global::System.Int32 @clientId, global::System.Int32 @command) { return base.@InvokeMethodAsync<global::System.Object>(-1360605994, new global::System.Object[]{@clientId, @command}); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.2.0.0"), global::Orleans.CodeGeneration.MethodInvokerAttribute("global::Raft.Interfaces.IClusterManager", 2139488188, typeof (global::Raft.Interfaces.IClusterManager)), global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] internal class OrleansCodeGenClusterManagerMethodInvoker : global::Orleans.CodeGeneration.IGrainMethodInvoker { public global::System.Threading.Tasks.Task<global::System.Object> @Invoke(global::Orleans.Runtime.IAddressable @grain, global::Orleans.CodeGeneration.InvokeMethodRequest @request) { global::System.Int32 interfaceId = @request.@InterfaceId; global::System.Int32 methodId = @request.@MethodId; global::System.Object[] arguments = @request.@Arguments; try { if (@grain == null) throw new global::System.ArgumentNullException("grain"); switch (interfaceId) { case 2139488188: switch (methodId) { case -227017028: return ((global::Raft.Interfaces.IClusterManager)@grain).@Configure().@Box(); case 1647346573: return ((global::Raft.Interfaces.IClusterManager)@grain).@NotifyLeaderUpdate((global::System.Int32)arguments[0], (global::System.Int32)arguments[1]).@Box(); case -1686842035: return ((global::Raft.Interfaces.IClusterManager)@grain).@RelayClientRequest((global::System.Int32)arguments[0], (global::System.Int32)arguments[1]).@Box(); case -1360605994: return ((global::Raft.Interfaces.IClusterManager)@grain).@RedirectClientRequest((global::System.Int32)arguments[0], (global::System.Int32)arguments[1]).@Box(); default: throw new global::System.NotImplementedException("interfaceId=" + 2139488188 + ",methodId=" + methodId); } default: throw new global::System.NotImplementedException("interfaceId=" + interfaceId); } } catch (global::System.Exception exception) { return global::Orleans.Async.TaskUtility.@Faulted(exception); } } public global::System.Int32 InterfaceId { get { return 2139488188; } } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.2.0.0"), global::System.SerializableAttribute, global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute, global::Orleans.CodeGeneration.GrainReferenceAttribute(typeof (global::Raft.Interfaces.IServer))] internal class OrleansCodeGenServerReference : global::Orleans.Runtime.GrainReference, global::Raft.Interfaces.IServer { protected @OrleansCodeGenServerReference(global::Orleans.Runtime.GrainReference @other): base (@other) { } protected @OrleansCodeGenServerReference(global::System.Runtime.Serialization.SerializationInfo @info, global::System.Runtime.Serialization.StreamingContext @context): base (@info, @context) { } protected override global::System.Int32 InterfaceId { get { return 2115164851; } } public override global::System.String InterfaceName { get { return "global::Raft.Interfaces.IServer"; } } public override global::System.Boolean @IsCompatible(global::System.Int32 @interfaceId) { return @interfaceId == 2115164851; } protected override global::System.String @GetMethodName(global::System.Int32 @interfaceId, global::System.Int32 @methodId) { switch (@interfaceId) { case 2115164851: switch (@methodId) { case 1472034337: return "Configure"; case -84135934: return "VoteRequest"; case -1645665559: return "VoteResponse"; case -1478130170: return "AppendEntriesRequest"; case 1694759622: return "AppendEntriesResponse"; case -1360605994: return "RedirectClientRequest"; case 127647396: return "ProcessClientRequest"; default: throw new global::System.NotImplementedException("interfaceId=" + 2115164851 + ",methodId=" + @methodId); } default: throw new global::System.NotImplementedException("interfaceId=" + @interfaceId); } } public global::System.Threading.Tasks.Task @Configure(global::System.Int32 @id, global::System.Collections.Generic.List<global::System.Int32> @serverIds, global::System.Int32 @clusterId) { return base.@InvokeMethodAsync<global::System.Object>(1472034337, new global::System.Object[]{@id, @serverIds, @clusterId}); } public global::System.Threading.Tasks.Task @VoteRequest(global::System.Int32 @term, global::System.Int32 @candidateId, global::System.Int32 @lastLogIndex, global::System.Int32 @lastLogTerm) { return base.@InvokeMethodAsync<global::System.Object>(-84135934, new global::System.Object[]{@term, @candidateId, @lastLogIndex, @lastLogTerm}); } public global::System.Threading.Tasks.Task @VoteResponse(global::System.Int32 @term, global::System.Boolean @voteGranted) { return base.@InvokeMethodAsync<global::System.Object>(-1645665559, new global::System.Object[]{@term, @voteGranted}); } public global::System.Threading.Tasks.Task @AppendEntriesRequest(global::System.Int32 @term, global::System.Int32 @leaderId, global::System.Int32 @prevLogIndex, global::System.Int32 @prevLogTerm, global::System.Collections.Generic.List<global::Raft.Interfaces.Log> @entries, global::System.Int32 @leaderCommit, global::System.Int32 @clientId) { return base.@InvokeMethodAsync<global::System.Object>(-1478130170, new global::System.Object[]{@term, @leaderId, @prevLogIndex, @prevLogTerm, @entries, @leaderCommit, @clientId}); } public global::System.Threading.Tasks.Task @AppendEntriesResponse(global::System.Int32 @term, global::System.Boolean @success, global::System.Int32 @serverId, global::System.Int32 @clientId) { return base.@InvokeMethodAsync<global::System.Object>(1694759622, new global::System.Object[]{@term, @success, @serverId, @clientId}); } public global::System.Threading.Tasks.Task @RedirectClientRequest(global::System.Int32 @clientId, global::System.Int32 @command) { return base.@InvokeMethodAsync<global::System.Object>(-1360605994, new global::System.Object[]{@clientId, @command}); } public global::System.Threading.Tasks.Task @ProcessClientRequest(global::System.Int32 @clientId, global::System.Int32 @command) { return base.@InvokeMethodAsync<global::System.Object>(127647396, new global::System.Object[]{@clientId, @command}); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.2.0.0"), global::Orleans.CodeGeneration.MethodInvokerAttribute("global::Raft.Interfaces.IServer", 2115164851, typeof (global::Raft.Interfaces.IServer)), global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] internal class OrleansCodeGenServerMethodInvoker : global::Orleans.CodeGeneration.IGrainMethodInvoker { public global::System.Threading.Tasks.Task<global::System.Object> @Invoke(global::Orleans.Runtime.IAddressable @grain, global::Orleans.CodeGeneration.InvokeMethodRequest @request) { global::System.Int32 interfaceId = @request.@InterfaceId; global::System.Int32 methodId = @request.@MethodId; global::System.Object[] arguments = @request.@Arguments; try { if (@grain == null) throw new global::System.ArgumentNullException("grain"); switch (interfaceId) { case 2115164851: switch (methodId) { case 1472034337: return ((global::Raft.Interfaces.IServer)@grain).@Configure((global::System.Int32)arguments[0], (global::System.Collections.Generic.List<global::System.Int32>)arguments[1], (global::System.Int32)arguments[2]).@Box(); case -84135934: return ((global::Raft.Interfaces.IServer)@grain).@VoteRequest((global::System.Int32)arguments[0], (global::System.Int32)arguments[1], (global::System.Int32)arguments[2], (global::System.Int32)arguments[3]).@Box(); case -1645665559: return ((global::Raft.Interfaces.IServer)@grain).@VoteResponse((global::System.Int32)arguments[0], (global::System.Boolean)arguments[1]).@Box(); case -1478130170: return ((global::Raft.Interfaces.IServer)@grain).@AppendEntriesRequest((global::System.Int32)arguments[0], (global::System.Int32)arguments[1], (global::System.Int32)arguments[2], (global::System.Int32)arguments[3], (global::System.Collections.Generic.List<global::Raft.Interfaces.Log>)arguments[4], (global::System.Int32)arguments[5], (global::System.Int32)arguments[6]).@Box(); case 1694759622: return ((global::Raft.Interfaces.IServer)@grain).@AppendEntriesResponse((global::System.Int32)arguments[0], (global::System.Boolean)arguments[1], (global::System.Int32)arguments[2], (global::System.Int32)arguments[3]).@Box(); case -1360605994: return ((global::Raft.Interfaces.IServer)@grain).@RedirectClientRequest((global::System.Int32)arguments[0], (global::System.Int32)arguments[1]).@Box(); case 127647396: return ((global::Raft.Interfaces.IServer)@grain).@ProcessClientRequest((global::System.Int32)arguments[0], (global::System.Int32)arguments[1]).@Box(); default: throw new global::System.NotImplementedException("interfaceId=" + 2115164851 + ",methodId=" + methodId); } default: throw new global::System.NotImplementedException("interfaceId=" + interfaceId); } } catch (global::System.Exception exception) { return global::Orleans.Async.TaskUtility.@Faulted(exception); } } public global::System.Int32 InterfaceId { get { return 2115164851; } } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.2.0.0"), global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute, global::Orleans.CodeGeneration.SerializerAttribute(typeof (global::Raft.Interfaces.Log)), global::Orleans.CodeGeneration.RegisterSerializerAttribute] internal class OrleansCodeGenRaft_Interfaces_LogSerializer { private static readonly global::System.Reflection.FieldInfo field1 = typeof (global::Raft.Interfaces.Log).@GetField("Command", (System.@Reflection.@BindingFlags.@Instance | System.@Reflection.@BindingFlags.@NonPublic | System.@Reflection.@BindingFlags.@Public)); private static readonly global::System.Func<global::Raft.Interfaces.Log, global::System.Int32> getField1 = (global::System.Func<global::Raft.Interfaces.Log, global::System.Int32>)global::Orleans.Serialization.SerializationManager.@GetGetter(field1); private static readonly global::System.Action<global::Raft.Interfaces.Log, global::System.Int32> setField1 = (global::System.Action<global::Raft.Interfaces.Log, global::System.Int32>)global::Orleans.Serialization.SerializationManager.@GetReferenceSetter(field1); private static readonly global::System.Reflection.FieldInfo field0 = typeof (global::Raft.Interfaces.Log).@GetField("Term", (System.@Reflection.@BindingFlags.@Instance | System.@Reflection.@BindingFlags.@NonPublic | System.@Reflection.@BindingFlags.@Public)); private static readonly global::System.Func<global::Raft.Interfaces.Log, global::System.Int32> getField0 = (global::System.Func<global::Raft.Interfaces.Log, global::System.Int32>)global::Orleans.Serialization.SerializationManager.@GetGetter(field0); private static readonly global::System.Action<global::Raft.Interfaces.Log, global::System.Int32> setField0 = (global::System.Action<global::Raft.Interfaces.Log, global::System.Int32>)global::Orleans.Serialization.SerializationManager.@GetReferenceSetter(field0); [global::Orleans.CodeGeneration.CopierMethodAttribute] public static global::System.Object DeepCopier(global::System.Object original) { global::Raft.Interfaces.Log input = ((global::Raft.Interfaces.Log)original); global::Raft.Interfaces.Log result = new global::Raft.Interfaces.Log(); setField1(result, getField1(input)); setField0(result, getField0(input)); global::Orleans.@Serialization.@SerializationContext.@Current.@RecordObject(original, result); return result; } [global::Orleans.CodeGeneration.SerializerMethodAttribute] public static void Serializer(global::System.Object untypedInput, global::Orleans.Serialization.BinaryTokenStreamWriter stream, global::System.Type expected) { global::Raft.Interfaces.Log input = (global::Raft.Interfaces.Log)untypedInput; global::Orleans.Serialization.SerializationManager.@SerializeInner(getField1(input), stream, typeof (global::System.Int32)); global::Orleans.Serialization.SerializationManager.@SerializeInner(getField0(input), stream, typeof (global::System.Int32)); } [global::Orleans.CodeGeneration.DeserializerMethodAttribute] public static global::System.Object Deserializer(global::System.Type expected, global::Orleans.Serialization.BinaryTokenStreamReader stream) { global::Raft.Interfaces.Log result = new global::Raft.Interfaces.Log(); global::Orleans.@Serialization.@DeserializationContext.@Current.@RecordObject(result); setField1(result, (global::System.Int32)global::Orleans.Serialization.SerializationManager.@DeserializeInner(typeof (global::System.Int32), stream)); setField0(result, (global::System.Int32)global::Orleans.Serialization.SerializationManager.@DeserializeInner(typeof (global::System.Int32), stream)); return (global::Raft.Interfaces.Log)result; } public static void Register() { global::Orleans.Serialization.SerializationManager.@Register(typeof (global::Raft.Interfaces.Log), DeepCopier, Serializer, Deserializer); } static OrleansCodeGenRaft_Interfaces_LogSerializer() { Register(); } } } #pragma warning restore 162 #pragma warning restore 219 #pragma warning restore 414 #pragma warning restore 649 #pragma warning restore 693 #pragma warning restore 1591 #pragma warning restore 1998 #endif
/* Copyright 2014 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using DriveProxy.Utils; namespace DriveProxy.Service { internal class ServicePipeServer : IDisposable { public enum ExecuteResult { Ok, Exception, DisconnectClient, DisconnectServer } protected bool _Enabled = false; protected Exception _LastException = null; private Pipe.Server _pipe; protected int _ProcessCount = 0; public bool Enabled { get { return _Enabled; } set { _Enabled = value; } } public bool Processing { get { if (ProcessCount > 0) { return true; } return false; } } public int ProcessCount { get { return _ProcessCount; } } public Exception LastException { get { return _LastException; } set { _LastException = value; Log.Error(_LastException, false); } } public string LastExceptionMessage { get { if (HasException) { return LastException.Message; } return ""; } } public bool HasException { get { if (LastException != null) { return true; } return false; } } public void Dispose() { try { if (_pipe == null) { return; } _pipe.Dispose(); _pipe = null; } catch (Exception exception) { LastException = exception; } } public bool Process() { try { return Process(ServicePipe.PipeName, true); } catch (Exception exception) { LastException = exception; return false; } } protected bool Process(string pipeName, bool waitForDisconnectMessage) { try { _ProcessCount++; try { _Enabled = true; DateTime started = DateTime.Now; while (Enabled) { if (IsCreated() || Create(pipeName)) { if (Connect()) { ServicePipeServer.ExecuteResult executeResult = Execute(); if (!waitForDisconnectMessage) { break; } if (executeResult == ServicePipeServer.ExecuteResult.DisconnectServer) { break; } } else { Log.Warning("Could not connect to pipe " + pipeName); System.Threading.Thread.Sleep(10); } } else { Log.Warning("Could not create pipe " + pipeName); System.Threading.Thread.Sleep(10); } if (!waitForDisconnectMessage) { TimeSpan timeSpan = DateTime.Now.Subtract(started); if (timeSpan.TotalSeconds >= 15) { Log.Error("Closing pipe " + _pipe.Name + " (client did not connect)"); break; } } } Close(); } finally { _ProcessCount--; } return true; } catch (Exception exception) { LastException = exception; return false; } } protected void Process_Thread(object args) { try { var pipeName = (string)args; var server = new ServicePipeServer(); server.Process(pipeName, false); } catch (Exception exception) { LastException = exception; } } public bool IsCreated() { try { if (_pipe == null) { return false; } return _pipe.IsCreated; } catch (Exception exception) { LastException = exception; return false; } } protected bool Create(string pipeName) { try { Close(); Log.Information("Attempting to create pipe '" + pipeName + "'"); _pipe = Pipe.Server.Create(pipeName, System.IO.FileAccess.ReadWrite); Log.Information("Successfully created pipe '" + pipeName + "'"); return true; } catch (Exception exception) { LastException = exception; return false; } } public bool IsConnected() { try { if (_pipe == null) { return false; } return _pipe.IsConnected; } catch (Exception exception) { LastException = exception; return false; } } protected bool Connect() { try { if (_pipe == null) { throw new Exception("Pipe has not been created."); } if (!_pipe.Connect()) { return false; } return true; } catch (Exception exception) { LastException = exception; return false; } } public void Disconnect() { try { if (_pipe == null) { return; } _pipe.Disconnect(); } catch (Exception exception) { LastException = exception; } } public void Close() { try { if (_pipe == null) { return; } _pipe.Close(); } catch (Exception exception) { LastException = exception; } } protected ExecuteResult Execute() { try { if (_pipe == null) { throw new Exception("Pipe has not been created."); } Log.Debug("Attempting to handle Service.Execute"); string result = null; var executeResult = ExecuteResult.Ok; string message = Read(); if (message == "ping") { Log.Information("Received 'ping' message"); result = "hello"; } else if (message == "redirect") { Log.Information("Received 'redirect' message"); Guid guid = Guid.NewGuid(); result = guid.ToString().Replace("-", ""); string pipeName = "DriveProxy.Service_" + result; Log.Information("Redirecting to new pipe " + pipeName); new System.Threading.Thread(Process_Thread).Start(pipeName); } else if (message == "process count") { Log.Information("Received 'process count' message"); result = _ProcessCount.ToString(); } else if (message == "close") { Log.Information("Received 'close' message"); executeResult = ExecuteResult.DisconnectClient; } else if (message == "disconnect") { Log.Information("Received 'disconnect' message"); result = "disconnecting"; executeResult = ExecuteResult.DisconnectServer; } else { Log.Debug("Received 'execute' message"); string[] args = message.Split(','); result = Service.Execute(args); } if (result != null) { Write(result); } Log.Debug("Successfully handled Service.Execute"); return executeResult; } catch (Exception exception) { LastException = exception; return ExecuteResult.Exception; } finally { Disconnect(); } } protected string Read() { try { Log.Debug("Attempting to read message from ServicePipe process"); string result = ServicePipe.Read(_pipe); Log.Debug(String.Format("Successfully read message: \"{0}\" from ServicePipe process", result)); return result; } catch (Exception exception) { Log.Error(exception); return null; } } protected void Write(string message) { try { if (message.Length > 100) { Log.Information(String.Format("Sending: \"{0}\" to ServicePipe process", message.Substring(0, 100) + "...TRUNCATED")); } else { Log.Information(String.Format("Sending: \"{0}\" to ServicePipe process", message)); } ServicePipe.Write(_pipe, message); Log.Debug("Successfully wrote message to ServicePipe process"); } catch (Exception exception) { Log.Error(exception); } } } }
/* * REST API Documentation for the MOTI School Bus Application * * The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus. * * OpenAPI spec version: v1 * * */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using SchoolBusAPI.Models; namespace SchoolBusAPI.Models { /// <summary> /// The users associated with a given group that has been defined in the application. /// </summary> [MetaDataExtension (Description = "The users associated with a given group that has been defined in the application.")] public partial class GroupMembership : AuditableEntity, IEquatable<GroupMembership> { /// <summary> /// Default constructor, required by entity framework /// </summary> public GroupMembership() { this.Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="GroupMembership" /> class. /// </summary> /// <param name="Id">A system-generated unique identifier for a GroupMembership (required).</param> /// <param name="Active">A flag indicating the User is active in the group. Set false to remove the user from the designated group. (required).</param> /// <param name="Group">A foreign key reference to the system-generated unique identifier for a Group.</param> /// <param name="User">A foreign key reference to the system-generated unique identifier for a User.</param> public GroupMembership(int Id, bool Active, Group Group = null, User User = null) { this.Id = Id; this.Active = Active; this.Group = Group; this.User = User; } /// <summary> /// A system-generated unique identifier for a GroupMembership /// </summary> /// <value>A system-generated unique identifier for a GroupMembership</value> [MetaDataExtension (Description = "A system-generated unique identifier for a GroupMembership")] public int Id { get; set; } /// <summary> /// A flag indicating the User is active in the group. Set false to remove the user from the designated group. /// </summary> /// <value>A flag indicating the User is active in the group. Set false to remove the user from the designated group.</value> [MetaDataExtension (Description = "A flag indicating the User is active in the group. Set false to remove the user from the designated group.")] public bool Active { get; set; } /// <summary> /// A foreign key reference to the system-generated unique identifier for a Group /// </summary> /// <value>A foreign key reference to the system-generated unique identifier for a Group</value> [MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a Group")] public Group Group { get; set; } /// <summary> /// Foreign key for Group /// </summary> [ForeignKey("Group")] [JsonIgnore] [MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a Group")] public int? GroupId { get; set; } /// <summary> /// A foreign key reference to the system-generated unique identifier for a User /// </summary> /// <value>A foreign key reference to the system-generated unique identifier for a User</value> [MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a User")] public User User { get; set; } /// <summary> /// Foreign key for User /// </summary> [ForeignKey("User")] [JsonIgnore] [MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a User")] public int? 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 GroupMembership {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Active: ").Append(Active).Append("\n"); sb.Append(" Group: ").Append(Group).Append("\n"); sb.Append(" User: ").Append(User).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) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((GroupMembership)obj); } /// <summary> /// Returns true if GroupMembership instances are equal /// </summary> /// <param name="other">Instance of GroupMembership to be compared</param> /// <returns>Boolean</returns> public bool Equals(GroupMembership other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( this.Id == other.Id || this.Id.Equals(other.Id) ) && ( this.Active == other.Active || this.Active.Equals(other.Active) ) && ( this.Group == other.Group || this.Group != null && this.Group.Equals(other.Group) ) && ( this.User == other.User || this.User != null && this.User.Equals(other.User) ); } /// <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 hash = hash * 59 + this.Id.GetHashCode(); hash = hash * 59 + this.Active.GetHashCode(); if (this.Group != null) { hash = hash * 59 + this.Group.GetHashCode(); } if (this.User != null) { hash = hash * 59 + this.User.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(GroupMembership left, GroupMembership right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(GroupMembership left, GroupMembership right) { return !Equals(left, right); } #endregion Operators } }
// 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.Text; using System; using System.Diagnostics; using System.Diagnostics.Contracts; 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 { return _fallback; } set { if (value == null) throw new ArgumentNullException(nameof(value)); Contract.EndContractBlock(); // 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 { get { return _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 = { }; 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); Contract.EndContractBlock(); 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 = &chars.DangerousGetPinnableReference()) { 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); Contract.EndContractBlock(); // 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 = &chars.DangerousGetPinnableReference()) fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference()) { 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); Contract.EndContractBlock(); 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); Contract.EndContractBlock(); // 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 = &chars.DangerousGetPinnableReference()) fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference()) { Convert(charsPtr, chars.Length, bytesPtr, bytes.Length, flush, out charsUsed, out bytesUsed, out completed); } } } }
// 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 Internal.Cryptography; namespace System.Security.Cryptography { /// <summary> /// Key derivation functions used to transform the raw secret agreement into key material /// </summary> public enum ECDiffieHellmanKeyDerivationFunction { Hash, Hmac, Tls } /// <summary> /// Wrapper for CNG's implementation of elliptic curve Diffie-Hellman key exchange /// </summary> public sealed partial class ECDiffieHellmanCng : ECDiffieHellman { private CngAlgorithmCore _core = new CngAlgorithmCore { DefaultKeyType = CngAlgorithm.ECDiffieHellman }; private CngAlgorithm _hashAlgorithm = CngAlgorithm.Sha256; private ECDiffieHellmanKeyDerivationFunction _kdf = ECDiffieHellmanKeyDerivationFunction.Hash; private byte[] _hmacKey; private byte[] _label; private byte[] _secretAppend; private byte[] _secretPrepend; private byte[] _seed; public ECDiffieHellmanCng(CngKey key) { if (key == null) throw new ArgumentNullException(nameof(key)); if (key.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman) throw new ArgumentException(SR.Cryptography_ArgECDHRequiresECDHKey, nameof(key)); Key = CngAlgorithmCore.Duplicate(key); } /// <summary> /// Hash algorithm used with the Hash and HMAC KDFs /// </summary> public CngAlgorithm HashAlgorithm { get { return _hashAlgorithm; } set { if (_hashAlgorithm == null) { throw new ArgumentNullException(nameof(value)); } _hashAlgorithm = value; } } /// <summary> /// KDF used to transform the secret agreement into key material /// </summary> public ECDiffieHellmanKeyDerivationFunction KeyDerivationFunction { get { return _kdf; } set { if (value < ECDiffieHellmanKeyDerivationFunction.Hash || value > ECDiffieHellmanKeyDerivationFunction.Tls) { throw new ArgumentOutOfRangeException(nameof(value)); } _kdf = value; } } /// <summary> /// Key used with the HMAC KDF /// </summary> public byte[] HmacKey { get { return _hmacKey; } set { _hmacKey = value; } } /// <summary> /// Label bytes used for the TLS KDF /// </summary> public byte[] Label { get { return _label; } set { _label = value; } } /// <summary> /// Bytes to append to the raw secret agreement before processing by the KDF /// </summary> public byte[] SecretAppend { get { return _secretAppend; } set { _secretAppend = value; } } /// <summary> /// Bytes to prepend to the raw secret agreement before processing by the KDF /// </summary> public byte[] SecretPrepend { get { return _secretPrepend; } set { _secretPrepend = value; } } /// <summary> /// Seed bytes used for the TLS KDF /// </summary> public byte[] Seed { get { return _seed; } set { _seed = value; } } /// <summary> /// Use the secret agreement as the HMAC key rather than supplying a seperate one /// </summary> public bool UseSecretAgreementAsHmacKey { get { return HmacKey == null; } } protected override void Dispose(bool disposing) { _core.Dispose(); } private void DisposeKey() { _core.DisposeKey(); } internal string GetCurveName(out string oidValue) { return Key.GetCurveName(out oidValue); } private void ImportFullKeyBlob(byte[] ecfullKeyBlob, bool includePrivateParameters) { Key = ECCng.ImportFullKeyBlob(ecfullKeyBlob, includePrivateParameters); } private void ImportKeyBlob(byte[] ecfullKeyBlob, string curveName, bool includePrivateParameters) { Key = ECCng.ImportKeyBlob(ecfullKeyBlob, curveName, includePrivateParameters); } private byte[] ExportKeyBlob(bool includePrivateParameters) { return ECCng.ExportKeyBlob(Key, includePrivateParameters); } private byte[] ExportFullKeyBlob(bool includePrivateParameters) { return ECCng.ExportFullKeyBlob(Key, includePrivateParameters); } private void AcceptImport(CngPkcs8.Pkcs8Response response) { Key = response.Key; } public override bool TryExportPkcs8PrivateKey(Span<byte> destination, out int bytesWritten) { return Key.TryExportKeyBlob( Interop.NCrypt.NCRYPT_PKCS8_PRIVATE_KEY_BLOB, destination, out bytesWritten); } private byte[] ExportEncryptedPkcs8(ReadOnlySpan<char> pkcs8Password, int kdfCount) { return Key.ExportPkcs8KeyBlob(pkcs8Password, kdfCount); } private bool TryExportEncryptedPkcs8( ReadOnlySpan<char> pkcs8Password, int kdfCount, Span<byte> destination, out int bytesWritten) { return Key.TryExportPkcs8KeyBlob( pkcs8Password, kdfCount, destination, out bytesWritten); } } }
//================================================================================================= // Copyright 2017 Dirk Lemstra <https://graphicsmagick.codeplex.com/> // // Licensed under the ImageMagick License (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.imagemagick.org/script/license.php // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language governing permissions and // limitations under the License. //================================================================================================= using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Reflection; using System.Text; using System.Windows.Media.Imaging; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using Fasterflect; namespace GraphicsMagick { public sealed class MagickColor: IEquatable<MagickColor>, IComparable<MagickColor> { internal object _Instance; internal MagickColor(object instance) { _Instance = instance; } public static object GetInstance(MagickColor obj) { if (ReferenceEquals(obj, null)) return null; return obj._Instance; } public static object GetInstance(object obj) { if (ReferenceEquals(obj, null)) return null; MagickColor casted = obj as MagickColor; if (ReferenceEquals(casted, null)) return obj; return casted._Instance; } public MagickColor(String color) : this(AssemblyHelper.CreateInstance(Types.MagickColor, new Type[] {typeof(String)}, color)) { } [CLSCompliant(false)] public MagickColor(UInt16 red, UInt16 green, UInt16 blue, UInt16 alpha) : this(AssemblyHelper.CreateInstance(Types.MagickColor, new Type[] {typeof(UInt16), typeof(UInt16), typeof(UInt16), typeof(UInt16)}, red, green, blue, alpha)) { } [CLSCompliant(false)] public MagickColor(UInt16 red, UInt16 green, UInt16 blue) : this(AssemblyHelper.CreateInstance(Types.MagickColor, new Type[] {typeof(UInt16), typeof(UInt16), typeof(UInt16)}, red, green, blue)) { } public MagickColor(Color color) : this(AssemblyHelper.CreateInstance(Types.MagickColor, new Type[] {typeof(Color)}, color)) { } public MagickColor() : this(AssemblyHelper.CreateInstance(Types.MagickColor)) { } public static bool operator ==(MagickColor left, MagickColor right) { if (ReferenceEquals(left, null)) return ReferenceEquals(right, null); return Object.Equals(left, right); } public static bool operator >(MagickColor left, MagickColor right) { if (ReferenceEquals(left, null)) return ReferenceEquals(right, null); return left.CompareTo(right) == 1; } public static bool operator >=(MagickColor left, MagickColor right) { if (ReferenceEquals(left, null)) return ReferenceEquals(right, null); return left.CompareTo(right) >= 0; } public static implicit operator Color(MagickColor color) { object result = Types.MagickColor.CallMethod("op_Implicit", new Type[] {Types.MagickColor}, GraphicsMagick.MagickColor.GetInstance(color)); return (Color)result; } public static implicit operator MagickColor(Color color) { object result = Types.MagickColor.CallMethod("op_Implicit", new Type[] {typeof(Color)}, color); return (result == null ? null : new MagickColor(result)); } public static bool operator !=(MagickColor left, MagickColor right) { if (ReferenceEquals(left, null)) return !ReferenceEquals(right, null); return !Object.Equals(left, right); } public static bool operator <(MagickColor left, MagickColor right) { if (ReferenceEquals(left, null)) return !ReferenceEquals(right, null); return left.CompareTo(right) == -1; } public static bool operator <=(MagickColor left, MagickColor right) { if (ReferenceEquals(left, null)) return !ReferenceEquals(right, null); return left.CompareTo(right) <= 0; } [CLSCompliant(false)] public UInt16 A { get { object result; try { result = _Instance.GetPropertyValue("A"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (UInt16)result; } set { try { _Instance.SetPropertyValue("A", value); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } } } [CLSCompliant(false)] public UInt16 B { get { object result; try { result = _Instance.GetPropertyValue("B"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (UInt16)result; } set { try { _Instance.SetPropertyValue("B", value); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } } } [CLSCompliant(false)] public UInt16 G { get { object result; try { result = _Instance.GetPropertyValue("G"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (UInt16)result; } set { try { _Instance.SetPropertyValue("G", value); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } } } [CLSCompliant(false)] public UInt16 R { get { object result; try { result = _Instance.GetPropertyValue("R"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (UInt16)result; } set { try { _Instance.SetPropertyValue("R", value); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } } } public static MagickColor Transparent { get { object result; try { result = Types.MagickColor.GetPropertyValue("Transparent"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (result == null ? null : new MagickColor(result)); } } public Int32 CompareTo(MagickColor other) { object result; try { result = _Instance.CallMethod("CompareTo", new Type[] {Types.MagickColor}, GraphicsMagick.MagickColor.GetInstance(other)); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (Int32)result; } public Boolean Equals(MagickColor other) { object result; try { result = _Instance.CallMethod("Equals", new Type[] {Types.MagickColor}, GraphicsMagick.MagickColor.GetInstance(other)); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (Boolean)result; } public override Boolean Equals(Object obj) { object result; try { result = _Instance.CallMethod("Equals", new Type[] {typeof(Object)}, GraphicsMagick.MagickColor.GetInstance(obj)); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (Boolean)result; } public override Int32 GetHashCode() { object result; try { result = _Instance.CallMethod("GetHashCode"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (Int32)result; } public Color ToColor() { object result; try { result = _Instance.CallMethod("ToColor"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (Color)result; } public override String ToString() { object result; try { result = _Instance.CallMethod("ToString"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (String)result; } } }
using System; using System.Runtime.Serialization; using System.Threading.Tasks; namespace GenFx { /// <summary> /// Provides the abstract base class for genetic entities in a genetic algorithm. /// </summary> /// <remarks> /// A genetic entity in a genetic algorithm represents the "organism" which undergoes evolution. All the genetic /// operators such as the <see cref="SelectionOperator"/>, <see cref="CrossoverOperator"/>, and /// <see cref="MutationOperator"/> act upon genetic entities to bring about change in the system. /// </remarks> [DataContract] public abstract class GeneticEntity : GeneticComponentWithAlgorithm, IComparable<GeneticEntity>, IComparable, IEquatable<GeneticEntity> { [DataMember] private double rawFitnessValue; [DataMember] private double scaledFitnessValue; /// <summary> /// When overriden in a derived class, gets the string representation of the entity. /// </summary> /// <value>The string representation of the entity.</value> public abstract string Representation { get; } /// <summary> /// Gets or sets the number of generations this entity has survived without being altered. /// </summary> /// <value>The number of generations this entity has survived without being altered.</value> [DataMember] public int Age { get; set; } /// <summary> /// Gets the fitness value of the entity before being scaled by the <see cref="FitnessScalingStrategy"/>. /// </summary> /// <value>The fitness value of the entity before being scaled by the <see cref="FitnessScalingStrategy"/>.</value> /// <remarks> /// The fitness value is a relative measurement of how close a entity is to meeting the goal /// of the genetic algorithm. /// </remarks> /// <seealso cref="FitnessEvaluator"/> public double RawFitnessValue { get { return this.rawFitnessValue; } } /// <summary> /// Gets or sets the fitness value of the entity after it has been scaled by the <see cref="FitnessScalingStrategy"/>. /// </summary> /// <value>The fitness value of the entity after it has been scaled by the <see cref="FitnessScalingStrategy"/>.</value> /// <remarks> /// <para> /// The fitness value is a relative measurement of how close a entity is to meeting the goal /// of the genetic algorithm. /// </para> /// <para> /// This value is equal to <see cref="RawFitnessValue"/> if a /// <see cref="FitnessScalingStrategy"/> is not being used. /// </para> /// </remarks> /// <seealso cref="FitnessEvaluator"/> /// <seealso cref="FitnessScalingStrategy"/> public double ScaledFitnessValue { get { return this.scaledFitnessValue; } set { this.scaledFitnessValue = value; } } /// <summary> /// Evaluates the <see cref="RawFitnessValue"/> of the entity. /// </summary> public async Task EvaluateFitnessAsync() { if (this.Algorithm?.FitnessEvaluator != null) { this.rawFitnessValue = this.scaledFitnessValue = await this.Algorithm.FitnessEvaluator.EvaluateFitnessAsync(this); } } /// <summary> /// Returns the appropriate fitness value of the <b>GeneticEntity</b> based on the the <paramref name="fitnessType"/>. /// </summary> /// <param name="fitnessType"><see cref="FitnessType"/> indicating which fitness value to /// return.</param> /// <returns>The appropriate fitness value of the <b>GeneticEntity</b>.</returns> /// <exception cref="ArgumentException"><paramref name="fitnessType"/> value is undefined.</exception> public double GetFitnessValue(FitnessType fitnessType) { if (!Enum.IsDefined(typeof(FitnessType), fitnessType)) { throw EnumHelper.CreateUndefinedEnumException(typeof(FitnessType), "fitnessType"); } if (fitnessType == FitnessType.Raw) { return this.rawFitnessValue; } else { return this.scaledFitnessValue; } } /// <summary> /// Initializes the component to ensure its readiness for algorithm execution. /// </summary> /// <param name="algorithm">The algorithm that is to use this component.</param> public override void Initialize(GeneticAlgorithm algorithm) { base.Initialize(algorithm); this.rawFitnessValue = 0; this.scaledFitnessValue = 0; this.Age = 0; } /// <summary> /// Returns the string representation of the entity. /// </summary> /// <returns>The string representation of the entity.</returns> public override string ToString() { return this.Representation; } /// <summary> /// Returns a clone of this entity. /// </summary> /// <returns>A clone of this entity.</returns> public GeneticEntity Clone() { GeneticEntity clone = (GeneticEntity)this.CreateNew(); clone.Algorithm = this.Algorithm; this.CopyTo(clone); clone.IsInitialized = true; return clone; } /// <summary> /// Copies the state from this instance to <paramref name="entity"/>. /// </summary> /// <param name="entity"><see cref="GeneticEntity"/> to which state is to be copied.</param> /// <remarks> /// <para> /// The default implementation of this method is to copy the state of this instance /// to the entity passed in. /// </para> /// <para> /// <b>Notes to inheritors:</b> When overriding this method, it is necessary to call the /// <b>CopyTo</b> method of the base class. It is not necessary to copy the state of properties that /// are adorned with the <see cref="ConfigurationPropertyAttribute"/>; these properties have their state /// automatically copied as part of the base implementation of this method. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="entity"/> is null.</exception> public virtual void CopyTo(GeneticEntity entity) { if (entity is null) { throw new ArgumentNullException(nameof(entity)); } this.CopyConfigurationStateTo(entity); entity.Age = this.Age; entity.rawFitnessValue = this.rawFitnessValue; entity.scaledFitnessValue = this.scaledFitnessValue; } /// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A value that indicates the relative order of the objects being compared. The /// return value has the following meanings: /// * Less than zero: This object is less than <paramref name="other"/>. /// * Zero: This object is equal to <paramref name="other"/>. /// * Greater than zero: This object is greater than <paramref name="other"/>. /// </returns> public abstract int CompareTo(GeneticEntity other); /// <summary> /// Compares the current object with another object. /// </summary> /// <param name="obj">An object to compare with this object.</param> /// <returns> /// A value that indicates the relative order of the objects being compared. The /// return value has the following meanings: /// * Less than zero: This object is less than <paramref name="obj"/>. /// * Zero: This object is equal to <paramref name="obj"/> /// * Greater than zero: This object is greater than <paramref name="obj"/>. /// </returns> public int CompareTo(object obj) { if (obj == null) { return 1; } if (!(obj is GeneticEntity entity)) { throw new ArgumentException(StringUtil.GetFormattedString( Resources.ErrorMsg_ObjectIsWrongType, typeof(GeneticEntity)), nameof(obj)); } return this.CompareTo(entity); } /// <summary> /// Indicates whether the current object is equal to another object. /// </summary> /// <param name="obj">An object to compare with this object.</param> /// <returns>true if the current object is equal to <paramref name="obj"/>; otherwise, false.</returns> public override bool Equals(object obj) { if (obj == null) { return false; } if (!(obj is GeneticEntity entity)) { return false; } return this.Equals(entity); } /// <summary> /// Serves as the default hash function. /// </summary> /// <returns>A hash code for the current object.</returns> public override int GetHashCode() { return base.GetHashCode(); } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns>true if the current object is equal to <paramref name="other"/>; otherwise, false.</returns> public bool Equals(GeneticEntity other) { return this.CompareTo(other) == 0; } /// <summary> /// Compares two <see cref="GeneticEntity"/> objects for equality. /// </summary> /// <param name="obj1">The first <see cref="GeneticEntity"/> object to compare.</param> /// <param name="obj2">The second <see cref="GeneticEntity"/> object to compare.</param> /// <returns>true if the two <see cref="GeneticEntity"/> objects are equal; otherwise, false.</returns> public static bool operator ==(GeneticEntity obj1, GeneticEntity obj2) { return ComparisonHelper.CompareObjects(obj1, obj2) == 0; } /// <summary> /// Compares two <see cref="GeneticEntity"/> objects for inequality. /// </summary> /// <param name="obj1">The first <see cref="GeneticEntity"/> object to compare.</param> /// <param name="obj2">The second <see cref="GeneticEntity"/> object to compare.</param> /// <returns>true if the two <see cref="GeneticEntity"/> objects are not equal; otherwise, false.</returns> public static bool operator !=(GeneticEntity obj1, GeneticEntity obj2) { return ComparisonHelper.CompareObjects(obj1, obj2) != 0; } /// <summary> /// Compares two <see cref="GeneticEntity"/> objects to determine if <paramref name="obj1"/> is less than <paramref name="obj2"/>. /// </summary> /// <param name="obj1">The first <see cref="GeneticEntity"/> object to compare.</param> /// <param name="obj2">The second <see cref="GeneticEntity"/> object to compare.</param> /// <returns>true if <paramref name="obj1"/> is less than <paramref name="obj2"/>; otherwise, false.</returns> public static bool operator <(GeneticEntity obj1, GeneticEntity obj2) { return ComparisonHelper.CompareObjects(obj1, obj2) < 0; } /// <summary> /// Compares two <see cref="GeneticEntity"/> objects to determine if <paramref name="obj1"/> is greater than <paramref name="obj2"/>. /// </summary> /// <param name="obj1">The first <see cref="GeneticEntity"/> object to compare.</param> /// <param name="obj2">The second <see cref="GeneticEntity"/> object to compare.</param> /// <returns>true if <paramref name="obj1"/> is greater than <paramref name="obj2"/>; otherwise, false.</returns> public static bool operator >(GeneticEntity obj1, GeneticEntity obj2) { return ComparisonHelper.CompareObjects(obj1, obj2) > 0; } public static bool operator <=(GeneticEntity left, GeneticEntity right) { return left is null || left.CompareTo(right) <= 0; } public static bool operator >=(GeneticEntity left, GeneticEntity right) { return left is null ? right is null : left.CompareTo(right) >= 0; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Dialogflow.V2.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedEnvironmentsClientTest { [xunit::FactAttribute] public void GetEnvironmentRequestObject() { moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict); GetEnvironmentRequest request = new GetEnvironmentRequest { EnvironmentName = EnvironmentName.FromProjectEnvironment("[PROJECT]", "[ENVIRONMENT]"), }; Environment expectedResponse = new Environment { EnvironmentName = EnvironmentName.FromProjectEnvironment("[PROJECT]", "[ENVIRONMENT]"), Description = "description2cf9da67", AgentVersionAsVersionName = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"), State = Environment.Types.State.Loading, UpdateTime = new wkt::Timestamp(), TextToSpeechSettings = new TextToSpeechSettings(), Fulfillment = new Fulfillment(), }; mockGrpcClient.Setup(x => x.GetEnvironment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null); Environment response = client.GetEnvironment(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetEnvironmentRequestObjectAsync() { moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict); GetEnvironmentRequest request = new GetEnvironmentRequest { EnvironmentName = EnvironmentName.FromProjectEnvironment("[PROJECT]", "[ENVIRONMENT]"), }; Environment expectedResponse = new Environment { EnvironmentName = EnvironmentName.FromProjectEnvironment("[PROJECT]", "[ENVIRONMENT]"), Description = "description2cf9da67", AgentVersionAsVersionName = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"), State = Environment.Types.State.Loading, UpdateTime = new wkt::Timestamp(), TextToSpeechSettings = new TextToSpeechSettings(), Fulfillment = new Fulfillment(), }; mockGrpcClient.Setup(x => x.GetEnvironmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Environment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null); Environment responseCallSettings = await client.GetEnvironmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Environment responseCancellationToken = await client.GetEnvironmentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateEnvironmentRequestObject() { moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict); CreateEnvironmentRequest request = new CreateEnvironmentRequest { ParentAsAgentName = AgentName.FromProject("[PROJECT]"), Environment = new Environment(), EnvironmentId = "environment_id26e3069e", }; Environment expectedResponse = new Environment { EnvironmentName = EnvironmentName.FromProjectEnvironment("[PROJECT]", "[ENVIRONMENT]"), Description = "description2cf9da67", AgentVersionAsVersionName = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"), State = Environment.Types.State.Loading, UpdateTime = new wkt::Timestamp(), TextToSpeechSettings = new TextToSpeechSettings(), Fulfillment = new Fulfillment(), }; mockGrpcClient.Setup(x => x.CreateEnvironment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null); Environment response = client.CreateEnvironment(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateEnvironmentRequestObjectAsync() { moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict); CreateEnvironmentRequest request = new CreateEnvironmentRequest { ParentAsAgentName = AgentName.FromProject("[PROJECT]"), Environment = new Environment(), EnvironmentId = "environment_id26e3069e", }; Environment expectedResponse = new Environment { EnvironmentName = EnvironmentName.FromProjectEnvironment("[PROJECT]", "[ENVIRONMENT]"), Description = "description2cf9da67", AgentVersionAsVersionName = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"), State = Environment.Types.State.Loading, UpdateTime = new wkt::Timestamp(), TextToSpeechSettings = new TextToSpeechSettings(), Fulfillment = new Fulfillment(), }; mockGrpcClient.Setup(x => x.CreateEnvironmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Environment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null); Environment responseCallSettings = await client.CreateEnvironmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Environment responseCancellationToken = await client.CreateEnvironmentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateEnvironmentRequestObject() { moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict); UpdateEnvironmentRequest request = new UpdateEnvironmentRequest { Environment = new Environment(), UpdateMask = new wkt::FieldMask(), AllowLoadToDraftAndDiscardChanges = true, }; Environment expectedResponse = new Environment { EnvironmentName = EnvironmentName.FromProjectEnvironment("[PROJECT]", "[ENVIRONMENT]"), Description = "description2cf9da67", AgentVersionAsVersionName = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"), State = Environment.Types.State.Loading, UpdateTime = new wkt::Timestamp(), TextToSpeechSettings = new TextToSpeechSettings(), Fulfillment = new Fulfillment(), }; mockGrpcClient.Setup(x => x.UpdateEnvironment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null); Environment response = client.UpdateEnvironment(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateEnvironmentRequestObjectAsync() { moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict); UpdateEnvironmentRequest request = new UpdateEnvironmentRequest { Environment = new Environment(), UpdateMask = new wkt::FieldMask(), AllowLoadToDraftAndDiscardChanges = true, }; Environment expectedResponse = new Environment { EnvironmentName = EnvironmentName.FromProjectEnvironment("[PROJECT]", "[ENVIRONMENT]"), Description = "description2cf9da67", AgentVersionAsVersionName = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"), State = Environment.Types.State.Loading, UpdateTime = new wkt::Timestamp(), TextToSpeechSettings = new TextToSpeechSettings(), Fulfillment = new Fulfillment(), }; mockGrpcClient.Setup(x => x.UpdateEnvironmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Environment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null); Environment responseCallSettings = await client.UpdateEnvironmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Environment responseCancellationToken = await client.UpdateEnvironmentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteEnvironmentRequestObject() { moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict); DeleteEnvironmentRequest request = new DeleteEnvironmentRequest { EnvironmentName = EnvironmentName.FromProjectEnvironment("[PROJECT]", "[ENVIRONMENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteEnvironment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null); client.DeleteEnvironment(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteEnvironmentRequestObjectAsync() { moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict); DeleteEnvironmentRequest request = new DeleteEnvironmentRequest { EnvironmentName = EnvironmentName.FromProjectEnvironment("[PROJECT]", "[ENVIRONMENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteEnvironmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null); await client.DeleteEnvironmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteEnvironmentAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
using IdSharp.Tagging.Harness.WinForms.UserControls; namespace IdSharp.Tagging.Harness.WinForms { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.btnClose = new System.Windows.Forms.Button(); this.lblVersion = new System.Windows.Forms.Label(); this.tabMain = new System.Windows.Forms.TabControl(); this.tpFile = new System.Windows.Forms.TabPage(); this.tabFile = new System.Windows.Forms.TabControl(); this.tpID3v2 = new System.Windows.Forms.TabPage(); this.ucID3v2 = new ID3v2UserControl(); this.tpID3v1 = new System.Windows.Forms.TabPage(); this.ucID3v1 = new ID3v1UserControl(); this.pnlButtons = new System.Windows.Forms.Panel(); this.btnRemoveID3v1 = new System.Windows.Forms.Button(); this.btnRemoveID3v2 = new System.Windows.Forms.Button(); this.btnSave = new System.Windows.Forms.Button(); this.btnLoad = new System.Windows.Forms.Button(); this.tpScan = new System.Windows.Forms.TabPage(); this.btnScan = new System.Windows.Forms.Button(); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.colArtist = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colTitle = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colAlbum = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colGenre = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colYear = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colFilename = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.btnChooseDirectory = new System.Windows.Forms.Button(); this.txtDirectory = new System.Windows.Forms.TextBox(); this.lblDirectory = new System.Windows.Forms.Label(); this.prgScanFiles = new System.Windows.Forms.ProgressBar(); this.folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog(); this.audioOpenFileDialog = new System.Windows.Forms.OpenFileDialog(); this.tabMain.SuspendLayout(); this.tpFile.SuspendLayout(); this.tabFile.SuspendLayout(); this.tpID3v2.SuspendLayout(); this.tpID3v1.SuspendLayout(); this.pnlButtons.SuspendLayout(); this.tpScan.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout(); // // btnClose // this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnClose.Location = new System.Drawing.Point(689, 486); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(94, 23); this.btnClose.TabIndex = 90; this.btnClose.Text = "&Close"; this.btnClose.UseVisualStyleBackColor = true; this.btnClose.Click += new System.EventHandler(this.btnClose_Click); // // lblVersion // this.lblVersion.AutoSize = true; this.lblVersion.Location = new System.Drawing.Point(9, 9); this.lblVersion.Name = "lblVersion"; this.lblVersion.Size = new System.Drawing.Size(48, 13); this.lblVersion.TabIndex = 24; this.lblVersion.Text = "[Version]"; // // tabMain // this.tabMain.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tabMain.Controls.Add(this.tpFile); this.tabMain.Controls.Add(this.tpScan); this.tabMain.Location = new System.Drawing.Point(12, 31); this.tabMain.Name = "tabMain"; this.tabMain.SelectedIndex = 0; this.tabMain.Size = new System.Drawing.Size(771, 449); this.tabMain.TabIndex = 99; // // tpFile // this.tpFile.Controls.Add(this.tabFile); this.tpFile.Controls.Add(this.pnlButtons); this.tpFile.Location = new System.Drawing.Point(4, 22); this.tpFile.Name = "tpFile"; this.tpFile.Padding = new System.Windows.Forms.Padding(3); this.tpFile.Size = new System.Drawing.Size(763, 423); this.tpFile.TabIndex = 4; this.tpFile.Text = "File"; this.tpFile.UseVisualStyleBackColor = true; // // tabFile // this.tabFile.Controls.Add(this.tpID3v2); this.tabFile.Controls.Add(this.tpID3v1); this.tabFile.Dock = System.Windows.Forms.DockStyle.Fill; this.tabFile.Location = new System.Drawing.Point(3, 3); this.tabFile.Name = "tabFile"; this.tabFile.SelectedIndex = 0; this.tabFile.Size = new System.Drawing.Size(757, 385); this.tabFile.TabIndex = 0; // // tpID3v2 // this.tpID3v2.Controls.Add(this.ucID3v2); this.tpID3v2.Location = new System.Drawing.Point(4, 22); this.tpID3v2.Name = "tpID3v2"; this.tpID3v2.Padding = new System.Windows.Forms.Padding(3); this.tpID3v2.Size = new System.Drawing.Size(749, 359); this.tpID3v2.TabIndex = 0; this.tpID3v2.Text = "ID3v2"; this.tpID3v2.UseVisualStyleBackColor = true; // // ucID3v2 // this.ucID3v2.Dock = System.Windows.Forms.DockStyle.Fill; this.ucID3v2.Location = new System.Drawing.Point(3, 3); this.ucID3v2.Name = "ucID3v2"; this.ucID3v2.Size = new System.Drawing.Size(743, 353); this.ucID3v2.TabIndex = 0; // // tpID3v1 // this.tpID3v1.Controls.Add(this.ucID3v1); this.tpID3v1.Location = new System.Drawing.Point(4, 22); this.tpID3v1.Name = "tpID3v1"; this.tpID3v1.Padding = new System.Windows.Forms.Padding(3); this.tpID3v1.Size = new System.Drawing.Size(749, 359); this.tpID3v1.TabIndex = 1; this.tpID3v1.Text = "ID3v1"; this.tpID3v1.UseVisualStyleBackColor = true; // // ucID3v1 // this.ucID3v1.Dock = System.Windows.Forms.DockStyle.Fill; this.ucID3v1.Location = new System.Drawing.Point(3, 3); this.ucID3v1.Name = "ucID3v1"; this.ucID3v1.Size = new System.Drawing.Size(743, 353); this.ucID3v1.TabIndex = 0; // // pnlButtons // this.pnlButtons.Controls.Add(this.btnRemoveID3v1); this.pnlButtons.Controls.Add(this.btnRemoveID3v2); this.pnlButtons.Controls.Add(this.btnSave); this.pnlButtons.Controls.Add(this.btnLoad); this.pnlButtons.Dock = System.Windows.Forms.DockStyle.Bottom; this.pnlButtons.Location = new System.Drawing.Point(3, 388); this.pnlButtons.Name = "pnlButtons"; this.pnlButtons.Size = new System.Drawing.Size(757, 32); this.pnlButtons.TabIndex = 1; // // btnRemoveID3v1 // this.btnRemoveID3v1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnRemoveID3v1.Enabled = false; this.btnRemoveID3v1.Location = new System.Drawing.Point(302, 6); this.btnRemoveID3v1.Name = "btnRemoveID3v1"; this.btnRemoveID3v1.Size = new System.Drawing.Size(94, 23); this.btnRemoveID3v1.TabIndex = 124; this.btnRemoveID3v1.Text = "R&emove ID3v1"; this.btnRemoveID3v1.UseVisualStyleBackColor = true; this.btnRemoveID3v1.Click += new System.EventHandler(this.btnRemoveID3v1_Click); // // btnRemoveID3v2 // this.btnRemoveID3v2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnRemoveID3v2.Enabled = false; this.btnRemoveID3v2.Location = new System.Drawing.Point(202, 6); this.btnRemoveID3v2.Name = "btnRemoveID3v2"; this.btnRemoveID3v2.Size = new System.Drawing.Size(94, 23); this.btnRemoveID3v2.TabIndex = 123; this.btnRemoveID3v2.Text = "&Remove ID3v2"; this.btnRemoveID3v2.UseVisualStyleBackColor = true; this.btnRemoveID3v2.Click += new System.EventHandler(this.btnRemoveID3v2_Click); // // btnSave // this.btnSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnSave.Enabled = false; this.btnSave.Location = new System.Drawing.Point(102, 6); this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(94, 23); this.btnSave.TabIndex = 122; this.btnSave.Text = "&Save"; this.btnSave.UseVisualStyleBackColor = true; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // btnLoad // this.btnLoad.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnLoad.Location = new System.Drawing.Point(2, 6); this.btnLoad.Name = "btnLoad"; this.btnLoad.Size = new System.Drawing.Size(94, 23); this.btnLoad.TabIndex = 121; this.btnLoad.Text = "&Load"; this.btnLoad.UseVisualStyleBackColor = true; this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click); // // tpScan // this.tpScan.Controls.Add(this.btnScan); this.tpScan.Controls.Add(this.dataGridView1); this.tpScan.Controls.Add(this.btnChooseDirectory); this.tpScan.Controls.Add(this.txtDirectory); this.tpScan.Controls.Add(this.lblDirectory); this.tpScan.Controls.Add(this.prgScanFiles); this.tpScan.Location = new System.Drawing.Point(4, 22); this.tpScan.Name = "tpScan"; this.tpScan.Padding = new System.Windows.Forms.Padding(3); this.tpScan.Size = new System.Drawing.Size(763, 423); this.tpScan.TabIndex = 1; this.tpScan.Text = "Scan"; this.tpScan.UseVisualStyleBackColor = true; // // btnScan // this.btnScan.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnScan.Location = new System.Drawing.Point(666, 9); this.btnScan.Name = "btnScan"; this.btnScan.Size = new System.Drawing.Size(75, 20); this.btnScan.TabIndex = 26; this.btnScan.Text = "&Scan"; this.btnScan.UseVisualStyleBackColor = true; this.btnScan.Click += new System.EventHandler(this.btnScan_Click); // // dataGridView1 // this.dataGridView1.AllowUserToAddRows = false; this.dataGridView1.AllowUserToDeleteRows = false; this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.colArtist, this.colTitle, this.colAlbum, this.colGenre, this.colYear, this.colFilename}); this.dataGridView1.Location = new System.Drawing.Point(17, 35); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.ReadOnly = true; this.dataGridView1.Size = new System.Drawing.Size(724, 370); this.dataGridView1.TabIndex = 25; // // colArtist // this.colArtist.DataPropertyName = "Artist"; this.colArtist.HeaderText = "Artist"; this.colArtist.Name = "colArtist"; this.colArtist.ReadOnly = true; // // colTitle // this.colTitle.DataPropertyName = "Title"; this.colTitle.HeaderText = "Title"; this.colTitle.Name = "colTitle"; this.colTitle.ReadOnly = true; // // colAlbum // this.colAlbum.DataPropertyName = "Album"; this.colAlbum.HeaderText = "Album"; this.colAlbum.Name = "colAlbum"; this.colAlbum.ReadOnly = true; // // colGenre // this.colGenre.DataPropertyName = "Genre"; this.colGenre.HeaderText = "Genre"; this.colGenre.Name = "colGenre"; this.colGenre.ReadOnly = true; // // colYear // this.colYear.DataPropertyName = "Year"; this.colYear.HeaderText = "Year"; this.colYear.Name = "colYear"; this.colYear.ReadOnly = true; // // colFilename // this.colFilename.DataPropertyName = "Filename"; this.colFilename.HeaderText = "Filename"; this.colFilename.Name = "colFilename"; this.colFilename.ReadOnly = true; // // btnChooseDirectory // this.btnChooseDirectory.Location = new System.Drawing.Point(414, 9); this.btnChooseDirectory.Name = "btnChooseDirectory"; this.btnChooseDirectory.Size = new System.Drawing.Size(24, 20); this.btnChooseDirectory.TabIndex = 24; this.btnChooseDirectory.Text = "..."; this.btnChooseDirectory.UseVisualStyleBackColor = true; this.btnChooseDirectory.Click += new System.EventHandler(this.btnChooseDirectory_Click); // // txtDirectory // this.txtDirectory.Location = new System.Drawing.Point(98, 9); this.txtDirectory.Name = "txtDirectory"; this.txtDirectory.Size = new System.Drawing.Size(310, 20); this.txtDirectory.TabIndex = 22; // // lblDirectory // this.lblDirectory.AutoSize = true; this.lblDirectory.Location = new System.Drawing.Point(14, 12); this.lblDirectory.Name = "lblDirectory"; this.lblDirectory.Size = new System.Drawing.Size(49, 13); this.lblDirectory.TabIndex = 23; this.lblDirectory.Text = "Directory"; // // prgScanFiles // this.prgScanFiles.Location = new System.Drawing.Point(17, 9); this.prgScanFiles.Name = "prgScanFiles"; this.prgScanFiles.Size = new System.Drawing.Size(549, 20); this.prgScanFiles.TabIndex = 27; this.prgScanFiles.Visible = false; // // folderBrowserDialog // this.folderBrowserDialog.RootFolder = System.Environment.SpecialFolder.MyComputer; this.folderBrowserDialog.ShowNewFolderButton = false; // // audioOpenFileDialog // this.audioOpenFileDialog.Filter = "*.mp3|*.mp3"; // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(795, 521); this.Controls.Add(this.lblVersion); this.Controls.Add(this.btnClose); this.Controls.Add(this.tabMain); this.MinimumSize = new System.Drawing.Size(696, 380); this.Name = "MainForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "IdSharp Harness"; this.tabMain.ResumeLayout(false); this.tpFile.ResumeLayout(false); this.tabFile.ResumeLayout(false); this.tpID3v2.ResumeLayout(false); this.tpID3v1.ResumeLayout(false); this.pnlButtons.ResumeLayout(false); this.tpScan.ResumeLayout(false); this.tpScan.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnClose; private System.Windows.Forms.Label lblVersion; private System.Windows.Forms.TabControl tabMain; private System.Windows.Forms.TabPage tpScan; private System.Windows.Forms.Button btnChooseDirectory; private System.Windows.Forms.TextBox txtDirectory; private System.Windows.Forms.Label lblDirectory; private System.Windows.Forms.Button btnScan; private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.ProgressBar prgScanFiles; private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog; private System.Windows.Forms.DataGridViewTextBoxColumn colArtist; private System.Windows.Forms.DataGridViewTextBoxColumn colTitle; private System.Windows.Forms.DataGridViewTextBoxColumn colAlbum; private System.Windows.Forms.DataGridViewTextBoxColumn colGenre; private System.Windows.Forms.DataGridViewTextBoxColumn colYear; private System.Windows.Forms.DataGridViewTextBoxColumn colFilename; private System.Windows.Forms.TabPage tpFile; private ID3v2UserControl ucID3v2; private ID3v1UserControl ucID3v1; private System.Windows.Forms.TabControl tabFile; private System.Windows.Forms.TabPage tpID3v2; private System.Windows.Forms.TabPage tpID3v1; private System.Windows.Forms.Panel pnlButtons; private System.Windows.Forms.Button btnRemoveID3v2; private System.Windows.Forms.Button btnSave; private System.Windows.Forms.Button btnLoad; private System.Windows.Forms.OpenFileDialog audioOpenFileDialog; private System.Windows.Forms.Button btnRemoveID3v1; } }
using System; using System.IO; using System.Text; using System.Xml; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using System.Net; using System.Globalization; namespace Trinity.Configuration { internal class XMLConfig { private const string section_label = "section"; private const string entry_label = "entry"; private string config_file; private XElement root_xelement; public XMLConfig(string xml_file_name) { config_file = xml_file_name; if (File.Exists(xml_file_name)) { root_xelement = XElement.Load(config_file); } else { root_xelement = new XElement("Trinity"); } } public void Save() { root_xelement.Save(config_file); } public double GetEntryValue(string section, string entry, double defaultValue) { string entry_value = GetEntryValue(section, entry); if (entry_value == null) return defaultValue; try { return Double.Parse(entry_value, CultureInfo.InvariantCulture); } catch { return 0; } } public bool GetEntryValue(string section, string entry, bool defaultValue) { string entry_value = GetEntryValue(section, entry); if (entry_value == null) return defaultValue; try { return Boolean.Parse(entry_value); } catch { return false; } } public string GetEntryValue(string section, string entry, string defaultValue) { string entry_value = GetEntryValue(section, entry); return (entry_value == null ? defaultValue : entry_value); } public IPAddress GetEntryValue(string section, string entry, IPAddress defaultValue) { string entry_value = GetEntryValue(section, entry); return (entry_value == null ? defaultValue : Utilities.NetworkUtility.Hostname2IPv4Address(entry_value)); } public int GetEntryValue(string section, string entry, int defaultValue) { string entry_value = GetEntryValue(section, entry); if (entry_value == null) return defaultValue; try { return Int32.Parse(entry_value, CultureInfo.InvariantCulture); } catch { return 0; } } public long GetEntryValue(string section, string entry, long defaultValue) { string entry_value = GetEntryValue(section, entry); if (entry_value == null) return defaultValue; try { return Int64.Parse(entry_value, CultureInfo.InvariantCulture); } catch { return 0; } } public string GetEntryValue(string section_name, string entry_name) { try { var matched_sections = from section in root_xelement.Elements(section_label) where ((string)section.Attribute("name")).Equals(section_name) select section; return (from entry in matched_sections.Elements(entry_label) where ((string)entry.Attribute("name")).Equals(entry_name) select entry.Value).ToArray<string>()[0]; } catch (Exception) { return null; } } public string GetEntryProperty(string section_name, string entry_name, string entry_value, string property_name) { try { var matched_sections = from section in root_xelement.Elements(section_label) where ((string)section.Attribute("name")).Equals(section_name) select section; var property_values = from entry in matched_sections.Elements(entry_label) where ((string)entry.Attribute("name")).Equals(entry_name) && entry.Value.Equals(entry_value) select ((string)entry.Attribute(property_name)); return property_values.ToArray<string>()[0]; } catch (Exception) { return null; } } public Dictionary<string,string> GetEntryProperties(string section_name, string entry_name, string entry_value) { Dictionary<string, string> dic = new Dictionary<string, string>(); try { var matched_sections = from section in root_xelement.Elements(section_label) where ((string)section.Attribute("name")).Equals(section_name) select section; var attributes = (from entry in matched_sections.Elements(entry_label) where ((string)entry.Attribute("name")).Equals(entry_name) && entry.Value.Equals(entry_value) select entry.Attributes()).ToArray()[0]; foreach (var attribute in attributes) { dic.Add(attribute.Name.ToString(), attribute.Value); } } catch (Exception) { return new Dictionary<string,string>(); } return dic; } public List<string> GetEntryValues(string section_name, string entry_name) { try { var current_section = from section in root_xelement.Elements("section") where ((string)section.Attribute("name")).Equals(section_name) select section; return (from entry in current_section.Elements("entry") where ((string)entry.Attribute("name")).Equals(entry_name) select entry.Value).ToList<string>(); } catch (Exception) { return new List<string>(); } } public List<XElement> GetEntries(string section_name, string entry_name) { try { var sections = from section in root_xelement.Elements("section") where ((string)section.Attribute("name")).Equals(section_name) select section; return (from entry in sections.Elements("entry") where ((string)entry.Attribute("name")).Equals(entry_name) select entry).ToList(); } catch { return new List<XElement>(); } } public void SetEntryValue(string section_name, string entry_name, object entry_value) { var matched_sections = from section in root_xelement.Elements(section_label) where ((string)section.Attribute("name")).Equals(section_name) select section; XElement selected_section; if (matched_sections.Count<object>() == 0) { //selected section doesn't exist selected_section = new XElement(section_label, new XAttribute("name", section_name)); root_xelement.Add(selected_section); } else { selected_section = matched_sections.First<XElement>(); } var matched_entries = from entry in selected_section.Elements(entry_label) where ((string)entry.Attribute("name")).Equals(entry_name) select entry; XElement selected_entry; if (matched_entries.Count<object>() == 0) { //selected entry doesn't exist selected_entry = new XElement(entry_label, new XAttribute("name", entry_name)); selected_section.Add(selected_entry); } else { selected_entry = matched_entries.First<XElement>(); } selected_entry.SetValue(entry_value); } public void SetEntryProperty(string section_name, string entry_name, object entry_value, string property_name, object property_value) { var matched_sections = from section in root_xelement.Elements(section_label) where ((string)section.Attribute("name")).Equals(section_name) select section; XElement selected_section; if (matched_sections.Count<object>() == 0) { //selected section doesn't exist selected_section = new XElement(section_label, new XAttribute("name", section_name)); root_xelement.Add(selected_section); } else { selected_section = matched_sections.First<XElement>(); } var matched_entries = from entry in selected_section.Elements(entry_label) where ((string)entry.Attribute("name")).Equals(entry_name) && entry.Value.Equals(entry_value) select entry; XElement selected_entry; if (matched_entries.Count<object>() == 0) { //selected entry doesn't exist selected_entry = new XElement(entry_label, new XAttribute("name", entry_name)); selected_section.Add(selected_entry); selected_entry.SetValue(entry_value); } else { selected_entry = matched_entries.First<XElement>(); } selected_entry.SetAttributeValue(property_name, property_value); } public void SetEntryValues(string section_name, string entry_name, List<object> entry_value_list) { var matched_sections = from section in root_xelement.Elements(section_label) where ((string)section.Attribute("name")).Equals(section_name) select section; XElement selected_section; if (matched_sections.Count<object>() == 0) { //selected section doesn't exist selected_section = new XElement(section_label, new XAttribute("name", section_name)); root_xelement.Add(selected_section); } else { selected_section = matched_sections.First<XElement>(); } var matched_entries = from entry in selected_section.Elements(entry_label) where ((string)entry.Attribute("name")).Equals(entry_name) select entry; foreach (XElement entry in matched_entries) { entry.Remove(); } for(int i=0;i<entry_value_list.Count;i++) { XElement new_entry = new XElement(entry_label, new XAttribute("name", entry_name)); new_entry.SetValue(entry_value_list[i]); selected_section.Add(new_entry); } } public void SetEntryProperties(string section_name, string entry_name, object entry_value, Dictionary<string,object> property_values) { var matched_sections = from section in root_xelement.Elements(section_label) where ((string)section.Attribute("name")).Equals(section_name) select section; XElement selected_section; if (matched_sections.Count<object>() == 0) { //selected section doesn't exist selected_section = new XElement(section_label, new XAttribute("name", section_name)); root_xelement.Add(selected_section); } else { selected_section = matched_sections.First<XElement>(); } var matched_entries = from entry in selected_section.Elements(entry_label) where ((string)entry.Attribute("name")).Equals(entry_name) && entry.Value.Equals(entry_value) select entry; XElement selected_entry; if (matched_entries.Count<object>() == 0) { //selected entry doesn't exist selected_entry = new XElement(entry_label, new XAttribute("name", entry_name)); selected_section.Add(selected_entry); selected_entry.SetValue(entry_value); } else { selected_entry = matched_entries.First<XElement>(); } foreach (KeyValuePair<string, object> pair in property_values) { selected_entry.SetAttributeValue(pair.Key, pair.Value); } } public void ClearEntryValues(string section_name, string entry_name) { var matched_sections = from section in root_xelement.Elements(section_label) where ((string)section.Attribute("name")).Equals(section_name) select section; XElement selected_section; if (matched_sections.Count<object>() == 0) { //selected section doesn't exist selected_section = new XElement(section_label, new XAttribute("name", section_name)); root_xelement.Add(selected_section); } else { selected_section = matched_sections.First<XElement>(); } var matched_entries = from entry in selected_section.Elements(entry_label) where ((string)entry.Attribute("name")).Equals(entry_name) select entry; foreach (XElement entry in matched_entries) { entry.Remove(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Dynamic.Utils; using System.Linq.Expressions; using System.Reflection; using System.Threading; namespace System.Linq.Expressions.Interpreter { internal partial class CallInstruction { private const int MaxHelpers = 3; private const int MaxArgs = 3; public virtual object InvokeInstance(object instance, params object[] args) { switch (args.Length) { case 0: return Invoke(instance); case 1: return Invoke(instance, args[0]); case 2: return Invoke(instance, args[0], args[1]); case 3: return Invoke(instance, args[0], args[1], args[2]); case 4: return Invoke(instance, args[0], args[1], args[2], args[3]); case 5: return Invoke(instance, args[0], args[1], args[2], args[3], args[4]); case 6: return Invoke(instance, args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return Invoke(instance, args[0], args[1], args[2], args[3], args[4], args[5], args[6]); case 8: return Invoke(instance, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); default: throw new InvalidOperationException(); } } public virtual object Invoke(params object[] args) { switch (args.Length) { case 0: return Invoke(); case 1: return Invoke(args[0]); case 2: return Invoke(args[0], args[1]); case 3: return Invoke(args[0], args[1], args[2]); case 4: return Invoke(args[0], args[1], args[2], args[3]); case 5: return Invoke(args[0], args[1], args[2], args[3], args[4]); case 6: return Invoke(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return Invoke(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); case 8: return Invoke(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); case 9: return Invoke(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]); default: throw new InvalidOperationException(); } } public virtual object Invoke() { throw new InvalidOperationException(); } public virtual object Invoke(object arg0) { throw new InvalidOperationException(); } public virtual object Invoke(object arg0, object arg1) { throw new InvalidOperationException(); } public virtual object Invoke(object arg0, object arg1, object arg2) { throw new InvalidOperationException(); } public virtual object Invoke(object arg0, object arg1, object arg2, object arg3) { throw new InvalidOperationException(); } public virtual object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4) { throw new InvalidOperationException(); } public virtual object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5) { throw new InvalidOperationException(); } public virtual object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) { throw new InvalidOperationException(); } public virtual object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7) { throw new InvalidOperationException(); } public virtual object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8) { throw new InvalidOperationException(); } #if FEATURE_FAST_CREATE /// <summary> /// Fast creation works if we have a known primitive types for the entire /// method siganture. If we have any non-primitive types then FastCreate /// falls back to SlowCreate which works for all types. /// /// Fast creation is fast because it avoids using reflection (MakeGenericType /// and Activator.CreateInstance) to create the types. It does this through /// calling a series of generic methods picking up each strong type of the /// signature along the way. When it runs out of types it news up the /// appropriate CallInstruction with the strong-types that have been built up. /// /// One relaxation is that for return types which are non-primitive types /// we can fallback to object due to relaxed delegates. /// </summary> private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] pi) { Type t = TryGetParameterOrReturnType(target, pi, 0); if (t == null) { return new ActionCallInstruction(target); } if (t.GetTypeInfo().IsEnum) return SlowCreate(target, pi); switch (TypeExtensions.GetTypeCode(t)) { case TypeCode.Object: { if (t != typeof(object) && (IndexIsNotReturnType(0, target, pi) || t.GetTypeInfo().IsValueType)) { // if we're on the return type relaxed delegates makes it ok to use object goto default; } return FastCreate<Object>(target, pi); } case TypeCode.Int16: return FastCreate<Int16>(target, pi); case TypeCode.Int32: return FastCreate<Int32>(target, pi); case TypeCode.Int64: return FastCreate<Int64>(target, pi); case TypeCode.Boolean: return FastCreate<Boolean>(target, pi); case TypeCode.Char: return FastCreate<Char>(target, pi); case TypeCode.Byte: return FastCreate<Byte>(target, pi); case TypeCode.Decimal: return FastCreate<Decimal>(target, pi); case TypeCode.DateTime: return FastCreate<DateTime>(target, pi); case TypeCode.Double: return FastCreate<Double>(target, pi); case TypeCode.Single: return FastCreate<Single>(target, pi); case TypeCode.UInt16: return FastCreate<UInt16>(target, pi); case TypeCode.UInt32: return FastCreate<UInt32>(target, pi); case TypeCode.UInt64: return FastCreate<UInt64>(target, pi); case TypeCode.String: return FastCreate<String>(target, pi); case TypeCode.SByte: return FastCreate<SByte>(target, pi); default: return SlowCreate(target, pi); } } private static CallInstruction FastCreate<T0>(MethodInfo target, ParameterInfo[] pi) { Type t = TryGetParameterOrReturnType(target, pi, 1); if (t == null) { if (target.ReturnType == typeof(void)) { return new ActionCallInstruction<T0>(target); } return new FuncCallInstruction<T0>(target); } if (t.GetTypeInfo().IsEnum) return SlowCreate(target, pi); switch (TypeExtensions.GetTypeCode(t)) { case TypeCode.Object: { if (t != typeof(object) && (IndexIsNotReturnType(1, target, pi) || t.GetTypeInfo().IsValueType)) { // if we're on the return type relaxed delegates makes it ok to use object goto default; } return FastCreate<T0, Object>(target, pi); } case TypeCode.Int16: return FastCreate<T0, Int16>(target, pi); case TypeCode.Int32: return FastCreate<T0, Int32>(target, pi); case TypeCode.Int64: return FastCreate<T0, Int64>(target, pi); case TypeCode.Boolean: return FastCreate<T0, Boolean>(target, pi); case TypeCode.Char: return FastCreate<T0, Char>(target, pi); case TypeCode.Byte: return FastCreate<T0, Byte>(target, pi); case TypeCode.Decimal: return FastCreate<T0, Decimal>(target, pi); case TypeCode.DateTime: return FastCreate<T0, DateTime>(target, pi); case TypeCode.Double: return FastCreate<T0, Double>(target, pi); case TypeCode.Single: return FastCreate<T0, Single>(target, pi); case TypeCode.UInt16: return FastCreate<T0, UInt16>(target, pi); case TypeCode.UInt32: return FastCreate<T0, UInt32>(target, pi); case TypeCode.UInt64: return FastCreate<T0, UInt64>(target, pi); case TypeCode.String: return FastCreate<T0, String>(target, pi); case TypeCode.SByte: return FastCreate<T0, SByte>(target, pi); default: return SlowCreate(target, pi); } } private static CallInstruction FastCreate<T0, T1>(MethodInfo target, ParameterInfo[] pi) { Type t = TryGetParameterOrReturnType(target, pi, 2); if (t == null) { if (target.ReturnType == typeof(void)) { return new ActionCallInstruction<T0, T1>(target); } return new FuncCallInstruction<T0, T1>(target); } if (t.GetTypeInfo().IsEnum) return SlowCreate(target, pi); switch (TypeExtensions.GetTypeCode(t)) { case TypeCode.Object: { Debug.Assert(pi.Length == 2); if (t.GetTypeInfo().IsValueType) goto default; return new FuncCallInstruction<T0, T1, Object>(target); } case TypeCode.Int16: return new FuncCallInstruction<T0, T1, Int16>(target); case TypeCode.Int32: return new FuncCallInstruction<T0, T1, Int32>(target); case TypeCode.Int64: return new FuncCallInstruction<T0, T1, Int64>(target); case TypeCode.Boolean: return new FuncCallInstruction<T0, T1, Boolean>(target); case TypeCode.Char: return new FuncCallInstruction<T0, T1, Char>(target); case TypeCode.Byte: return new FuncCallInstruction<T0, T1, Byte>(target); case TypeCode.Decimal: return new FuncCallInstruction<T0, T1, Decimal>(target); case TypeCode.DateTime: return new FuncCallInstruction<T0, T1, DateTime>(target); case TypeCode.Double: return new FuncCallInstruction<T0, T1, Double>(target); case TypeCode.Single: return new FuncCallInstruction<T0, T1, Single>(target); case TypeCode.UInt16: return new FuncCallInstruction<T0, T1, UInt16>(target); case TypeCode.UInt32: return new FuncCallInstruction<T0, T1, UInt32>(target); case TypeCode.UInt64: return new FuncCallInstruction<T0, T1, UInt64>(target); case TypeCode.String: return new FuncCallInstruction<T0, T1, String>(target); case TypeCode.SByte: return new FuncCallInstruction<T0, T1, SByte>(target); default: return SlowCreate(target, pi); } } #endif #if FEATURE_DLG_INVOKE private static Type GetHelperType(MethodInfo info, Type[] arrTypes) { Type t; if (info.ReturnType == typeof(void)) { switch (arrTypes.Length) { case 0: t = typeof(ActionCallInstruction); break; case 1: t = typeof(ActionCallInstruction<>).MakeGenericType(arrTypes); break; case 2: t = typeof(ActionCallInstruction<,>).MakeGenericType(arrTypes); break; default: throw new InvalidOperationException(); } } else { switch (arrTypes.Length) { case 1: t = typeof(FuncCallInstruction<>).MakeGenericType(arrTypes); break; case 2: t = typeof(FuncCallInstruction<,>).MakeGenericType(arrTypes); break; case 3: t = typeof(FuncCallInstruction<,,>).MakeGenericType(arrTypes); break; default: throw new InvalidOperationException(); } } return t; } #endif } #if FEATURE_DLG_INVOKE internal sealed class ActionCallInstruction : CallInstruction { private readonly Action _target; public override int ArgumentCount { get { return 0; } } public ActionCallInstruction(Action target) { _target = target; } public override int ProducedStack { get { return 0; } } public ActionCallInstruction(MethodInfo target) { _target = (Action)target.CreateDelegate(typeof(Action), target); } public override object Invoke() { _target(); return null; } public override int Run(InterpretedFrame frame) { _target(); frame.StackIndex -= 0; return 1; } } internal sealed class ActionCallInstruction<T0> : CallInstruction { private readonly Action<T0> _target; public override int ProducedStack { get { return 0; } } public override int ArgumentCount { get { return 1; } } public ActionCallInstruction(Action<T0> target) { _target = target; } public ActionCallInstruction(MethodInfo target) { _target = (Action<T0>)target.CreateDelegate(typeof(Action<T0>), target); } public override object Invoke(object arg0) { _target(arg0 != null ? (T0)arg0 : default(T0)); return null; } public override int Run(InterpretedFrame frame) { _target((T0)frame.Data[frame.StackIndex - 1]); frame.StackIndex -= 1; return 1; } } internal sealed class ActionCallInstruction<T0, T1> : CallInstruction { private readonly Action<T0, T1> _target; public override int ProducedStack { get { return 0; } } public override int ArgumentCount { get { return 2; } } public ActionCallInstruction(Action<T0, T1> target) { _target = target; } public ActionCallInstruction(MethodInfo target) { _target = (Action<T0, T1>)target.CreateDelegate(typeof(Action<T0, T1>), target); } public override object Invoke(object arg0, object arg1) { _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1)); return null; } public override int Run(InterpretedFrame frame) { _target((T0)frame.Data[frame.StackIndex - 2], (T1)frame.Data[frame.StackIndex - 1]); frame.StackIndex -= 2; return 1; } } internal sealed class FuncCallInstruction<TRet> : CallInstruction { private readonly Func<TRet> _target; public override int ProducedStack { get { return 1; } } public override int ArgumentCount { get { return 0; } } public FuncCallInstruction(Func<TRet> target) { _target = target; } public FuncCallInstruction(MethodInfo target) { _target = (Func<TRet>)target.CreateDelegate(typeof(Func<TRet>), target); } public override object Invoke() { return _target(); } public override int Run(InterpretedFrame frame) { frame.Data[frame.StackIndex - 0] = _target(); frame.StackIndex -= -1; return 1; } } internal sealed class FuncCallInstruction<T0, TRet> : CallInstruction { private readonly Func<T0, TRet> _target; public override int ProducedStack { get { return 1; } } public override int ArgumentCount { get { return 1; } } public FuncCallInstruction(Func<T0, TRet> target) { _target = target; } public FuncCallInstruction(MethodInfo target) { _target = (Func<T0, TRet>)target.CreateDelegate(typeof(Func<T0, TRet>), target); } public override object Invoke(object arg0) { return _target(arg0 != null ? (T0)arg0 : default(T0)); } public override int Run(InterpretedFrame frame) { frame.Data[frame.StackIndex - 1] = _target((T0)frame.Data[frame.StackIndex - 1]); frame.StackIndex -= 0; return 1; } } internal sealed class FuncCallInstruction<T0, T1, TRet> : CallInstruction { private readonly Func<T0, T1, TRet> _target; public override int ProducedStack { get { return 1; } } public override int ArgumentCount { get { return 2; } } public FuncCallInstruction(Func<T0, T1, TRet> target) { _target = target; } public FuncCallInstruction(MethodInfo target) { _target = (Func<T0, T1, TRet>)target.CreateDelegate(typeof(Func<T0, T1, TRet>), target); } public override object Invoke(object arg0, object arg1) { return _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1)); } public override int Run(InterpretedFrame frame) { frame.Data[frame.StackIndex - 2] = _target((T0)frame.Data[frame.StackIndex - 2], (T1)frame.Data[frame.StackIndex - 1]); frame.StackIndex -= 1; return 1; } } #endif }
// -- FILE ------------------------------------------------------------------ // name : TimeCalendarTest.cs // project : Itenso Time Period // created : Jani Giannoudis - 2011.02.18 // language : C# 4.0 // environment: .NET 2.0 // copyright : (c) 2011-2012 by Itenso GmbH, Switzerland // -------------------------------------------------------------------------- using System; using System.Globalization; using Itenso.TimePeriod; using Xunit; namespace Itenso.TimePeriodTests { // ------------------------------------------------------------------------ public sealed class TimeCalendarTest : TestUnitBase { // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void StartOffsetTest() { Assert.Equal( new TimeCalendar().StartOffset, TimeCalendar.DefaultStartOffset ); TimeSpan offset = Duration.Second; TimeCalendar timeCalendar = new TimeCalendar( new TimeCalendarConfig { StartOffset = offset, EndOffset = TimeSpan.Zero } ); Assert.Equal( timeCalendar.StartOffset, offset ); } // StartOffsetTest // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void EndOffsetTest() { Assert.Equal( new TimeCalendar().EndOffset, TimeCalendar.DefaultEndOffset ); TimeSpan offset = Duration.Second.Negate(); TimeCalendar timeCalendar = new TimeCalendar( new TimeCalendarConfig { StartOffset = TimeSpan.Zero, EndOffset = offset } ); Assert.Equal( timeCalendar.EndOffset, offset ); } // EndOffsetTest // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void InvalidOffset1Test() { Assert.NotNull(Assert.Throws<ArgumentOutOfRangeException>(() => new TimeCalendar( new TimeCalendarConfig { StartOffset = Duration.Second.Negate(), EndOffset = TimeSpan.Zero } ))); } // InvalidOffset1Test // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void InvalidOffset2Test() { Assert.NotNull(Assert.Throws<ArgumentOutOfRangeException>(() => new TimeCalendar( new TimeCalendarConfig { StartOffset = TimeSpan.Zero, EndOffset = Duration.Second } ))); } // InvalidOffset2Test // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void CultureTest() { Assert.Equal( new TimeCalendar().Culture, CultureInfo.CurrentCulture ); CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { Assert.Equal( TimeCalendar.New( culture ).Culture, culture ); } } // CultureTest // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void FirstDayOfWeekTest() { Assert.Equal( new TimeCalendar().FirstDayOfWeek, CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek ); CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { Assert.Equal( TimeCalendar.New( culture ).FirstDayOfWeek, culture.DateTimeFormat.FirstDayOfWeek ); } } // FirstDayOfWeekTest // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void MapStartTest() { DateTime now = ClockProxy.Clock.Now; TimeSpan offset = Duration.Second; CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { Assert.Equal( TimeCalendar.New( culture, TimeSpan.Zero, TimeSpan.Zero ).MapStart( now ), now ); Assert.Equal( TimeCalendar.New( culture, offset, TimeSpan.Zero ).MapStart( now ), now.Add( offset ) ); Assert.Equal( TimeCalendar.New( culture, TimeSpan.Zero, TimeSpan.Zero ).MapStart( testDate ), testDate ); Assert.Equal( TimeCalendar.New( culture, offset, TimeSpan.Zero ).MapStart( testDate ), testDate.Add( offset ) ); } } // MapStartTest // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void UnmapStartTest() { DateTime now = ClockProxy.Clock.Now; TimeSpan offset = Duration.Second; CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { Assert.Equal( TimeCalendar.New( culture, TimeSpan.Zero, TimeSpan.Zero ).UnmapStart( now ), now ); Assert.Equal( TimeCalendar.New( culture, offset, TimeSpan.Zero ).UnmapStart( now ), now.Subtract( offset ) ); Assert.Equal( TimeCalendar.New( culture, TimeSpan.Zero, TimeSpan.Zero ).UnmapStart( testDate ), testDate ); Assert.Equal( TimeCalendar.New( culture, offset, TimeSpan.Zero ).UnmapStart( testDate ), testDate.Subtract( offset ) ); } } // UnmapStartTest // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void MapEndTest() { DateTime now = ClockProxy.Clock.Now; TimeSpan offset = Duration.Second.Negate(); CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { Assert.Equal( TimeCalendar.New( culture, TimeSpan.Zero, TimeSpan.Zero ).MapEnd( now ), now ); Assert.Equal( TimeCalendar.New( culture, TimeSpan.Zero, offset ).MapEnd( now ), now.Add( offset ) ); Assert.Equal( TimeCalendar.New( culture, TimeSpan.Zero, TimeSpan.Zero ).MapEnd( testDate ), testDate ); Assert.Equal( TimeCalendar.New( culture, TimeSpan.Zero, offset ).MapEnd( testDate ), testDate.Add( offset ) ); } } // MapEndTest // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void UnmapEndTest() { DateTime now = ClockProxy.Clock.Now; TimeSpan offset = Duration.Second.Negate(); CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { Assert.Equal( TimeCalendar.New( culture, TimeSpan.Zero, TimeSpan.Zero ).UnmapEnd( now ), now ); Assert.Equal( TimeCalendar.New( culture, TimeSpan.Zero, offset ).UnmapEnd( now ), now.Subtract( offset ) ); Assert.Equal( TimeCalendar.New( culture, TimeSpan.Zero, TimeSpan.Zero ).UnmapEnd( testDate ), testDate ); Assert.Equal( TimeCalendar.New( culture, TimeSpan.Zero, offset ).UnmapEnd( testDate ), testDate.Subtract( offset ) ); } } // UnmapEndTest // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void GetYearTest() { DateTime now = ClockProxy.Clock.Now; CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { Assert.Equal( TimeCalendar.New( culture ).GetYear( now ), culture.Calendar.GetYear( now ) ); Assert.Equal( TimeCalendar.New( culture ).GetYear( testDate ), culture.Calendar.GetYear( testDate ) ); } } // GetYearTest // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void GetMonthTest() { DateTime now = ClockProxy.Clock.Now; CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { Assert.Equal( TimeCalendar.New( culture ).GetMonth( now ), culture.Calendar.GetMonth( now ) ); Assert.Equal( TimeCalendar.New( culture ).GetMonth( testDate ), culture.Calendar.GetMonth( testDate ) ); } } // GetMonthTest // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void GetHourTest() { DateTime now = ClockProxy.Clock.Now; CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { Assert.Equal( TimeCalendar.New( culture ).GetHour( now ), culture.Calendar.GetHour( now ) ); Assert.Equal( TimeCalendar.New( culture ).GetHour( testDate ), culture.Calendar.GetHour( testDate ) ); } } // GetHourTest // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void GetMinuteTest() { DateTime now = ClockProxy.Clock.Now; CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { Assert.Equal( TimeCalendar.New( culture ).GetMinute( now ), culture.Calendar.GetMinute( now ) ); Assert.Equal( TimeCalendar.New( culture ).GetMinute( testDate ), culture.Calendar.GetMinute( testDate ) ); } } // GetMinuteTest // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void GetDayOfMonthTest() { DateTime now = ClockProxy.Clock.Now; CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { Assert.Equal( TimeCalendar.New( culture ).GetDayOfMonth( now ), culture.Calendar.GetDayOfMonth( now ) ); Assert.Equal( TimeCalendar.New( culture ).GetDayOfMonth( testDate ), culture.Calendar.GetDayOfMonth( testDate ) ); } } // GetDayOfMonthTest // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void GetDayOfWeekTest() { DateTime now = ClockProxy.Clock.Now; CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { Assert.Equal( TimeCalendar.New( culture ).GetDayOfWeek( now ), culture.Calendar.GetDayOfWeek( now ) ); Assert.Equal( TimeCalendar.New( culture ).GetDayOfWeek( testDate ), culture.Calendar.GetDayOfWeek( testDate ) ); } } // GetDayOfWeekTest // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void GetDaysInMonthTest() { DateTime now = ClockProxy.Clock.Now; CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { Assert.Equal( TimeCalendar.New( culture ).GetDaysInMonth( now.Year, now.Month ), culture.Calendar.GetDaysInMonth( now.Year, now.Month ) ); Assert.Equal( TimeCalendar.New( culture ).GetDaysInMonth( testDate.Year, testDate.Month ), culture.Calendar.GetDaysInMonth( testDate.Year, testDate.Month ) ); } } // GetDaysInMonthTest // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void GetMonthNameTest() { DateTime now = ClockProxy.Clock.Now; CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { Assert.Equal( TimeCalendar.New( culture ).GetMonthName( now.Month ), culture.DateTimeFormat.GetMonthName( now.Month ) ); Assert.Equal( TimeCalendar.New( culture ).GetMonthName( testDate.Month ), culture.DateTimeFormat.GetMonthName( testDate.Month ) ); } } // GetMonthNameTest // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void GetDayNameTest() { DateTime now = ClockProxy.Clock.Now; CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { Assert.Equal( TimeCalendar.New( culture ).GetDayName( now.DayOfWeek ), culture.DateTimeFormat.GetDayName( now.DayOfWeek ) ); Assert.Equal( TimeCalendar.New( culture ).GetDayName( testDate.DayOfWeek ), culture.DateTimeFormat.GetDayName( testDate.DayOfWeek ) ); } } // GetDayNameTest // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void GetWeekOfYearTest() { DateTime now = ClockProxy.Clock.Now; CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { foreach ( CalendarWeekRule weekRule in Enum.GetValues( typeof( CalendarWeekRule ) ) ) { culture.DateTimeFormat.CalendarWeekRule = weekRule; int year; int weekOfYear; // calendar week TimeCalendar timeCalendar = TimeCalendar.New( culture ); TimeTool.GetWeekOfYear( now, culture, weekRule, culture.DateTimeFormat.FirstDayOfWeek, YearWeekType.Calendar, out year, out weekOfYear ); Assert.Equal( timeCalendar.GetWeekOfYear( now ), weekOfYear ); // iso 8601 calendar week TimeCalendar timeCalendarIso8601 = TimeCalendar.New( culture, YearMonth.January, YearWeekType.Iso8601 ); TimeTool.GetWeekOfYear( now, culture, weekRule, culture.DateTimeFormat.FirstDayOfWeek, YearWeekType.Iso8601, out year, out weekOfYear ); Assert.Equal( timeCalendarIso8601.GetWeekOfYear( now ), weekOfYear ); } } } // GetWeekOfYearTest // ---------------------------------------------------------------------- [Trait("Category", "TimeCalendar")] [Fact] public void GetStartOfWeekTest() { DateTime now = ClockProxy.Clock.Now; CultureTestData cultures = new CultureTestData(); foreach ( CultureInfo culture in cultures ) { foreach ( CalendarWeekRule weekRule in Enum.GetValues( typeof( CalendarWeekRule ) ) ) { culture.DateTimeFormat.CalendarWeekRule = weekRule; int year; int weekOfYear; // calendar week TimeTool.GetWeekOfYear( now, culture, YearWeekType.Calendar, out year, out weekOfYear ); DateTime weekStartCalendar = TimeTool.GetStartOfYearWeek( year, weekOfYear, culture, YearWeekType.Calendar ); TimeCalendar timeCalendar = TimeCalendar.New( culture ); Assert.Equal( timeCalendar.GetStartOfYearWeek( year, weekOfYear ), weekStartCalendar ); // iso 8601 calendar week TimeTool.GetWeekOfYear( now, culture, YearWeekType.Iso8601, out year, out weekOfYear ); DateTime weekStartCalendarIso8601 = TimeTool.GetStartOfYearWeek( year, weekOfYear, culture, YearWeekType.Iso8601 ); TimeCalendar timeCalendarIso8601 = TimeCalendar.New( culture, YearMonth.January, YearWeekType.Iso8601 ); Assert.Equal( timeCalendarIso8601.GetStartOfYearWeek( year, weekOfYear ), weekStartCalendarIso8601 ); } } } // GetStartOfWeekTest // ---------------------------------------------------------------------- // members private readonly DateTime testDate = new DateTime( 2010, 3, 18, 14, 9, 34, 234 ); } // class TimeCalendarTest } // namespace Itenso.TimePeriodTests // -- EOF -------------------------------------------------------------------
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using System.Collections.ObjectModel; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium { [TestFixture] public class ElementFindingTest : DriverTestFixture { [Test] public void ShouldReturnTitleOfPageIfSet() { driver.Url = xhtmlTestPage; Assert.AreEqual(driver.Title, "XHTML Test Page"); driver.Url = simpleTestPage; Assert.AreEqual(driver.Title, "Hello WebDriver"); } [Test] [ExpectedException(typeof(NoSuchElementException))] public void ShouldNotBeAbleToLocateASingleElementThatDoesNotExist() { driver.Url = formsPage; driver.FindElement(By.Id("nonExistantButton")); } [Test] public void ShouldBeAbleToClickOnLinkIdentifiedByText() { driver.Url = xhtmlTestPage; driver.FindElement(By.LinkText("click me")).Click(); //TODO (jimevan): this is an ugly sleep. Remove when implicit waiting is implemented. System.Threading.Thread.Sleep(500); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void DriverShouldBeAbleToFindElementsAfterLoadingMoreThanOnePageAtATime() { driver.Url = formsPage; driver.Url = xhtmlTestPage; driver.FindElement(By.LinkText("click me")).Click(); //TODO (jimevan): this is an ugly sleep. Remove when implicit waiting is implemented. System.Threading.Thread.Sleep(500); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldBeAbleToClickOnLinkIdentifiedById() { driver.Url = xhtmlTestPage; driver.FindElement(By.Id("linkId")).Click(); //TODO (jimevan): this is an ugly sleep. Remove when implicit waiting is implemented. System.Threading.Thread.Sleep(500); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] [ExpectedException(typeof(NoSuchElementException))] public void ShouldThrowAnExceptionWhenThereIsNoLinkToClickAndItIsFoundWithLinkText() { driver.Url = xhtmlTestPage; driver.FindElement(By.LinkText("Not here either")); } [Test] public void ShouldFindAnElementBasedOnId() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("checky")); Assert.IsFalse(element.Selected); } [Test] [ExpectedException(typeof(NoSuchElementException))] public void ShouldNotBeAbleToFindElementsBasedOnIdIfTheElementIsNotThere() { driver.Url = formsPage; driver.FindElement(By.Id("notThere")); } [Test] public void ShouldBeAbleToFindChildrenOfANode() { driver.Url = xhtmlTestPage; ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.XPath("/html/head")); IWebElement head = elements[0]; ReadOnlyCollection<IWebElement> importedScripts = head.FindElements(By.TagName("script")); Assert.AreEqual(importedScripts.Count, 2); } [Test] public void ReturnAnEmptyListWhenThereAreNoChildrenOfANode() { driver.Url = xhtmlTestPage; IWebElement table = driver.FindElement(By.Id("table")); ReadOnlyCollection<IWebElement> rows = table.FindElements(By.TagName("tr")); Assert.AreEqual(rows.Count, 0); } [Test] public void ShouldFindElementsByName() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Name("checky")); Assert.AreEqual(element.Value, "furrfu"); } [Test] public void ShouldFindElementsByClass() { driver.Url = xhtmlTestPage; IWebElement element = driver.FindElement(By.ClassName("extraDiv")); Assert.IsTrue(element.Text.StartsWith("Another div starts here.")); } [Test] public void ShouldFindElementsByClassWhenItIsTheFirstNameAmongMany() { driver.Url = xhtmlTestPage; IWebElement element = driver.FindElement(By.ClassName("nameA")); Assert.AreEqual(element.Text, "An H2 title"); } [Test] public void ShouldFindElementsByClassWhenItIsTheLastNameAmongMany() { driver.Url = xhtmlTestPage; IWebElement element = driver.FindElement(By.ClassName("nameC")); Assert.AreEqual(element.Text, "An H2 title"); } [Test] public void ShouldFindElementsByClassWhenItIsInTheMiddleAmongMany() { driver.Url = xhtmlTestPage; IWebElement element = driver.FindElement(By.ClassName("nameBnoise")); Assert.AreEqual(element.Text, "An H2 title"); } [Test] public void ShouldFindElementByClassWhenItsNameIsSurroundedByWhitespace() { driver.Url = xhtmlTestPage; IWebElement element = driver.FindElement(By.ClassName("spaceAround")); Assert.AreEqual("Spaced out", element.Text); } [Test] public void ShouldFindElementsByClassWhenItsNameIsSurroundedByWhitespace() { driver.Url = xhtmlTestPage; ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.ClassName("spaceAround")); Assert.AreEqual(1, elements.Count); Assert.AreEqual("Spaced out", elements[0].Text); } [Test] [ExpectedException(typeof(NoSuchElementException))] public void ShouldNotFindElementsByClassWhenTheNameQueriedIsShorterThanCandidateName() { driver.Url = xhtmlTestPage; driver.FindElement(By.ClassName("nameB")); } [Test] public void ShouldBeAbleToFindMultipleElementsByXPath() { driver.Url = xhtmlTestPage; ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.XPath("//div")); Assert.IsTrue(elements.Count > 1); } [Test] public void ShouldBeAbleToFindMultipleElementsByLinkText() { driver.Url = xhtmlTestPage; ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.LinkText("click me")); Assert.IsTrue(elements.Count == 2, "Expected 2 links, got " + elements.Count); } [Test] public void ShouldBeAbleToFindMultipleElementsByPartialLinkText() { driver.Url = xhtmlTestPage; ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.PartialLinkText("ick me")); Assert.IsTrue(elements.Count == 2); } [Test] public void ShouldBeAbleToFindElementByPartialLinkText() { driver.Url = xhtmlTestPage; driver.FindElement(By.PartialLinkText("anon")); } [Test] public void ShouldBeAbleToFindMultipleElementsByName() { driver.Url = nestedPage; ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Name("checky")); Assert.IsTrue(elements.Count > 1); } [Test] public void ShouldBeAbleToFindMultipleElementsById() { driver.Url = nestedPage; ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Id("2")); Assert.AreEqual(8, elements.Count); } [Test] public void ShouldBeAbleToFindMultipleElementsByClassName() { driver.Url = xhtmlTestPage; ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.ClassName("nameC")); Assert.IsTrue(elements.Count > 1); } [Test] // You don't want to ask why this is here public void WhenFindingByNameShouldNotReturnById() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Name("id-name1")); Assert.AreEqual(element.Value, "name"); element = driver.FindElement(By.Id("id-name1")); Assert.AreEqual(element.Value, "id"); element = driver.FindElement(By.Name("id-name2")); Assert.AreEqual(element.Value, "name"); element = driver.FindElement(By.Id("id-name2")); Assert.AreEqual(element.Value, "id"); } [Test] public void ShouldFindGrandChildren() { driver.Url = formsPage; IWebElement form = driver.FindElement(By.Id("nested_form")); form.FindElement(By.Name("x")); } [Test] [ExpectedException(typeof(NoSuchElementException))] public void ShouldNotFindElementOutSideTree() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Name("login")); element.FindElement(By.Name("x")); } [Test] public void ShouldReturnElementsThatDoNotSupportTheNameProperty() { driver.Url = nestedPage; driver.FindElement(By.Name("div1")); // If this works, we're all good } [Test] public void ShouldFindHiddenElementsByName() { driver.Url = formsPage; driver.FindElement(By.Name("hidden")); } [Test] public void ShouldFindAnElementBasedOnTagName() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.TagName("input")); Assert.IsNotNull(element); } [Test] public void ShouldfindElementsBasedOnTagName() { driver.Url = formsPage; ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.TagName("input")); Assert.IsNotNull(elements); } [Test] [ExpectedException(typeof(IllegalLocatorException))] public void FindingElementByCompoundClassNameIsAnError() { driver.Url = xhtmlTestPage; driver.FindElement(By.ClassName("a b")); } [Test] [ExpectedException(typeof(IllegalLocatorException))] public void FindingElementCollectionByCompoundClassNameIsAnError() { driver.FindElements(By.ClassName("a b")); } [Test] [Category("Javascript")] public void ShouldBeAbleToClickOnLinksWithNoHrefAttribute() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.LinkText("No href")); element.Click(); // if any exception is thrown, we won't get this far. Sanity check Assert.AreEqual("Changed", driver.Title); } [Test] [ExpectedException(typeof(NoSuchElementException))] public void ShouldNotBeAbleToFindAnElementOnABlankPage() { driver.Url = "about:blank"; driver.FindElement(By.TagName("a")); } [Test] [ExpectedException(typeof(NoSuchElementException))] public void ShouldNotBeAbleToLocateASingleElementOnABlankPage() { // Note we're on the default start page for the browser at this point. CreateFreshDriver(); driver.FindElement(By.Id("nonExistantButton")); } [Test] [Category("Javascript")] [ExpectedException(typeof(StaleElementReferenceException))] public void RemovingAnElementDynamicallyFromTheDomShouldCauseAStaleRefException() { driver.Url = javascriptPage; IRenderedWebElement toBeDeleted = (IRenderedWebElement)driver.FindElement(By.Id("deleted")); Assert.IsTrue(toBeDeleted.Displayed); driver.FindElement(By.Id("delete")).Click(); //TODO (jimevan): this is an ugly sleep. Remove when implicit waiting is implemented. System.Threading.Thread.Sleep(500); bool displayedAfterDelete = toBeDeleted.Displayed; } [Test] public void FindingALinkByXpathUsingContainsKeywordShouldWork() { driver.Url = nestedPage; driver.FindElement(By.XPath("//a[contains(.,'hello world')]")); } [Test] [Category("Javascript")] public void ShouldBeAbleToFindAnElementByCssSelector() { if (!SupportsSelectorApi()) { Assert.Ignore("Skipping test: selector API not supported"); } driver.Url = xhtmlTestPage; driver.FindElement(By.CssSelector("div.content")); } [Test] [Category("Javascript")] public void ShouldBeAbleToFindAnElementsByCssSelector() { if (!SupportsSelectorApi()) { Assert.Ignore("Skipping test: selector API not supported"); } driver.Url = xhtmlTestPage; driver.FindElements(By.CssSelector("p")); } private bool SupportsSelectorApi() { return driver is IFindsByCssSelector && (bool)((IJavaScriptExecutor)driver).ExecuteScript("return document['querySelector'] !== undefined;"); } } }
namespace Gurtle { using System.Windows.Forms; partial class WebProxyDialog { /// <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.Windows.Forms.Button btnCancel; System.Windows.Forms.Button btnOK; System.Windows.Forms.Label label4; System.Windows.Forms.Label label1; System.Windows.Forms.Label label2; System.Windows.Forms.Label label3; System.Windows.Forms.Label label5; this._testButton = new System.Windows.Forms.Button(); this._noExpectContinueBox = new System.Windows.Forms.CheckBox(); this._autoBox = new System.Windows.Forms.RadioButton(); this._manualBox = new System.Windows.Forms.RadioButton(); this._passwordBox = new System.Windows.Forms.TextBox(); this._addressBox = new System.Windows.Forms.TextBox(); this._domainBox = new System.Windows.Forms.TextBox(); this._userNameBox = new System.Windows.Forms.TextBox(); this._portBox = new System.Windows.Forms.TextBox(); btnCancel = new System.Windows.Forms.Button(); btnOK = new System.Windows.Forms.Button(); label4 = new System.Windows.Forms.Label(); label1 = new System.Windows.Forms.Label(); label2 = new System.Windows.Forms.Label(); label3 = new System.Windows.Forms.Label(); label5 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // btnCancel // btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; btnCancel.Location = new System.Drawing.Point(327, 285); btnCancel.Margin = new System.Windows.Forms.Padding(3, 3, 1, 3); btnCancel.Name = "btnCancel"; btnCancel.Size = new System.Drawing.Size(90, 30); btnCancel.TabIndex = 15; btnCancel.Text = "Cancel"; btnCancel.UseVisualStyleBackColor = true; // // btnOK // btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); btnOK.Location = new System.Drawing.Point(231, 285); btnOK.Name = "btnOK"; btnOK.Size = new System.Drawing.Size(90, 30); btnOK.TabIndex = 14; btnOK.Text = "OK"; btnOK.UseVisualStyleBackColor = true; // // label4 // label4.AutoSize = true; label4.Location = new System.Drawing.Point(31, 191); label4.Margin = new System.Windows.Forms.Padding(21, 0, 3, 0); label4.Name = "label4"; label4.Size = new System.Drawing.Size(71, 17); label4.TabIndex = 10; label4.Text = "Pa&ssword:"; label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label1 // label1.AutoSize = true; label1.Location = new System.Drawing.Point(31, 71); label1.Margin = new System.Windows.Forms.Padding(21, 0, 3, 0); label1.Name = "label1"; label1.Size = new System.Drawing.Size(102, 17); label1.TabIndex = 2; label1.Text = "&Proxy Address:"; label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label2 // label2.AutoSize = true; label2.Location = new System.Drawing.Point(31, 131); label2.Margin = new System.Windows.Forms.Padding(21, 0, 3, 0); label2.Name = "label2"; label2.Size = new System.Drawing.Size(60, 17); label2.TabIndex = 6; label2.Text = "&Domain:"; label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label3 // label3.AutoSize = true; label3.Location = new System.Drawing.Point(31, 161); label3.Margin = new System.Windows.Forms.Padding(21, 0, 3, 0); label3.Name = "label3"; label3.Size = new System.Drawing.Size(79, 17); label3.TabIndex = 8; label3.Text = "&User Name:"; label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label5 // label5.AutoSize = true; label5.Location = new System.Drawing.Point(31, 101); label5.Margin = new System.Windows.Forms.Padding(21, 0, 3, 0); label5.Name = "label5"; label5.Size = new System.Drawing.Size(80, 17); label5.TabIndex = 4; label5.Text = "P&roxy Port:"; label5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // _testButton // this._testButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this._testButton.Location = new System.Drawing.Point(13, 285); this._testButton.Name = "_testButton"; this._testButton.Size = new System.Drawing.Size(90, 30); this._testButton.TabIndex = 13; this._testButton.Text = "&Test"; this._testButton.UseVisualStyleBackColor = true; this._testButton.Click += new System.EventHandler(this.TestButton_Click); // // _noExpectContinueBox // this._noExpectContinueBox.AutoSize = true; this._noExpectContinueBox.Location = new System.Drawing.Point(146, 223); this._noExpectContinueBox.Margin = new System.Windows.Forms.Padding(3, 8, 3, 1); this._noExpectContinueBox.Name = "_noExpectContinueBox"; this._noExpectContinueBox.Size = new System.Drawing.Size(207, 21); this._noExpectContinueBox.TabIndex = 12; this._noExpectContinueBox.Text = "Do not expect 100-Continue"; this._noExpectContinueBox.UseVisualStyleBackColor = true; // // _autoBox // this._autoBox.AutoSize = true; this._autoBox.Checked = true; this._autoBox.Location = new System.Drawing.Point(13, 14); this._autoBox.Name = "_autoBox"; this._autoBox.Size = new System.Drawing.Size(245, 21); this._autoBox.TabIndex = 0; this._autoBox.TabStop = true; this._autoBox.Text = "&Automatically detect proxy settings"; this._autoBox.UseVisualStyleBackColor = true; // // _manualBox // this._manualBox.AutoSize = true; this._manualBox.Location = new System.Drawing.Point(13, 41); this._manualBox.Name = "_manualBox"; this._manualBox.Padding = new System.Windows.Forms.Padding(0, 0, 0, 6); this._manualBox.Size = new System.Drawing.Size(204, 27); this._manualBox.TabIndex = 1; this._manualBox.Text = "&Use following proxy settings:"; this._manualBox.UseVisualStyleBackColor = true; // // _passwordBox // this._passwordBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._passwordBox.Location = new System.Drawing.Point(146, 188); this._passwordBox.Margin = new System.Windows.Forms.Padding(3, 3, 0, 3); this._passwordBox.Name = "_passwordBox"; this._passwordBox.PasswordChar = '*'; this._passwordBox.Size = new System.Drawing.Size(272, 24); this._passwordBox.TabIndex = 11; // // _addressBox // this._addressBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._addressBox.Location = new System.Drawing.Point(146, 68); this._addressBox.Margin = new System.Windows.Forms.Padding(3, 3, 0, 3); this._addressBox.Name = "_addressBox"; this._addressBox.Size = new System.Drawing.Size(272, 24); this._addressBox.TabIndex = 3; // // _domainBox // this._domainBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._domainBox.Location = new System.Drawing.Point(146, 128); this._domainBox.Margin = new System.Windows.Forms.Padding(3, 3, 0, 3); this._domainBox.Name = "_domainBox"; this._domainBox.Size = new System.Drawing.Size(272, 24); this._domainBox.TabIndex = 7; // // _userNameBox // this._userNameBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._userNameBox.Location = new System.Drawing.Point(145, 158); this._userNameBox.Margin = new System.Windows.Forms.Padding(3, 3, 0, 3); this._userNameBox.Name = "_userNameBox"; this._userNameBox.Size = new System.Drawing.Size(273, 24); this._userNameBox.TabIndex = 9; // // _portBox // this._portBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._portBox.Location = new System.Drawing.Point(146, 98); this._portBox.Name = "_portBox"; this._portBox.Size = new System.Drawing.Size(63, 24); this._portBox.TabIndex = 5; // // WebProxyDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 17F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(428, 326); this.Controls.Add(this._noExpectContinueBox); this.Controls.Add(this._autoBox); this.Controls.Add(this._testButton); this.Controls.Add(btnCancel); this.Controls.Add(this._manualBox); this.Controls.Add(btnOK); this.Controls.Add(label4); this.Controls.Add(this._passwordBox); this.Controls.Add(label1); this.Controls.Add(label2); this.Controls.Add(label3); this.Controls.Add(this._addressBox); this.Controls.Add(this._domainBox); this.Controls.Add(this._userNameBox); this.Controls.Add(label5); this.Controls.Add(this._portBox); 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.MaximizeBox = false; this.MinimizeBox = false; this.Name = "WebProxyDialog"; this.Padding = new System.Windows.Forms.Padding(10, 12, 10, 8); this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Web Proxy"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private RadioButton _autoBox; private RadioButton _manualBox; private TextBox _passwordBox; private TextBox _addressBox; private TextBox _domainBox; private TextBox _userNameBox; private TextBox _portBox; private CheckBox _noExpectContinueBox; private Button _testButton; } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.Compute.V1 { /// <summary>Settings for <see cref="MachineTypesClient"/> instances.</summary> public sealed partial class MachineTypesSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="MachineTypesSettings"/>.</summary> /// <returns>A new instance of the default <see cref="MachineTypesSettings"/>.</returns> public static MachineTypesSettings GetDefault() => new MachineTypesSettings(); /// <summary>Constructs a new <see cref="MachineTypesSettings"/> object with default settings.</summary> public MachineTypesSettings() { } private MachineTypesSettings(MachineTypesSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); AggregatedListSettings = existing.AggregatedListSettings; GetSettings = existing.GetSettings; ListSettings = existing.ListSettings; OnCopy(existing); } partial void OnCopy(MachineTypesSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>MachineTypesClient.AggregatedList</c> and <c>MachineTypesClient.AggregatedListAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings AggregatedListSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>MachineTypesClient.Get</c> /// and <c>MachineTypesClient.GetAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>MachineTypesClient.List</c> /// and <c>MachineTypesClient.ListAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="MachineTypesSettings"/> object.</returns> public MachineTypesSettings Clone() => new MachineTypesSettings(this); } /// <summary> /// Builder class for <see cref="MachineTypesClient"/> to provide simple configuration of credentials, endpoint etc. /// </summary> public sealed partial class MachineTypesClientBuilder : gaxgrpc::ClientBuilderBase<MachineTypesClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public MachineTypesSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public MachineTypesClientBuilder() { UseJwtAccessWithScopes = MachineTypesClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref MachineTypesClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<MachineTypesClient> task); /// <summary>Builds the resulting client.</summary> public override MachineTypesClient Build() { MachineTypesClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<MachineTypesClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<MachineTypesClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private MachineTypesClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return MachineTypesClient.Create(callInvoker, Settings); } private async stt::Task<MachineTypesClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return MachineTypesClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => MachineTypesClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => MachineTypesClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => MachineTypesClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => ComputeRestAdapter.ComputeAdapter; } /// <summary>MachineTypes client wrapper, for convenient use.</summary> /// <remarks> /// The MachineTypes API. /// </remarks> public abstract partial class MachineTypesClient { /// <summary> /// The default endpoint for the MachineTypes service, which is a host of "compute.googleapis.com" and a port of /// 443. /// </summary> public static string DefaultEndpoint { get; } = "compute.googleapis.com:443"; /// <summary>The default MachineTypes scopes.</summary> /// <remarks> /// The default MachineTypes scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/compute.readonly</description></item> /// <item><description>https://www.googleapis.com/auth/compute</description></item> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/compute.readonly", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="MachineTypesClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="MachineTypesClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="MachineTypesClient"/>.</returns> public static stt::Task<MachineTypesClient> CreateAsync(st::CancellationToken cancellationToken = default) => new MachineTypesClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="MachineTypesClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="MachineTypesClientBuilder"/>. /// </summary> /// <returns>The created <see cref="MachineTypesClient"/>.</returns> public static MachineTypesClient Create() => new MachineTypesClientBuilder().Build(); /// <summary> /// Creates a <see cref="MachineTypesClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="MachineTypesSettings"/>.</param> /// <returns>The created <see cref="MachineTypesClient"/>.</returns> internal static MachineTypesClient Create(grpccore::CallInvoker callInvoker, MachineTypesSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } MachineTypes.MachineTypesClient grpcClient = new MachineTypes.MachineTypesClient(callInvoker); return new MachineTypesClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC MachineTypes client</summary> public virtual MachineTypes.MachineTypesClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Retrieves an aggregated list of machine types. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="scg::KeyValuePair{TKey,TValue}"/> resources.</returns> public virtual gax::PagedEnumerable<MachineTypeAggregatedList, scg::KeyValuePair<string, MachineTypesScopedList>> AggregatedList(AggregatedListMachineTypesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves an aggregated list of machine types. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns> /// A pageable asynchronous sequence of <see cref="scg::KeyValuePair{TKey,TValue}"/> resources. /// </returns> public virtual gax::PagedAsyncEnumerable<MachineTypeAggregatedList, scg::KeyValuePair<string, MachineTypesScopedList>> AggregatedListAsync(AggregatedListMachineTypesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves an aggregated list of machine types. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="scg::KeyValuePair{TKey,TValue}"/> resources.</returns> public virtual gax::PagedEnumerable<MachineTypeAggregatedList, scg::KeyValuePair<string, MachineTypesScopedList>> AggregatedList(string project, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => AggregatedList(new AggregatedListMachineTypesRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Retrieves an aggregated list of machine types. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns> /// A pageable asynchronous sequence of <see cref="scg::KeyValuePair{TKey,TValue}"/> resources. /// </returns> public virtual gax::PagedAsyncEnumerable<MachineTypeAggregatedList, scg::KeyValuePair<string, MachineTypesScopedList>> AggregatedListAsync(string project, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => AggregatedListAsync(new AggregatedListMachineTypesRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Returns the specified machine type. Gets a list of available machine types by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MachineType Get(GetMachineTypeRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the specified machine type. Gets a list of available machine types by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MachineType> GetAsync(GetMachineTypeRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the specified machine type. Gets a list of available machine types by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MachineType> GetAsync(GetMachineTypeRequest request, st::CancellationToken cancellationToken) => GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the specified machine type. Gets a list of available machine types by making a list() request. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="zone"> /// The name of the zone for this request. /// </param> /// <param name="machineType"> /// Name of the machine type to return. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MachineType Get(string project, string zone, string machineType, gaxgrpc::CallSettings callSettings = null) => Get(new GetMachineTypeRequest { MachineType = gax::GaxPreconditions.CheckNotNullOrEmpty(machineType, nameof(machineType)), Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Zone = gax::GaxPreconditions.CheckNotNullOrEmpty(zone, nameof(zone)), }, callSettings); /// <summary> /// Returns the specified machine type. Gets a list of available machine types by making a list() request. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="zone"> /// The name of the zone for this request. /// </param> /// <param name="machineType"> /// Name of the machine type to return. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MachineType> GetAsync(string project, string zone, string machineType, gaxgrpc::CallSettings callSettings = null) => GetAsync(new GetMachineTypeRequest { MachineType = gax::GaxPreconditions.CheckNotNullOrEmpty(machineType, nameof(machineType)), Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Zone = gax::GaxPreconditions.CheckNotNullOrEmpty(zone, nameof(zone)), }, callSettings); /// <summary> /// Returns the specified machine type. Gets a list of available machine types by making a list() request. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="zone"> /// The name of the zone for this request. /// </param> /// <param name="machineType"> /// Name of the machine type to return. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MachineType> GetAsync(string project, string zone, string machineType, st::CancellationToken cancellationToken) => GetAsync(project, zone, machineType, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Retrieves a list of machine types available to the specified project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="MachineType"/> resources.</returns> public virtual gax::PagedEnumerable<MachineTypeList, MachineType> List(ListMachineTypesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves a list of machine types available to the specified project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="MachineType"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<MachineTypeList, MachineType> ListAsync(ListMachineTypesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves a list of machine types available to the specified project. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="zone"> /// The name of the zone for this request. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="MachineType"/> resources.</returns> public virtual gax::PagedEnumerable<MachineTypeList, MachineType> List(string project, string zone, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => List(new ListMachineTypesRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Zone = gax::GaxPreconditions.CheckNotNullOrEmpty(zone, nameof(zone)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Retrieves a list of machine types available to the specified project. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="zone"> /// The name of the zone for this request. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="MachineType"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<MachineTypeList, MachineType> ListAsync(string project, string zone, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListAsync(new ListMachineTypesRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Zone = gax::GaxPreconditions.CheckNotNullOrEmpty(zone, nameof(zone)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); } /// <summary>MachineTypes client wrapper implementation, for convenient use.</summary> /// <remarks> /// The MachineTypes API. /// </remarks> public sealed partial class MachineTypesClientImpl : MachineTypesClient { private readonly gaxgrpc::ApiCall<AggregatedListMachineTypesRequest, MachineTypeAggregatedList> _callAggregatedList; private readonly gaxgrpc::ApiCall<GetMachineTypeRequest, MachineType> _callGet; private readonly gaxgrpc::ApiCall<ListMachineTypesRequest, MachineTypeList> _callList; /// <summary> /// Constructs a client wrapper for the MachineTypes service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="MachineTypesSettings"/> used within this client.</param> public MachineTypesClientImpl(MachineTypes.MachineTypesClient grpcClient, MachineTypesSettings settings) { GrpcClient = grpcClient; MachineTypesSettings effectiveSettings = settings ?? MachineTypesSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callAggregatedList = clientHelper.BuildApiCall<AggregatedListMachineTypesRequest, MachineTypeAggregatedList>(grpcClient.AggregatedListAsync, grpcClient.AggregatedList, effectiveSettings.AggregatedListSettings).WithGoogleRequestParam("project", request => request.Project); Modify_ApiCall(ref _callAggregatedList); Modify_AggregatedListApiCall(ref _callAggregatedList); _callGet = clientHelper.BuildApiCall<GetMachineTypeRequest, MachineType>(grpcClient.GetAsync, grpcClient.Get, effectiveSettings.GetSettings).WithGoogleRequestParam("project", request => request.Project).WithGoogleRequestParam("zone", request => request.Zone).WithGoogleRequestParam("machine_type", request => request.MachineType); Modify_ApiCall(ref _callGet); Modify_GetApiCall(ref _callGet); _callList = clientHelper.BuildApiCall<ListMachineTypesRequest, MachineTypeList>(grpcClient.ListAsync, grpcClient.List, effectiveSettings.ListSettings).WithGoogleRequestParam("project", request => request.Project).WithGoogleRequestParam("zone", request => request.Zone); Modify_ApiCall(ref _callList); Modify_ListApiCall(ref _callList); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_AggregatedListApiCall(ref gaxgrpc::ApiCall<AggregatedListMachineTypesRequest, MachineTypeAggregatedList> call); partial void Modify_GetApiCall(ref gaxgrpc::ApiCall<GetMachineTypeRequest, MachineType> call); partial void Modify_ListApiCall(ref gaxgrpc::ApiCall<ListMachineTypesRequest, MachineTypeList> call); partial void OnConstruction(MachineTypes.MachineTypesClient grpcClient, MachineTypesSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC MachineTypes client</summary> public override MachineTypes.MachineTypesClient GrpcClient { get; } partial void Modify_AggregatedListMachineTypesRequest(ref AggregatedListMachineTypesRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GetMachineTypeRequest(ref GetMachineTypeRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ListMachineTypesRequest(ref ListMachineTypesRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Retrieves an aggregated list of machine types. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="scg::KeyValuePair{TKey,TValue}"/> resources.</returns> public override gax::PagedEnumerable<MachineTypeAggregatedList, scg::KeyValuePair<string, MachineTypesScopedList>> AggregatedList(AggregatedListMachineTypesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_AggregatedListMachineTypesRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<AggregatedListMachineTypesRequest, MachineTypeAggregatedList, scg::KeyValuePair<string, MachineTypesScopedList>>(_callAggregatedList, request, callSettings); } /// <summary> /// Retrieves an aggregated list of machine types. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns> /// A pageable asynchronous sequence of <see cref="scg::KeyValuePair{TKey,TValue}"/> resources. /// </returns> public override gax::PagedAsyncEnumerable<MachineTypeAggregatedList, scg::KeyValuePair<string, MachineTypesScopedList>> AggregatedListAsync(AggregatedListMachineTypesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_AggregatedListMachineTypesRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<AggregatedListMachineTypesRequest, MachineTypeAggregatedList, scg::KeyValuePair<string, MachineTypesScopedList>>(_callAggregatedList, request, callSettings); } /// <summary> /// Returns the specified machine type. Gets a list of available machine types by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MachineType Get(GetMachineTypeRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetMachineTypeRequest(ref request, ref callSettings); return _callGet.Sync(request, callSettings); } /// <summary> /// Returns the specified machine type. Gets a list of available machine types by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MachineType> GetAsync(GetMachineTypeRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetMachineTypeRequest(ref request, ref callSettings); return _callGet.Async(request, callSettings); } /// <summary> /// Retrieves a list of machine types available to the specified project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="MachineType"/> resources.</returns> public override gax::PagedEnumerable<MachineTypeList, MachineType> List(ListMachineTypesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListMachineTypesRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListMachineTypesRequest, MachineTypeList, MachineType>(_callList, request, callSettings); } /// <summary> /// Retrieves a list of machine types available to the specified project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="MachineType"/> resources.</returns> public override gax::PagedAsyncEnumerable<MachineTypeList, MachineType> ListAsync(ListMachineTypesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListMachineTypesRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListMachineTypesRequest, MachineTypeList, MachineType>(_callList, request, callSettings); } } public partial class AggregatedListMachineTypesRequest : gaxgrpc::IPageRequest { /// <inheritdoc/> public int PageSize { get => checked((int)MaxResults); set => MaxResults = checked((uint)value); } } public partial class ListMachineTypesRequest : gaxgrpc::IPageRequest { /// <inheritdoc/> public int PageSize { get => checked((int)MaxResults); set => MaxResults = checked((uint)value); } } public partial class MachineTypeAggregatedList : gaxgrpc::IPageResponse<scg::KeyValuePair<string, MachineTypesScopedList>> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<scg::KeyValuePair<string, MachineTypesScopedList>> GetEnumerator() => Items.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } public partial class MachineTypeList : gaxgrpc::IPageResponse<MachineType> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<MachineType> GetEnumerator() => Items.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } }
// 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.Reflection; using System.Reflection.Emit; using Xunit; namespace System.Reflection.Emit.Tests { public class ModuleBuilderDefineUninitializedData { private const string DefaultAssemblyName = "ModuleBuilderDefineUninitializedData"; private const AssemblyBuilderAccess DefaultAssemblyBuilderAccess = AssemblyBuilderAccess.Run; private const string DefaultModuleName = "DynamicModule"; private const int MinStringLength = 8; private const int MaxStringLength = 256; private const int ReservedMaskFieldAttribute = 0x9500; // This constant maps to FieldAttributes.ReservedMask that is not available in the contract. private ModuleBuilder GetModuleBuilder() { AssemblyName name = new AssemblyName(DefaultAssemblyName); AssemblyBuilder asmBuilder = AssemblyBuilder.DefineDynamicAssembly(name, DefaultAssemblyBuilderAccess); return TestLibrary.Utilities.GetModuleBuilder(asmBuilder, DefaultModuleName); } [Fact] public void TestWithValidData() { ModuleBuilder builder = GetModuleBuilder(); string fieldName = "PosTest1_"; int size = TestLibrary.Generator.GetByte(); if (size == 0) size++; FieldAttributes[] attributes = new FieldAttributes[] { FieldAttributes.Assembly, FieldAttributes.FamANDAssem, FieldAttributes.Family, FieldAttributes.FamORAssem, FieldAttributes.FieldAccessMask, FieldAttributes.HasDefault, FieldAttributes.HasFieldMarshal, FieldAttributes.HasFieldRVA, FieldAttributes.InitOnly, FieldAttributes.Literal, FieldAttributes.NotSerialized, FieldAttributes.PinvokeImpl, FieldAttributes.Private, FieldAttributes.PrivateScope, FieldAttributes.Public, FieldAttributes.RTSpecialName, FieldAttributes.SpecialName, FieldAttributes.Static }; for (int i = 0; i < attributes.Length; ++i) { FieldAttributes attribute = attributes[i]; string desiredFieldName = fieldName + i.ToString(); FieldBuilder fb = builder.DefineUninitializedData(desiredFieldName, size, attribute); int desiredAttribute = ((int)attribute | (int)FieldAttributes.Static) & ~ReservedMaskFieldAttribute; VerificationHelper(fb, desiredFieldName, (FieldAttributes)desiredAttribute); } } [Fact] public void TestWithBoundaryData() { ModuleBuilder builder = GetModuleBuilder(); string fieldName = "PosTest2_"; int[] sizeValues = new int[] { 1, 0x003f0000 - 1 }; FieldAttributes[] attributes = new FieldAttributes[] { FieldAttributes.Assembly, FieldAttributes.FamANDAssem, FieldAttributes.Family, FieldAttributes.FamORAssem, FieldAttributes.FieldAccessMask, FieldAttributes.HasDefault, FieldAttributes.HasFieldMarshal, FieldAttributes.HasFieldRVA, FieldAttributes.InitOnly, FieldAttributes.Literal, FieldAttributes.NotSerialized, FieldAttributes.PinvokeImpl, FieldAttributes.Private, FieldAttributes.PrivateScope, FieldAttributes.Public, FieldAttributes.RTSpecialName, FieldAttributes.SpecialName, FieldAttributes.Static }; for (int i = 0; i < sizeValues.Length; ++i) { for (int j = 0; j < attributes.Length; ++j) { FieldAttributes attribute = attributes[j]; string desiredFieldName = fieldName + i.ToString() + "_" + j.ToString(); FieldBuilder fb = builder.DefineUninitializedData(desiredFieldName, sizeValues[i], attribute); int desiredAttribute = ((int)attribute | (int)FieldAttributes.Static) & (~ReservedMaskFieldAttribute); VerificationHelper(fb, desiredFieldName, (FieldAttributes)desiredAttribute); } } } [Fact] public void TestThrowsExceptionWithZeroLengthName() { ModuleBuilder builder = GetModuleBuilder(); FieldAttributes[] attributes = new FieldAttributes[] { FieldAttributes.Assembly, FieldAttributes.FamANDAssem, FieldAttributes.Family, FieldAttributes.FamORAssem, FieldAttributes.FieldAccessMask, FieldAttributes.HasDefault, FieldAttributes.HasFieldMarshal, FieldAttributes.HasFieldRVA, FieldAttributes.InitOnly, FieldAttributes.Literal, FieldAttributes.NotSerialized, FieldAttributes.PinvokeImpl, FieldAttributes.Private, FieldAttributes.PrivateScope, FieldAttributes.Public, FieldAttributes.RTSpecialName, FieldAttributes.SpecialName, FieldAttributes.Static }; int size = TestLibrary.Generator.GetByte(); for (int i = 0; i < attributes.Length; ++i) { VerificationHelper(builder, "", size, attributes[i], typeof(ArgumentException)); } } [Fact] public void TestThrowsExceptionWithInvalidSizeData() { int[] sizeValues = new int[] { 0, -1, 0x003f0000, 0x003f0000 + 1 }; ModuleBuilder builder = GetModuleBuilder(); FieldAttributes[] attributes = new FieldAttributes[] { FieldAttributes.Assembly, FieldAttributes.FamANDAssem, FieldAttributes.Family, FieldAttributes.FamORAssem, FieldAttributes.FieldAccessMask, FieldAttributes.HasDefault, FieldAttributes.HasFieldMarshal, FieldAttributes.HasFieldRVA, FieldAttributes.InitOnly, FieldAttributes.Literal, FieldAttributes.NotSerialized, FieldAttributes.PinvokeImpl, FieldAttributes.Private, FieldAttributes.PrivateScope, FieldAttributes.Public, FieldAttributes.RTSpecialName, FieldAttributes.SpecialName, FieldAttributes.Static }; for (int i = 0; i < sizeValues.Length; ++i) { for (int j = 0; j < attributes.Length; ++j) { FieldAttributes attribute = attributes[j]; VerificationHelper(builder, "", sizeValues[i], attribute, typeof(ArgumentException)); } } } [Fact] public void TestThrowsExceptionWithNullName() { ModuleBuilder builder = GetModuleBuilder(); FieldAttributes[] attributes = new FieldAttributes[] { FieldAttributes.Assembly, FieldAttributes.FamANDAssem, FieldAttributes.Family, FieldAttributes.FamORAssem, FieldAttributes.FieldAccessMask, FieldAttributes.HasDefault, FieldAttributes.HasFieldMarshal, FieldAttributes.HasFieldRVA, FieldAttributes.InitOnly, FieldAttributes.Literal, FieldAttributes.NotSerialized, FieldAttributes.PinvokeImpl, FieldAttributes.Private, FieldAttributes.PrivateScope, FieldAttributes.Public, FieldAttributes.RTSpecialName, FieldAttributes.SpecialName, FieldAttributes.Static }; int size = TestLibrary.Generator.GetByte(); for (int i = 0; i < attributes.Length; ++i) { VerificationHelper(builder, null, size, attributes[i], typeof(ArgumentNullException)); } } [Fact] public void TestThrowsExceptionOnCreateGlobalFunctionCalledPreviously() { FieldAttributes[] attributes = new FieldAttributes[] { FieldAttributes.Assembly, FieldAttributes.FamANDAssem, FieldAttributes.Family, FieldAttributes.FamORAssem, FieldAttributes.FieldAccessMask, FieldAttributes.HasDefault, FieldAttributes.HasFieldMarshal, FieldAttributes.HasFieldRVA, FieldAttributes.InitOnly, FieldAttributes.Literal, FieldAttributes.NotSerialized, FieldAttributes.PinvokeImpl, FieldAttributes.Private, FieldAttributes.PrivateScope, FieldAttributes.Public, FieldAttributes.RTSpecialName, FieldAttributes.SpecialName, FieldAttributes.Static }; int size = TestLibrary.Generator.GetByte(); ModuleBuilder testModuleBuilder = GetModuleBuilder(); testModuleBuilder.CreateGlobalFunctions(); string fieldName = "NegTest4_"; for (int i = 0; i < attributes.Length; ++i) { VerificationHelper(testModuleBuilder, fieldName + i.ToString(), size, attributes[i], typeof(InvalidOperationException)); } } private void VerificationHelper(FieldBuilder fb, string desiredName, FieldAttributes desiredAttribute) { Assert.Equal(desiredName, fb.Name); Assert.Equal(desiredAttribute, fb.Attributes); } private void VerificationHelper(ModuleBuilder builder, string name, int size, FieldAttributes attribute, Type desiredException) { Assert.Throws(desiredException, () => { FieldBuilder fieldBuilder = builder.DefineUninitializedData(name, size, attribute); }); } } }
/* Copyright 2008 Uppsala University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.Collections.Generic; using System.Windows.Forms; using System.Threading; using System.IO; using System.Diagnostics; using Haggle; using Microsoft.Win32; using Microsoft.WindowsMobile; namespace PhotoShare { public class PhotoShare { public AddInterestWindow addInterestWindow = new AddInterestWindow(); public NeighborListWindow neighborListWindow = new NeighborListWindow(); MainWindow mainWindow; public delegate void PhotoListUpdateDelegate(Haggle.DataObject dObj); public delegate void NeighborListUpdateDelegate(Node.NodeList neighborList); public delegate long InterestListUpdateDelegate(Haggle.Attribute.AttributeList interestList); public delegate bool connectToHaggleDelegate(); HaggleEventHandler updatedNeighborHandler; HaggleEventHandler shutdownHandler; HaggleEventHandler newDataObjectHandler; HaggleEventHandler interestListHandler; public HaggleHandle hh; DateTime vibrationTime = DateTime.Now; Utility.Vibration vib = new Utility.Vibration(); // The data objects we display in the picture list public List<Haggle.DataObject> dataObjects = new List<Haggle.DataObject>(); public uint numDataObjects = 0; // Try to connect to Haggle daemon. If it is not running, ask user if we should try to // start it. public PhotoShare() { if (!connectToHaggle()) { Application.Exit(); return; } mainWindow = new MainWindow(this); hh.EventLoopRunAsync(); Application.Run(mainWindow); } public void shutdown() { hh.Shutdown(); hh.Free(); Application.Exit(); } public void quit() { hh.Free(); Debug.WriteLine("Calling Application.Exit()"); Application.Exit(); } public bool tryLaunchHaggle() { DialogResult res = MessageBox.Show("Haggle does not seem to be running. Start Haggle now?", "Haggle Error", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (res == DialogResult.Yes) { int ret = HaggleHandle.SpawnDaemon(); if (ret != 0) { MessageBox.Show("Could not launch Haggle daemon, error=" + ret); return false; } return true; // Give Haggle some time to launch //Thread.Sleep(4000); } return false; } private bool connectToHaggle() { bool try_again = true; while (try_again) { try_again = false; if (HaggleHandle.DaemonPid() == 0) { if (!tryLaunchHaggle()) { return false; } } try { hh = new HaggleHandle("PhotoShare"); interestListHandler = new HaggleEventHandler(hh, HaggleEvent.INTEREST_LIST, new HaggleCallback(this.onInterestList)); hh.RequestInterests(); updatedNeighborHandler = new HaggleEventHandler(hh, HaggleEvent.NEIGHBOR_UPDATE, new HaggleCallback(this.onNeighborUpdate)); shutdownHandler = new HaggleEventHandler(hh, HaggleEvent.SHUTDOWN, new HaggleCallback(this.onHaggleShutdown)); newDataObjectHandler = new HaggleEventHandler(hh, HaggleEvent.NEW_DATAOBJECT, new HaggleCallback(this.onNewDataObject)); Utility.Vibration vib = new Utility.Vibration(); Debug.WriteLine("PhotoShare successfully connected to Haggle\n"); return true; } catch (Haggle.HaggleHandle.IPCException ex) { if (ex.GetError() == HaggleHandle.HAGGLE_BUSY_ERROR) { // FIXME: Should really check if there is another photoshare application running... HaggleHandle.Unregister("PhotoShare"); Thread.Sleep(2000); try_again = true; } else { Debug.WriteLine("Haggle Error: " + ex.ToString() + " errnum=" + ex.GetError()); uint pid = HaggleHandle.DaemonPid(); if (pid > 0) { MessageBox.Show("A Haggle PID file exists, but could still not connect to Haggle"); } else if (pid == 0) { if (!tryLaunchHaggle()) { HaggleHandle.Unregister("PhotoShare"); return false; } } else { DialogResult res = MessageBox.Show("Could not connect to Haggle.", "Haggle Error", MessageBoxButtons.OK, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); return false; } } } catch (Haggle.HaggleEventHandler.EventHandlerException ex) { MessageBox.Show(ex.ToString() + " Error=" + ex.GetError()); throw ex; } } Application.Exit(); return false; } // This function will run in the thread called from libhaggle private void onNewDataObject(HaggleEvent he) { DataObjectEvent e = he as DataObjectEvent; Debug.WriteLine("New Data Object -- metadata:\n" + e.dObj.GetRaw()); try { // Verify that the attributes that PhotoShare expects exist e.dObj.GetAttribute("Picture"); if (e.dObj.GetFilePath().Length > 0) { dataObjects.Add(e.dObj); numDataObjects++; if ((DateTime.Now - vibrationTime).TotalSeconds > 5) { vib.vibrate(300, 100, 2); vibrationTime = DateTime.Now; } mainWindow.photoListView.BeginInvoke(new PhotoListUpdateDelegate(mainWindow.doPhotoListUpdate), e.dObj); } } catch (Haggle.DataObject.NoSuchAttributeException) { Debug.WriteLine("No Picture attribute in received data object"); } } public void onNeighborUpdate(HaggleEvent he) { NeighborEvent e = he as NeighborEvent; //Vibration.SoundFileInfo sfi = new Vibration.SoundFileInfo(); //sfi.sstType = Vibration.SoundType.Vibrate; Debug.WriteLine("Neighbor update event!"); //uint ret = Vibration.SndSetSound(Vibration.SoundEvent.All, sfi, true); Debug.WriteLine("neighbors received"); if ((DateTime.Now - vibrationTime).TotalSeconds > 5) { vib.vibrate(100, 50, 3); vibrationTime = DateTime.Now; } neighborListWindow.BeginInvoke(new NeighborListUpdateDelegate(neighborListWindow.doNeighborListUpdate), e.neighbors); } private void onHaggleShutdown(HaggleEvent e) { MessageBox.Show("Haggle daemon was shut down"); } private void onInterestList(HaggleEvent he) { InterestsEvent e = he as InterestsEvent; addInterestWindow.BeginInvoke(new InterestListUpdateDelegate(addInterestWindow.interestListUpdate), e.interests); } /// <summary> /// The main entry point for the application. /// </summary> [MTAThread] static void Main() { try { new PhotoShare(); } catch { } } } }
// 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.Tracing; using System.Globalization; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; namespace System.Net { //TODO: If localization resources are not found, logging does not work. Issue #5126. [EventSource(Name = "Microsoft-System-Net-Security", LocalizationResources = "FxResources.System.Net.Security.SR")] internal sealed partial class NetEventSource { private const int EnumerateSecurityPackagesId = NextAvailableEventId; private const int SspiPackageNotFoundId = EnumerateSecurityPackagesId + 1; private const int AcquireDefaultCredentialId = SspiPackageNotFoundId + 1; private const int AcquireCredentialsHandleId = AcquireDefaultCredentialId + 1; private const int SecureChannelCtorId = AcquireCredentialsHandleId + 1; private const int LocatingPrivateKeyId = SecureChannelCtorId + 1; private const int CertIsType2Id = LocatingPrivateKeyId + 1; private const int FoundCertInStoreId = CertIsType2Id + 1; private const int NotFoundCertInStoreId = FoundCertInStoreId + 1; private const int InitializeSecurityContextId = NotFoundCertInStoreId + 1; private const int SecurityContextInputBufferId = InitializeSecurityContextId + 1; private const int SecurityContextInputBuffersId = SecurityContextInputBufferId + 1; private const int AcceptSecuritContextId = SecurityContextInputBuffersId + 1; private const int OperationReturnedSomethingId = AcceptSecuritContextId + 1; private const int RemoteCertificateId = OperationReturnedSomethingId + 1; private const int CertificateFromDelegateId = RemoteCertificateId + 1; private const int NoDelegateNoClientCertId = CertificateFromDelegateId + 1; private const int NoDelegateButClientCertId = NoDelegateNoClientCertId + 1; private const int AttemptingRestartUsingCertId = NoDelegateButClientCertId + 1; private const int NoIssuersTryAllCertsId = AttemptingRestartUsingCertId + 1; private const int LookForMatchingCertsId = NoIssuersTryAllCertsId + 1; private const int SelectedCertId = LookForMatchingCertsId + 1; private const int CertsAfterFilteringId = SelectedCertId + 1; private const int FindingMatchingCertsId = CertsAfterFilteringId + 1; private const int UsingCachedCredentialId = FindingMatchingCertsId + 1; private const int SspiSelectedCipherSuitId = UsingCachedCredentialId + 1; private const int RemoteCertificateErrorId = SspiSelectedCipherSuitId + 1; private const int RemoteVertificateValidId = RemoteCertificateErrorId + 1; private const int RemoteCertificateSuccesId = RemoteVertificateValidId + 1; private const int RemoteCertificateInvalidId = RemoteCertificateSuccesId + 1; [Event(EnumerateSecurityPackagesId, Keywords = Keywords.Default, Level = EventLevel.Informational)] public void EnumerateSecurityPackages(string securityPackage) { if (IsEnabled()) { WriteEvent(EnumerateSecurityPackagesId, securityPackage ?? ""); } } [Event(SspiPackageNotFoundId, Keywords = Keywords.Default, Level = EventLevel.Informational)] public void SspiPackageNotFound(string packageName) { if (IsEnabled()) { WriteEvent(SspiPackageNotFoundId, packageName ?? ""); } } [NonEvent] public void SecureChannelCtor(SecureChannel secureChannel, string hostname, X509CertificateCollection clientCertificates, EncryptionPolicy encryptionPolicy) { if (IsEnabled()) { SecureChannelCtor(hostname, GetHashCode(secureChannel), clientCertificates?.Count ?? 0, encryptionPolicy); } } [Event(SecureChannelCtorId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private unsafe void SecureChannelCtor(string hostname, int secureChannelHash, int clientCertificatesCount, EncryptionPolicy encryptionPolicy) => WriteEvent(SecureChannelCtorId, hostname, secureChannelHash, clientCertificatesCount, (int)encryptionPolicy); [NonEvent] public void LocatingPrivateKey(X509Certificate x509Certificate, SecureChannel secureChannel) { if (IsEnabled()) { LocatingPrivateKey(x509Certificate.ToString(true), GetHashCode(secureChannel)); } } [Event(LocatingPrivateKeyId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void LocatingPrivateKey(string x509Certificate, int secureChannelHash) => WriteEvent(LocatingPrivateKeyId, x509Certificate, secureChannelHash); [NonEvent] public void CertIsType2(SecureChannel secureChannel) { if (IsEnabled()) { CertIsType2(GetHashCode(secureChannel)); } } [Event(CertIsType2Id, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void CertIsType2(int secureChannelHash) => WriteEvent(CertIsType2Id, secureChannelHash); [NonEvent] public void FoundCertInStore(bool serverMode, SecureChannel secureChannel) { if (IsEnabled()) { FoundCertInStore(serverMode ? "LocalMachine" : "CurrentUser", GetHashCode(secureChannel)); } } [Event(FoundCertInStoreId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void FoundCertInStore(string store, int secureChannelHash) => WriteEvent(FoundCertInStoreId, store, secureChannelHash); [NonEvent] public void NotFoundCertInStore(SecureChannel secureChannel) { if (IsEnabled()) { NotFoundCertInStore(GetHashCode(secureChannel)); } } [Event(NotFoundCertInStoreId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void NotFoundCertInStore(int secureChannelHash) => WriteEvent(NotFoundCertInStoreId, secureChannelHash); [NonEvent] public void RemoteCertificate(X509Certificate remoteCertificate) { if (IsEnabled()) { WriteEvent(RemoteCertificateId, remoteCertificate?.ToString(true)); } } [Event(RemoteCertificateId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void RemoteCertificate(string remoteCertificate) => WriteEvent(RemoteCertificateId, remoteCertificate); [NonEvent] public void CertificateFromDelegate(SecureChannel secureChannel) { if (IsEnabled()) { CertificateFromDelegate(GetHashCode(secureChannel)); } } [Event(CertificateFromDelegateId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void CertificateFromDelegate(int secureChannelHash) => WriteEvent(CertificateFromDelegateId, secureChannelHash); [NonEvent] public void NoDelegateNoClientCert(SecureChannel secureChannel) { if (IsEnabled()) { NoDelegateNoClientCert(GetHashCode(secureChannel)); } } [Event(NoDelegateNoClientCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void NoDelegateNoClientCert(int secureChannelHash) => WriteEvent(NoDelegateNoClientCertId, secureChannelHash); [NonEvent] public void NoDelegateButClientCert(SecureChannel secureChannel) { if (IsEnabled()) { NoDelegateButClientCert(GetHashCode(secureChannel)); } } [Event(NoDelegateButClientCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void NoDelegateButClientCert(int secureChannelHash) => WriteEvent(NoDelegateButClientCertId, secureChannelHash); [NonEvent] public void AttemptingRestartUsingCert(X509Certificate clientCertificate, SecureChannel secureChannel) { if (IsEnabled()) { AttemptingRestartUsingCert(clientCertificate?.ToString(true), GetHashCode(secureChannel)); } } [Event(AttemptingRestartUsingCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void AttemptingRestartUsingCert(string clientCertificate, int secureChannelHash) => WriteEvent(AttemptingRestartUsingCertId, clientCertificate, secureChannelHash); [NonEvent] public void NoIssuersTryAllCerts(SecureChannel secureChannel) { if (IsEnabled()) { NoIssuersTryAllCerts(GetHashCode(secureChannel)); } } [Event(NoIssuersTryAllCertsId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void NoIssuersTryAllCerts(int secureChannelHash) => WriteEvent(NoIssuersTryAllCertsId, secureChannelHash); [NonEvent] public void LookForMatchingCerts(int issuersCount, SecureChannel secureChannel) { if (IsEnabled()) { LookForMatchingCerts(issuersCount, GetHashCode(secureChannel)); } } [Event(LookForMatchingCertsId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void LookForMatchingCerts(int issuersCount, int secureChannelHash) => WriteEvent(LookForMatchingCertsId, issuersCount, secureChannelHash); [NonEvent] public void SelectedCert(X509Certificate clientCertificate, SecureChannel secureChannel) { if (IsEnabled()) { SelectedCert(clientCertificate?.ToString(true), GetHashCode(secureChannel)); } } [Event(SelectedCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void SelectedCert(string clientCertificate, int secureChannelHash) => WriteEvent(SelectedCertId, clientCertificate, secureChannelHash); [NonEvent] public void CertsAfterFiltering(int filteredCertsCount, SecureChannel secureChannel) { if (IsEnabled()) { CertsAfterFiltering(filteredCertsCount, GetHashCode(secureChannel)); } } [Event(CertsAfterFilteringId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void CertsAfterFiltering(int filteredCertsCount, int secureChannelHash) => WriteEvent(CertsAfterFilteringId, filteredCertsCount, secureChannelHash); [NonEvent] public void FindingMatchingCerts(SecureChannel secureChannel) { if (IsEnabled()) { FindingMatchingCerts(GetHashCode(secureChannel)); } } [Event(FindingMatchingCertsId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void FindingMatchingCerts(int secureChannelHash) => WriteEvent(FindingMatchingCertsId, secureChannelHash); [NonEvent] public void UsingCachedCredential(SecureChannel secureChannel) { if (IsEnabled()) { WriteEvent(UsingCachedCredentialId, GetHashCode(secureChannel)); } } [Event(UsingCachedCredentialId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void UsingCachedCredential(int secureChannelHash) => WriteEvent(UsingCachedCredentialId, secureChannelHash); [Event(SspiSelectedCipherSuitId, Keywords = Keywords.Default, Level = EventLevel.Informational)] public unsafe void SspiSelectedCipherSuite( string process, SslProtocols sslProtocol, CipherAlgorithmType cipherAlgorithm, int cipherStrength, HashAlgorithmType hashAlgorithm, int hashStrength, ExchangeAlgorithmType keyExchangeAlgorithm, int keyExchangeStrength) { if (IsEnabled()) { WriteEvent(SspiSelectedCipherSuitId, process, (int)sslProtocol, (int)cipherAlgorithm, cipherStrength, (int)hashAlgorithm, hashStrength, (int)keyExchangeAlgorithm, keyExchangeStrength); } } [NonEvent] public void RemoteCertificateError(SecureChannel secureChannel, string message) { if (IsEnabled()) { RemoteCertificateError(GetHashCode(secureChannel), message); } } [Event(RemoteCertificateErrorId, Keywords = Keywords.Default, Level = EventLevel.Verbose)] private void RemoteCertificateError(int secureChannelHash, string message) => WriteEvent(RemoteCertificateErrorId, secureChannelHash, message); [NonEvent] public void RemoteCertDeclaredValid(SecureChannel secureChannel) { if (IsEnabled()) { RemoteCertDeclaredValid(GetHashCode(secureChannel)); } } [Event(RemoteVertificateValidId, Keywords = Keywords.Default, Level = EventLevel.Verbose)] private void RemoteCertDeclaredValid(int secureChannelHash) => WriteEvent(RemoteVertificateValidId, secureChannelHash); [NonEvent] public void RemoteCertHasNoErrors(SecureChannel secureChannel) { if (IsEnabled()) { RemoteCertHasNoErrors(GetHashCode(secureChannel)); } } [Event(RemoteCertificateSuccesId, Keywords = Keywords.Default, Level = EventLevel.Verbose)] private void RemoteCertHasNoErrors(int secureChannelHash) => WriteEvent(RemoteCertificateSuccesId, secureChannelHash); [NonEvent] public void RemoteCertUserDeclaredInvalid(SecureChannel secureChannel) { if (IsEnabled()) { RemoteCertUserDeclaredInvalid(GetHashCode(secureChannel)); } } [Event(RemoteCertificateInvalidId, Keywords = Keywords.Default, Level = EventLevel.Verbose)] private void RemoteCertUserDeclaredInvalid(int secureChannelHash) => WriteEvent(RemoteCertificateInvalidId, secureChannelHash); static partial void AdditionalCustomizedToString<T>(T value, ref string result) { X509Certificate cert = value as X509Certificate; if (cert != null) { result = cert.ToString(fVerbose: true); } } } }
// // ScanSegmentTree.cs // MSAGL class for visibility scan segment tree for Rectilinear Edge Routing. // // Copyright Microsoft Corporation. using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; namespace Microsoft.Msagl.Routing.Rectilinear { using DebugHelpers; internal class ScanSegmentTree : IComparer<ScanSegment> { internal ScanDirection ScanDirection { get; private set; } private readonly RbTree<ScanSegment> segmentTree; // Temporary variables for lookup. private readonly ScanSegment lookupSegment = new ScanSegment(new Point(0, 0), new Point(0, 1)); // dummy values avoid AF; will be overwritten readonly Func<ScanSegment, bool> findIntersectorPred; readonly Func<ScanSegment, bool> findPointPred; internal ScanSegmentTree(ScanDirection scanDir) { ScanDirection = scanDir; this.segmentTree = new RbTree<ScanSegment>(this); this.findIntersectorPred = new Func<ScanSegment, bool>(this.CompareIntersector); this.findPointPred = new Func<ScanSegment, bool>(this.CompareToPoint); } internal IEnumerable<ScanSegment> Segments { get { return this.segmentTree; } } // If the seg is already in the tree it returns that instance, else it inserts the new // seg and returns that. internal RBNode<ScanSegment> InsertUnique(ScanSegment seg) { // RBTree's internal operations on insert/remove etc. mean the node can't cache the // RBNode returned by insert(); instead we must do find() on each call. But we can // use the returned node to get predecessor/successor. AssertValidSegmentForInsertion(seg); var node = this.segmentTree.Find(seg); if (null != node) { Debug.Assert(seg.IsOverlapped == node.Item.IsOverlapped, "Existing node found with different isOverlapped"); return node; } return this.segmentTree.Insert(seg); } [Conditional("DEBUG")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] void AssertValidSegmentForInsertion(ScanSegment seg) { Debug.Assert((seg.End.X >= seg.Start.X) && (seg.End.Y >= seg.Start.Y), "Reversed direction in ScanSegment"); Debug.Assert(ScanDirection.IsFlat(seg.Start, seg.End), "non-flat segment cannot be inserted"); } internal void Remove(ScanSegment seg) { Debug.Assert(seg.IsVertical == ScanDirection.IsVertical, "seg.IsVertical != ScanDirection.IsVertical"); this.segmentTree.Remove(seg); } internal ScanSegment Find(Point start, Point end) { Debug.Assert(PointComparer.Equal(start, end) || !ScanDirection.IsPerpendicular(start, end) , "perpendicular segment passed"); this.lookupSegment.Update(start, end); RBNode<ScanSegment> node = this.segmentTree.Find(this.lookupSegment); if ((null != node) && PointComparer.Equal(node.Item.End, end)) { return node.Item; } return null; } // Find the lowest perpendicular scanseg that intersects the segment endpoints. internal ScanSegment FindLowestIntersector(Point start, Point end) { var node = FindLowestIntersectorNode(start, end); return (null != node) ? node.Item : null; } internal RBNode<ScanSegment> FindLowestIntersectorNode(Point start, Point end) { Debug.Assert(ScanDirection.IsPerpendicular(start, end), "non-perpendicular segment passed"); // Find the last segment that starts at or before 'start'. this.lookupSegment.Update(start, start); RBNode<ScanSegment> node = this.segmentTree.FindLast(this.findIntersectorPred); // We have a segment that intersects start/end, or one that ends before 'start' and thus we // must iterate to find the lowest bisector. TODOperf: see how much that iteration costs us // (here and Highest); consider a BSP tree or interval tree (maybe 2-d RBTree for updatability). if (PointComparer.Equal(start, end)) { if ((null != node) && (ScanDirection.Compare(node.Item.End, start) < 0)) { node = null; } } else { this.lookupSegment.Update(start, end); while ((null != node) && !node.Item.IntersectsSegment(this.lookupSegment)) { // If the node segment starts after 'end', no intersection was found. if (ScanDirection.Compare(node.Item.Start, end) > 0) { return null; } node = this.segmentTree.Next(node); } } return node; } // Find the highest perpendicular scanseg that intersects the segment endpoints. internal ScanSegment FindHighestIntersector(Point start, Point end) { Debug.Assert(ScanDirection.IsPerpendicular(start, end), "non-perpendicular segment passed"); // Find the last segment that starts at or before 'end'. this.lookupSegment.Update(end, end); RBNode<ScanSegment> node = this.segmentTree.FindLast(this.findIntersectorPred); // Now we either have a segment that intersects start/end, or one that ends before // 'end' and need to iterate to find the highest bisector. if (PointComparer.Equal(start, end)) { if ((null != node) && (ScanDirection.Compare(node.Item.End, start) < 0)) { node = null; } } else { this.lookupSegment.Update(start, end); while ((null != node) && !node.Item.IntersectsSegment(this.lookupSegment)) { // If the node segment ends before 'start', no intersection was found. if (ScanDirection.Compare(node.Item.End, start) < 0) { return null; } node = this.segmentTree.Previous(node); } } return (null != node) ? node.Item : null; } bool CompareIntersector(ScanSegment seg) { // We're looking for the last segment that starts before LookupSegment.Start. return (ScanDirection.Compare(seg.Start, this.lookupSegment.Start) <= 0); } internal ScanSegment FindSegmentContainingPoint(Point location, bool allowUnfound) { return FindSegmentOverlappingPoints(location, location, allowUnfound); } internal ScanSegment FindSegmentOverlappingPoints(Point start, Point end, bool allowUnfound) { this.lookupSegment.Update(start, end); RBNode<ScanSegment> node = this.segmentTree.FindFirst(this.findPointPred); // If we had any segments in the tree that end after 'start', node has the first one. // Now we need to that it starts before 'end'. ScanSegment.CompareToPointPositionFullLength // asserts the point is on the segment which we don't want to require here, so // compare the endpoints directly. if (null != node) { ScanSegment seg = node.Item; if (ScanDirection.Compare(seg.Start, end) <= 0) { return seg; } } // Not found. if (!allowUnfound) { Debug.Assert(false, "Could not find expected segment"); } return null; } bool CompareToPoint(ScanSegment treeSeg) { // Test if treeSeg overlaps the LookupSegment.Start point. We're using FindFirst, // so we'll just return false for everything that ends before the point and true for anything // that ends at or after it, then the caller will verify overlap. return (ScanDirection.Compare(treeSeg.End, this.lookupSegment.Start) >= 0); } RBNode<ScanSegment> MergeAndRemoveNextNode(ScanSegment currentSegment, RBNode<ScanSegment> nextSegNode) { // Merge at the ends only - if we're here, start will be the same or greater. if (-1 == ScanDirection.Compare(currentSegment.End, nextSegNode.Item.End)) { currentSegment.Update(currentSegment.Start, nextSegNode.Item.End); } // Removing the node can revise the tree's RBNodes internally so re-get the current segment. currentSegment.MergeGroupBoundaryCrossingList(nextSegNode.Item.GroupBoundaryPointAndCrossingsList); this.segmentTree.DeleteNodeInternal(nextSegNode); return this.segmentTree.Find(currentSegment); } internal void MergeSegments() { // As described in the doc, hintScanSegment handles all the non-overlapped non-reflection cases. DevTraceInfo(1, "{0} ScanSegmentTree MergeSegments, count = {1}" , ScanDirection.IsHorizontal ? "Horizontal" : "Vertical", this.segmentTree.Count); if (this.segmentTree.Count < 2) { return; } RBNode<ScanSegment> currentSegNode = this.segmentTree.TreeMinimum(); RBNode<ScanSegment> nextSegNode = this.segmentTree.Next(currentSegNode); for ( ; null != nextSegNode; nextSegNode = this.segmentTree.Next(currentSegNode)) { DevTraceInfo(2, "Current {0} Next {1}", currentSegNode.Item, nextSegNode.Item); int cmp = ScanDirection.Compare(nextSegNode.Item.Start, currentSegNode.Item.End); switch (cmp) { case 1: // Next segment starts after the current one. currentSegNode = nextSegNode; break; case 0: if (nextSegNode.Item.IsOverlapped == currentSegNode.Item.IsOverlapped) { // Overlapping is the same, so merge. Because the ordering in the tree is that // same-Start nodes are ordered by longest-End first, this will retain the tree ordering. DevTraceInfo(2, " (merged; start-at-end with same overlap)"); currentSegNode = MergeAndRemoveNextNode(currentSegNode.Item, nextSegNode); } else { // Touching start/end with differing IsOverlapped so they need a connecting vertex. DevTraceInfo(2, " (marked with NeedFinalOverlapVertex)"); currentSegNode.Item.NeedEndOverlapVertex = true; nextSegNode.Item.NeedStartOverlapVertex = true; currentSegNode = nextSegNode; } break; default: // -1 == cmp // nextSegNode.Item.Start is before currentSegNode.Item.End. Debug.Assert((nextSegNode.Item.Start != currentSegNode.Item.Start) || (nextSegNode.Item.End < currentSegNode.Item.End) , "Identical segments are not allowed, and longer ones must come first"); // Because longer segments are ordered before shorter ones at the same start position, // nextSegNode.Item must be a duplicate segment or is partially or totally overlapped. // In the case of reflection lookahead segments, the side-intersection calculated from // horizontal vs. vertical directions may be slightly different along the parallel // coordinate from an overlapped segment, so let non-overlapped win that disagreement. if (currentSegNode.Item.IsOverlapped != nextSegNode.Item.IsOverlapped) { Debug.Assert(ApproximateComparer.CloseIntersections(currentSegNode.Item.End, nextSegNode.Item.Start) , "Segments share a span with different IsOverlapped"); if (currentSegNode.Item.IsOverlapped) { // If the Starts are different, then currentSegNode is the only item at its // start, so we don't need to re-insert. Otherwise, we need to remove it and // re-find nextSegNode's side. if (currentSegNode.Item.Start == nextSegNode.Item.Start) { // currentSegNode is a tiny overlapped segment between two non-overlapped segments (so // we'll have another merge later, when we hit the other non-overlapped segment). // Notice reversed params. TestNote: No longer have repro with the change to convex hulls; // this may no longer happen since overlapped edges will now always be inside rectangular // obstacles so there are no angled-side calculations. currentSegNode = MergeAndRemoveNextNode(nextSegNode.Item, currentSegNode); DevTraceInfo(2, " (identical starts so discarding isOverlapped currentSegNode)"); } else { currentSegNode.Item.Update(currentSegNode.Item.Start, nextSegNode.Item.Start); DevTraceInfo(2, " (trimming isOverlapped currentSegNode to {0})", currentSegNode.Item); currentSegNode = nextSegNode; } } else { if (currentSegNode.Item.End == nextSegNode.Item.End) { // nextSegNode is a tiny non-overlapped segment between two overlapped segments (so // we'll have another merge later, when we hit the other non-overlapped segment). // TestNote: No longer have repro with the change to convex hulls; // this may no longer happen since overlapped edges will now always be inside rectangular // obstacles so there are no angled-side calculations. currentSegNode = MergeAndRemoveNextNode(currentSegNode.Item, nextSegNode); DevTraceInfo(2, " (identical ends so discarding isOverlapped currentSegNode)"); } else { // Remove nextSegNode, increment its start to be after currentSegment, re-insert nextSegNode, and // re-find currentSegNode (there may be more segments between nextSegment.Start and currentSegment.End). ScanSegment nextSegment = nextSegNode.Item; ScanSegment currentSegment = currentSegNode.Item; this.segmentTree.DeleteNodeInternal(nextSegNode); nextSegment.Update(currentSegment.End, nextSegment.End); this.segmentTree.Insert(nextSegment); nextSegment.TrimGroupBoundaryCrossingList(); DevTraceInfo(2, " (trimming isOverlapped nextSegNode to {0})", nextSegment); currentSegNode = this.segmentTree.Find(currentSegment); } } break; } // Overlaps match so do a normal merge operation. DevTraceInfo(2, " (merged; start-before-end)"); currentSegNode = MergeAndRemoveNextNode(currentSegNode.Item, nextSegNode); break; } // endswitch } // endfor #if DEVTRACE DevTraceInfo(1, "{0} ScanSegmentTree after MergeSegments, count = {1}" , ScanDirection.IsHorizontal ? "Horizontal" : "Vertical", this.segmentTree.Count); if (this.scanSegmentVerify.IsLevel(1)) { DevTraceInfo(1, "{0} ScanSegmentTree Consistency Check" , ScanDirection.IsHorizontal ? "Horizontal" : "Vertical"); bool retval = true; RBNode<ScanSegment> prevSegNode = this.segmentTree.TreeMinimum(); currentSegNode = this.segmentTree.Next(prevSegNode); while (null != currentSegNode) { DevTraceInfo(4, currentSegNode.Item.ToString()); // We should only have end-to-end touching, and that only if differing IsOverlapped. if ( (-1 != Compare(prevSegNode.Item, currentSegNode.Item)) || (1 != ScanDirection.Compare(currentSegNode.Item.Start, prevSegNode.Item.Start) || ((0 == ScanDirection.Compare(currentSegNode.Item.Start, prevSegNode.Item.End)) && (currentSegNode.Item.IsOverlapped == prevSegNode.Item.IsOverlapped)))) { this.scanSegmentTrace.WriteError(0, "Segments are not strictly increasing:"); this.scanSegmentTrace.WriteFollowup(0, prevSegNode.Item.ToString()); this.scanSegmentTrace.WriteFollowup(0, currentSegNode.Item.ToString()); retval = false; } prevSegNode = currentSegNode; currentSegNode = this.segmentTree.Next(currentSegNode); } Debug.Assert(retval, "ScanSegments are not strictly increasing"); } #endif // DEVTRACE } #region IComparer<ScanSegment> /// <summary> /// For ordering the line segments inserted by the ScanLine. Assuming vertical sweep (sweeping up from /// bottom, scanning horizontally) then order ScanSegments first by lowest Y coord, then by lowest X coord. /// </summary> /// <param name="first"></param> /// <param name="second"></param> /// <returns></returns> public int Compare(ScanSegment first, ScanSegment second) { if (first == second) return 0; if (first == null) return -1; if (second == null) return 1; // This orders on both axes. int cmp = ScanDirection.Compare(first.Start, second.Start); if (0 == cmp) { // Longer segments come first, to make overlap removal easier. cmp = -ScanDirection.Compare(first.End, second.End); } return cmp; } #endregion // IComparer<ScanSegment> #region DevTrace #if DEVTRACE readonly DevTrace scanSegmentTrace = new DevTrace("Rectilinear_ScanSegmentTrace", "ScanSegments"); readonly DevTrace scanSegmentVerify = new DevTrace("Rectilinear_ScanSegmentVerify"); #endif // DEVTRACE [Conditional("DEVTRACE")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] void DevTraceInfo(int verboseLevel, string format, params object[] args) { #if DEVTRACE this.scanSegmentTrace.WriteLineIf(DevTrace.Level.Info, verboseLevel, format, args); #endif // DEVTRACE } [Conditional("DEVTRACE")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] internal void DevTraceVerifyVisibility() { #if DEVTRACE if (this.scanSegmentVerify.IsLevel(1)) { DevTraceInfo(1, "Beginning {0} ScanSegmentTree VisibilityVertex Check..." , ScanDirection.IsHorizontal ? "Horizontal" : "Vertical"); bool retval = true; for (RBNode<ScanSegment> segNode = this.segmentTree.TreeMinimum(); null != segNode; segNode = this.segmentTree.Next(segNode)) { if (null == segNode.Item.LowestVisibilityVertex) { this.scanSegmentTrace.WriteError(0, "Segment has no VisibilityVertex: {0}", segNode.Item.ToString()); retval = false; } } DevTraceInfo(1, "{0} ScanSegmentTree VisibilityVertex Check complete: status {1}" , ScanDirection.IsHorizontal ? "Horizontal" : "Vertical", retval ? "pass" : "fail"); Debug.Assert(retval, "One or more ScanSegments do not have a VisibilityVertex"); } #endif // DEVTRACE } #endregion // DevTrace } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Windows; using System.Windows.Controls; using Microsoft.Practices.Prism.Events; using Microsoft.Practices.Prism.Logging; using Microsoft.Practices.Prism.Modularity; using Microsoft.Practices.Prism.Regions; using Microsoft.Practices.Prism.UnityExtensions; using Microsoft.Practices.ServiceLocation; using Microsoft.Practices.Unity; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System.Collections.Generic; using Microsoft.Practices.Prism.PubSubEvents; namespace Microsoft.Practices.Prism.UnityExtensions.Tests { [TestClass] public class UnityBootstrapperRunMethodFixture { [TestMethod] public void CanRunBootstrapper() { var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); } [TestMethod] public void RunShouldNotFailIfReturnedNullShell() { var bootstrapper = new DefaultUnityBootstrapper { ShellObject = null }; bootstrapper.Run(); } [TestMethod] public void RunConfiguresServiceLocatorProvider() { var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); Assert.IsTrue(ServiceLocation.ServiceLocator.Current is UnityServiceLocatorAdapter); } [TestMethod] public void RunShouldInitializeContainer() { var bootstrapper = new DefaultUnityBootstrapper(); var container = bootstrapper.BaseContainer; Assert.IsNull(container); bootstrapper.Run(); container = bootstrapper.BaseContainer; Assert.IsNotNull(container); Assert.IsInstanceOfType(container, typeof(UnityContainer)); } [TestMethod] public void RunAddsCompositionContainerToContainer() { var bootstrapper = new DefaultUnityBootstrapper(); var createdContainer = bootstrapper.CallCreateContainer(); var returnedContainer = createdContainer.Resolve<IUnityContainer>(); Assert.IsNotNull(returnedContainer); Assert.AreEqual(typeof(UnityContainer), returnedContainer.GetType()); } [TestMethod] public void RunShouldCallInitializeModules() { var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.InitializeModulesCalled); } [TestMethod] public void RunShouldCallConfigureDefaultRegionBehaviors() { var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.ConfigureDefaultRegionBehaviorsCalled); } [TestMethod] public void RunShouldCallConfigureRegionAdapterMappings() { var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.ConfigureRegionAdapterMappingsCalled); } [TestMethod] public void RunShouldAssignRegionManagerToReturnedShell() { var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); Assert.IsNotNull(RegionManager.GetRegionManager(bootstrapper.BaseShell)); } [TestMethod] public void RunShouldCallCreateLogger() { var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.CreateLoggerCalled); } [TestMethod] public void RunShouldCallCreateModuleCatalog() { var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.CreateModuleCatalogCalled); } [TestMethod] public void RunShouldCallConfigureModuleCatalog() { var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.ConfigureModuleCatalogCalled); } [TestMethod] public void RunShouldCallCreateContainer() { var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.CreateContainerCalled); } [TestMethod] public void RunShouldCallCreateShell() { var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.CreateShellCalled); } [TestMethod] public void RunShouldCallConfigureContainer() { var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.ConfigureContainerCalled); } [TestMethod] public void RunRegistersInstanceOfILoggerFacade() { var mockedContainer = new Mock<IUnityContainer>(); SetupMockedContainerForVerificationTests(mockedContainer); var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object); bootstrapper.Run(); mockedContainer.Verify(c => c.RegisterInstance(typeof(ILoggerFacade), null, bootstrapper.BaseLogger, It.IsAny<LifetimeManager>()), Times.Once()); } [TestMethod] public void RunRegistersInstanceOfIModuleCatalog() { var mockedContainer = new Mock<IUnityContainer>(); SetupMockedContainerForVerificationTests(mockedContainer); var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object); bootstrapper.Run(); mockedContainer.Verify(c => c.RegisterInstance(typeof(IModuleCatalog), null, It.IsAny<object>(), It.IsAny<LifetimeManager>()), Times.Once()); } [TestMethod] public void RunRegistersTypeForIServiceLocator() { var mockedContainer = new Mock<IUnityContainer>(); SetupMockedContainerForVerificationTests(mockedContainer); var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object); bootstrapper.Run(); mockedContainer.Verify(c => c.RegisterType(typeof(IServiceLocator), typeof(UnityServiceLocatorAdapter), null, It.IsAny<LifetimeManager>()), Times.Once()); } [TestMethod] public void RunRegistersTypeForIModuleInitializer() { var mockedContainer = new Mock<IUnityContainer>(); SetupMockedContainerForVerificationTests(mockedContainer); var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object); bootstrapper.Run(); mockedContainer.Verify(c => c.RegisterType(typeof(IModuleInitializer), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Once()); } [TestMethod] public void RunRegistersTypeForIRegionManager() { var mockedContainer = new Mock<IUnityContainer>(); SetupMockedContainerForVerificationTests(mockedContainer); var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object); bootstrapper.Run(); mockedContainer.Verify(c => c.RegisterType(typeof(IRegionManager), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Once()); } [TestMethod] public void RunRegistersTypeForRegionAdapterMappings() { var mockedContainer = new Mock<IUnityContainer>(); SetupMockedContainerForVerificationTests(mockedContainer); var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object); bootstrapper.Run(); mockedContainer.Verify(c => c.RegisterType(typeof(RegionAdapterMappings), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Once()); } [TestMethod] public void RunRegistersTypeForIRegionViewRegistry() { var mockedContainer = new Mock<IUnityContainer>(); SetupMockedContainerForVerificationTests(mockedContainer); var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object); bootstrapper.Run(); mockedContainer.Verify(c => c.RegisterType(typeof(IRegionViewRegistry), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Once()); } [TestMethod] public void RunRegistersTypeForIRegionBehaviorFactory() { var mockedContainer = new Mock<IUnityContainer>(); SetupMockedContainerForVerificationTests(mockedContainer); var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object); bootstrapper.Run(); mockedContainer.Verify(c => c.RegisterType(typeof(IRegionBehaviorFactory), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Once()); } [TestMethod] public void RunRegistersTypeForIEventAggregator() { var mockedContainer = new Mock<IUnityContainer>(); SetupMockedContainerForVerificationTests(mockedContainer); var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object); bootstrapper.Run(); mockedContainer.Verify(c => c.RegisterType(typeof(IEventAggregator), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Once()); } [TestMethod] public void RunFalseShouldNotRegisterDefaultServicesAndTypes() { var mockedContainer = new Mock<IUnityContainer>(); SetupMockedContainerForVerificationTests(mockedContainer); var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object); bootstrapper.Run(false); mockedContainer.Verify(c => c.RegisterType(typeof(IEventAggregator), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Never()); mockedContainer.Verify(c => c.RegisterType(typeof(IRegionManager), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Never()); mockedContainer.Verify(c => c.RegisterType(typeof(RegionAdapterMappings), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Never()); mockedContainer.Verify(c => c.RegisterType(typeof(IServiceLocator), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Never()); mockedContainer.Verify(c => c.RegisterType(typeof(IModuleInitializer), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Never()); } [TestMethod] public void ModuleManagerRunCalled() { // Have to use a non-mocked container because of IsRegistered<> extension method, Registrations property,and ContainerRegistration var container = new UnityContainer(); var mockedModuleInitializer = new Mock<IModuleInitializer>(); var mockedModuleManager = new Mock<IModuleManager>(); var regionAdapterMappings = new RegionAdapterMappings(); var serviceLocatorAdapter = new UnityServiceLocatorAdapter(container); var regionBehaviorFactory = new RegionBehaviorFactory(serviceLocatorAdapter); container.RegisterInstance<IServiceLocator>(serviceLocatorAdapter); container.RegisterInstance<UnityBootstrapperExtension>(new UnityBootstrapperExtension()); container.RegisterInstance<IModuleCatalog>(new ModuleCatalog()); container.RegisterInstance<IModuleInitializer>(mockedModuleInitializer.Object); container.RegisterInstance<IModuleManager>(mockedModuleManager.Object); container.RegisterInstance<RegionAdapterMappings>(regionAdapterMappings); container.RegisterInstance<SelectorRegionAdapter>(new SelectorRegionAdapter(regionBehaviorFactory)); container.RegisterInstance<ItemsControlRegionAdapter>(new ItemsControlRegionAdapter(regionBehaviorFactory)); container.RegisterInstance<ContentControlRegionAdapter>(new ContentControlRegionAdapter(regionBehaviorFactory)); var bootstrapper = new MockedContainerBootstrapper(container); bootstrapper.Run(); mockedModuleManager.Verify(mm => mm.Run(), Times.Once()); } [TestMethod] public void RunShouldCallTheMethodsInOrder() { var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); Assert.AreEqual("CreateLogger", bootstrapper.MethodCalls[0]); Assert.AreEqual("CreateModuleCatalog", bootstrapper.MethodCalls[1]); Assert.AreEqual("ConfigureModuleCatalog", bootstrapper.MethodCalls[2]); Assert.AreEqual("CreateContainer", bootstrapper.MethodCalls[3]); Assert.AreEqual("ConfigureContainer", bootstrapper.MethodCalls[4]); Assert.AreEqual("ConfigureServiceLocator", bootstrapper.MethodCalls[5]); Assert.AreEqual("ConfigureRegionAdapterMappings", bootstrapper.MethodCalls[6]); Assert.AreEqual("ConfigureDefaultRegionBehaviors", bootstrapper.MethodCalls[7]); Assert.AreEqual("RegisterFrameworkExceptionTypes", bootstrapper.MethodCalls[8]); Assert.AreEqual("CreateShell", bootstrapper.MethodCalls[9]); Assert.AreEqual("InitializeShell", bootstrapper.MethodCalls[10]); Assert.AreEqual("InitializeModules", bootstrapper.MethodCalls[11]); } [TestMethod] public void RunShouldLogBootstrapperSteps() { var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages[0].Contains("Logger was created successfully.")); Assert.IsTrue(messages[1].Contains("Creating module catalog.")); Assert.IsTrue(messages[2].Contains("Configuring module catalog.")); Assert.IsTrue(messages[3].Contains("Creating Unity container.")); Assert.IsTrue(messages[4].Contains("Configuring the Unity container.")); Assert.IsTrue(messages[5].Contains("Adding UnityBootstrapperExtension to container.")); Assert.IsTrue(messages[6].Contains("Configuring ServiceLocator singleton.")); Assert.IsTrue(messages[7].Contains("Configuring region adapters.")); Assert.IsTrue(messages[8].Contains("Configuring default region behaviors.")); Assert.IsTrue(messages[9].Contains("Registering Framework Exception Types.")); Assert.IsTrue(messages[10].Contains("Creating the shell.")); Assert.IsTrue(messages[11].Contains("Setting the RegionManager.")); Assert.IsTrue(messages[12].Contains("Updating Regions.")); Assert.IsTrue(messages[13].Contains("Initializing the shell.")); Assert.IsTrue(messages[14].Contains("Initializing modules.")); Assert.IsTrue(messages[15].Contains("Bootstrapper sequence completed.")); } [TestMethod] public void RunShouldLogLoggerCreationSuccess() { const string expectedMessageText = "Logger was created successfully."; var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutModuleCatalogCreation() { const string expectedMessageText = "Creating module catalog."; var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutConfiguringModuleCatalog() { const string expectedMessageText = "Configuring module catalog."; var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutCreatingTheContainer() { const string expectedMessageText = "Creating Unity container."; var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutConfiguringContainer() { const string expectedMessageText = "Configuring the Unity container."; var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutConfiguringRegionAdapters() { const string expectedMessageText = "Configuring region adapters."; var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutConfiguringRegionBehaviors() { const string expectedMessageText = "Configuring default region behaviors."; var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutRegisteringFrameworkExceptionTypes() { const string expectedMessageText = "Registering Framework Exception Types."; var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutCreatingTheShell() { const string expectedMessageText = "Creating the shell."; var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutInitializingTheShellIfShellCreated() { const string expectedMessageText = "Initializing the shell."; var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldNotLogAboutInitializingTheShellIfShellIsNotCreated() { const string expectedMessageText = "Initializing shell"; var bootstrapper = new DefaultUnityBootstrapper { ShellObject = null }; bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsFalse(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutInitializingModules() { const string expectedMessageText = "Initializing modules."; var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutRunCompleting() { const string expectedMessageText = "Bootstrapper sequence completed."; var bootstrapper = new DefaultUnityBootstrapper(); bootstrapper.Run(); var messages = bootstrapper.BaseLogger.Messages; Assert.IsTrue(messages.Contains(expectedMessageText)); } private static void SetupMockedContainerForVerificationTests(Mock<IUnityContainer> mockedContainer) { var mockedModuleInitializer = new Mock<IModuleInitializer>(); var mockedModuleManager = new Mock<IModuleManager>(); var regionAdapterMappings = new RegionAdapterMappings(); var serviceLocatorAdapter = new UnityServiceLocatorAdapter(mockedContainer.Object); var regionBehaviorFactory = new RegionBehaviorFactory(serviceLocatorAdapter); mockedContainer.Setup(c => c.Resolve(typeof(IServiceLocator), (string)null)).Returns(serviceLocatorAdapter); mockedContainer.Setup(c => c.RegisterInstance(It.IsAny<Type>(), It.IsAny<string>(), It.IsAny<object>(), It.IsAny<LifetimeManager>())); mockedContainer.Setup(c => c.Resolve(typeof(UnityBootstrapperExtension), (string)null)).Returns( new UnityBootstrapperExtension()); mockedContainer.Setup(c => c.Resolve(typeof(IModuleCatalog), (string)null)).Returns( new ModuleCatalog()); mockedContainer.Setup(c => c.Resolve(typeof(IModuleInitializer), (string)null)).Returns( mockedModuleInitializer.Object); mockedContainer.Setup(c => c.Resolve(typeof(IModuleManager), (string)null)).Returns( mockedModuleManager.Object); mockedContainer.Setup(c => c.Resolve(typeof(RegionAdapterMappings), (string)null)).Returns( regionAdapterMappings); mockedContainer.Setup(c => c.Resolve(typeof(SelectorRegionAdapter), (string)null)).Returns( new SelectorRegionAdapter(regionBehaviorFactory)); mockedContainer.Setup(c => c.Resolve(typeof(ItemsControlRegionAdapter), (string)null)).Returns( new ItemsControlRegionAdapter(regionBehaviorFactory)); mockedContainer.Setup(c => c.Resolve(typeof(ContentControlRegionAdapter), (string)null)).Returns( new ContentControlRegionAdapter(regionBehaviorFactory)); } private class MockedContainerBootstrapper : UnityBootstrapper { private readonly IUnityContainer container; public ILoggerFacade BaseLogger { get { return base.Logger; } } public void CallConfigureContainer() { base.ConfigureContainer(); } public MockedContainerBootstrapper(IUnityContainer container) { this.container = container; } protected override IUnityContainer CreateContainer() { return container; } protected override DependencyObject CreateShell() { return new UserControl(); } protected override void InitializeShell() { // no op } } } }
/* Copyright (c) 2004-2009 Krzysztof Ostrowski. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED "AS IS" BY THE ABOVE COPYRIGHT HOLDER(S) AND ALL OTHER CONTRIBUTORS 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 ABOVE COPYRIGHT HOLDER(S) OR ANY OTHER 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. */ // #define Using_VS2005Beta1 #define DEBUG_CheckAddressesOnDeserialization using System; using System.Net; namespace QS.Fx.Network { /// <summary> /// This class represents a full IPv4 network address including an IP address and a port number. /// </summary> [Serializable] [QS.Fx.Serialization.ClassID(QS.ClassID.NetworkAddress)] public sealed class NetworkAddress : System.IComparable, System.IComparable<QS.Fx.Network.NetworkAddress>, QS.Fx.Serialization.ISerializable, QS.Fx.Serialization.IStringSerializable /* , QS.CMS.Base.IBase1Serializable, QS.CMS.Base2.IMessage, QS.CMS.Scattering.IScatterAddress, QS.CMS.Base2.IBase2Serializable */ { #region Helpers /// <summary> /// Tests whether the given IP address is a multicast address. /// </summary> /// <param name="addr">The address to test.</param> /// <returns>True if the address is a multicast address.</returns> public static bool IsMulticastIPAddress(IPAddress addr) { byte firstByte = (addr.GetAddressBytes())[0]; return firstByte >= 224 && firstByte <= 239; } /// <summary> /// True if this address is a multicast address. /// </summary> public bool IsMulticastAddress { get { return IsMulticastIPAddress(this.HostIPAddress); } } #endregion #region Constants /// <summary> /// Represents an uninitialized network address. /// </summary> public static NetworkAddress Any { get { return new NetworkAddress(IPAddress.None, 0); } } #endregion #region Constructors /// <summary> /// Create a network address from a string. /// </summary> /// <param name="addressString">The address string. It must be in the format "IPAddress:PortNo", e.g. 192.168.0.0:20000.</param> public NetworkAddress(string addressString) { int separator_position = addressString.IndexOf(":"); this.host = IPAddress.Parse(addressString.Substring(0, separator_position)); this.port = (int) Convert.ToUInt32(addressString.Substring(separator_position + 1)); } /// <summary> /// Create a network address from a given IP address and port number. /// </summary> /// <param name="hostIPAddress">IP address</param> /// <param name="port">port number</param> public NetworkAddress(IPAddress hostIPAddress, int port) { this.host = hostIPAddress; this.port = port; } /// <summary> /// The copy constructor. /// </summary> /// <param name="anotherAddress">The address to duplicate.</param> public NetworkAddress(NetworkAddress anotherAddress) { this.host = anotherAddress.host; this.port = anotherAddress.port; } /// <summary> /// The default constructor that creates an uninitialized address. /// </summary> public NetworkAddress() { } /* public NetworkAddress(QS.CMS.Base2.IBlockOfData blockOfData) { byte[] bytes = new byte[4]; Buffer.BlockCopy(blockOfData.Buffer, (int) blockOfData.OffsetWithinBuffer, bytes, 0, 4); host = new IPAddress(bytes); port = BitConverter.ToInt32(blockOfData.Buffer, (int) blockOfData.OffsetWithinBuffer + 4); } */ #endregion #region Accessors /// <summary> /// The IP address of the host. /// </summary> [System.Xml.Serialization.XmlIgnore] public IPAddress HostIPAddress { get { return host; } set { host = value; } } /// <summary> /// The string representation of the IP address of the host. /// </summary> [System.Xml.Serialization.XmlAttribute("IPAddress")] public string HostIPAddressAsString { get { return host.ToString(); } set { host = IPAddress.Parse(value); } } /// <summary> /// The port number. /// </summary> [System.Xml.Serialization.XmlAttribute("PortNo")] public int PortNumber { get { return port; } set { port = value; } } #endregion #region Fields private IPAddress host; private int port; #endregion #region System.Object Overrides public override bool Equals(object obj) { return (obj is QS.Fx.Network.NetworkAddress) && ((QS.Fx.Network.NetworkAddress) obj).host.Equals(this.host) && ((QS.Fx.Network.NetworkAddress) obj).port.Equals(this.port); } public override int GetHashCode() { return host.GetHashCode() ^ port.GetHashCode(); } public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); // bool isfirst = true; // foreach (byte b in host.GetAddressBytes()) // { // if (isfirst) // isfirst = false; // else // sb.Append("."); // sb.Append(b.ToString("000")); // } sb.Append(host.ToString()); sb.Append(":"); sb.Append(port.ToString()); return sb.ToString(); } #endregion /* #region ISerializable Members [System.Xml.Serialization.XmlIgnore] public virtual ClassID ClassIDAsSerializable { get { return ClassID.NetworkAddress; } } public virtual void save(System.IO.Stream memoryStream) { byte[] buffer; buffer = System.BitConverter.GetBytes(port); memoryStream.Write(buffer, 0, buffer.Length); buffer = host.GetAddressBytes(); memoryStream.Write(buffer, 0, buffer.Length); } public virtual void load(System.IO.Stream memoryStream) { byte[] buffer = new byte[4]; memoryStream.Read(buffer, 0, 4); port = System.BitConverter.ToInt32(buffer, 0); buffer = new byte[4]; memoryStream.Read(buffer, 0, 4); host = IPAddress.Parse( buffer[0] + "." + buffer[1] + "." + buffer[2] + "." + buffer[3]); } #endregion */ /* [System.Xml.Serialization.XmlIgnore] public static uint SizeAsBlockOfData { get { return 4 + (uint) System.Runtime.InteropServices.Marshal.SizeOf(typeof(int)); } } */ /* #region Base2.IMessage Members [System.Xml.Serialization.XmlIgnore] public QS.CMS.Base2.IOutgoingData AsOutgoingData { get { return new QS.CMS.Base2.OutgoingVector(new QS.CMS.Base2.IBlockOfData[] { new QS.CMS.Base2.BlockOfData(host.GetAddressBytes()), new QS.CMS.Base2.BlockOfData(BitConverter.GetBytes(port)) }); } } // public uint Size // { // get // { // return NetworkAddress.SizeAsBlockOfData; // } // } // // public void serializeTo(byte[] bufferForData, uint offsetWithinBuffer, uint spaceWithinBuffer) // { // Buffer.BlockCopy(, 0, bufferForData, (int) offsetWithinBuffer, 4); // byte[] bytes = ; // Buffer.BlockCopy(bytes , 0, bufferForData, (int) offsetWithinBuffer + 4, bytes.Length); // } #endregion */ /* #region IScatterAddress Members public QS.CMS.Scattering.AddressClass AddressClass { get { return QS.CMS.Scattering.AddressClass.INDIVIDUAL_ADDRESS; } } #endregion */ /* #region Base2.ISerializable Members public uint Size { get { return QS.CMS.Base2.SizeOf.IPAddress + QS.CMS.Base2.SizeOf.UInt32; } } void QS.CMS.Base2.IBase2Serializable.load(QS.CMS.Base2.IBlockOfData blockOfData) { host = QS.CMS.Base2.Serializer.loadIPAddress(blockOfData); port = QS.CMS.Base2.Serializer.loadInt32(blockOfData); } void QS.CMS.Base2.IBase2Serializable.save(QS.CMS.Base2.IBlockOfData blockOfData) { QS.CMS.Base2.Serializer.saveIPAddress(host, blockOfData); QS.CMS.Base2.Serializer.saveInt32(port, blockOfData); } public QS.ClassID ClassID { get { return ClassID.NetworkAddress; } } #endregion */ /* public unsafe void CopyTo(System.ArraySegment<byte> segment) { if (segment.Count < 6) throw new ArgumentException("Not enough space."); fixed (byte* arrayptr = segment.Array) { byte* dataptr = arrayptr + segment.Offset; *((int*)dataptr) = port; #pragma warning disable 0618 *((long*)(dataptr + sizeof(int))) = host.Address; #pragma warning restore 0618 } } */ #region QS.Fx.Serialization.ISerializable Members public QS.Fx.Serialization.SerializableInfo SerializableInfo { get { int total_size = sizeof(int) + sizeof(long); return new QS.Fx.Serialization.SerializableInfo((ushort)QS.ClassID.NetworkAddress, (ushort)total_size, total_size, 0); } } public unsafe void SerializeTo(ref QS.Fx.Base.ConsumableBlock header, ref System.Collections.Generic.IList<QS.Fx.Base.Block> data) { fixed (byte* arrayptr = header.Array) { byte *headerptr = arrayptr + header.Offset; *((int*) headerptr) = port; #pragma warning disable 0618 *((long*)(headerptr + sizeof(int))) = host.Address; #pragma warning restore 0618 } header.consume(sizeof(int) + sizeof(long)); } public unsafe void DeserializeFrom(ref QS.Fx.Base.ConsumableBlock header, ref QS.Fx.Base.ConsumableBlock data) { long host_address = 0; #if DEBUG_CheckAddressesOnDeserialization try { #endif fixed (byte* arrayptr = header.Array) { byte* headerptr = arrayptr + header.Offset; port = *((int*)headerptr); host_address = *((long*)(headerptr + sizeof(int))); } header.consume(sizeof(int) + sizeof(long)); host = new IPAddress(host_address); #if DEBUG_CheckAddressesOnDeserialization } catch (Exception exc) { throw new Exception("Error while deserializing address {" + host_address.ToString("x") + "}.", exc); } #endif } #endregion #region IComparable Members public int CompareTo(object obj) { if (obj is QS.Fx.Network.NetworkAddress) return ((IComparable<NetworkAddress>) this).CompareTo(obj as NetworkAddress); else throw new ArgumentException(); } #endregion #region CompareIPAddresses /// <summary> /// Tests whether the two given IP addresses are identical. /// </summary> /// <param name="address1">Address 1.</param> /// <param name="address2">Address 2.</param> /// <returns>True if Address1 == Address2.</returns> public unsafe static int CompareIPAddresses(IPAddress address1, IPAddress address2) { #pragma warning disable 618 long n1 = address1.Address; long n2 = address2.Address; #pragma warning restore 618 int result = ((byte*)&n1)[0] - ((byte*)&n2)[0]; if (result == 0) { result = ((byte*)&n1)[1] - ((byte*)&n2)[1]; if (result == 0) { result = ((byte*)&n1)[2] - ((byte*)&n2)[2]; if (result == 0) result = ((byte*)&n1)[3] - ((byte*)&n2)[3]; } } return result; } #endregion #region IComparable<NetworkAddress> Members int IComparable<NetworkAddress>.CompareTo(NetworkAddress other) { int result = CompareIPAddresses(this.HostIPAddress, other.HostIPAddress); return (result == 0) ? (this.PortNumber.CompareTo(other.PortNumber)) : result; } #if Using_VS2005Beta1 bool IComparable<NetworkAddress>.Equals(NetworkAddress other) { return ((IComparable<NetworkAddress>)this).CompareTo(other) == 0; } #endif #endregion #region IStringSerializable Members ushort QS.Fx.Serialization.IStringSerializable.ClassID { get { return (ushort)ClassID.NetworkAddress; } } string QS.Fx.Serialization.IStringSerializable.AsString { get { return host.ToString() + ":" + port.ToString(); } set { int separator = value.IndexOf(":"); host = IPAddress.Parse(value.Substring(0, separator)); port = System.Convert.ToInt32(value.Substring(separator + 1)); } } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="CounterSetInstanceCounterDataSet.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Diagnostics.PerformanceData { using System; using System.Threading; using System.Runtime.InteropServices; using System.ComponentModel; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Security; using Microsoft.Win32; /// <summary> /// CounterData class is used to store actual raw counter data. It is the value element within /// CounterSetInstanceCounterDataSet, which is part of CounterSetInstance. /// </summary> [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public sealed class CounterData { [SecurityCritical] unsafe private Int64 * m_offset; /// <summary> /// CounterData constructor /// </summary> /// <param name="counterId"> counterId would come from CounterSet::AddCounter() parameter </param> /// <param name="pCounterData"> The memory location to store raw counter data </param> [System.Security.SecurityCritical] unsafe internal CounterData(Int64 * pCounterData) { m_offset = pCounterData; * m_offset = 0; } /// <summary> /// Value property it used to query/update actual raw counter data. /// </summary> public Int64 Value { [System.Security.SecurityCritical] get { unsafe { return Interlocked.Read(ref (* m_offset)); } } [System.Security.SecurityCritical] set { unsafe { Interlocked.Exchange(ref (* m_offset), value); } } } [System.Security.SecurityCritical] public void Increment() { unsafe { Interlocked.Increment (ref (*m_offset)); } } [System.Security.SecurityCritical] public void Decrement() { unsafe { Interlocked.Decrement (ref (*m_offset)); } } [System.Security.SecurityCritical] public void IncrementBy(Int64 value) { unsafe { Interlocked.Add (ref (*m_offset), value); } } /// <summary> /// RawValue property it used to query/update actual raw counter data. /// This property is not thread-safe and should only be used /// for performance-critical single-threaded access. /// </summary> public Int64 RawValue { [System.Security.SecurityCritical] get { unsafe { return (* m_offset); } } [System.Security.SecurityCritical] set { unsafe { * m_offset = value; } } } } /// <summary> /// CounterSetInstanceCounterDataSet is part of CounterSetInstance class, and is used to store raw counter data /// for all counters added in CounterSet. /// </summary> [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public sealed class CounterSetInstanceCounterDataSet : IDisposable { internal CounterSetInstance m_instance; private Dictionary<Int32, CounterData> m_counters; private Int32 m_disposed; [SecurityCritical] unsafe internal byte * m_dataBlock; [System.Security.SecurityCritical] [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] internal CounterSetInstanceCounterDataSet(CounterSetInstance thisInst) { m_instance = thisInst; m_counters = new Dictionary<Int32, CounterData>(); unsafe { if (m_instance.m_counterSet.m_provider == null) { throw new ArgumentException(SR.GetString(SR.Perflib_Argument_ProviderNotFound, m_instance.m_counterSet.m_providerGuid), "ProviderGuid"); } if (m_instance.m_counterSet.m_provider.m_hProvider.IsInvalid) { throw new InvalidOperationException(SR.GetString(SR.Perflib_InvalidOperation_NoActiveProvider, m_instance.m_counterSet.m_providerGuid)); } m_dataBlock = (byte *) Marshal.AllocHGlobal(m_instance.m_counterSet.m_idToCounter.Count * sizeof(Int64)); if (m_dataBlock == null) { throw new InsufficientMemoryException(SR.GetString(SR.Perflib_InsufficientMemory_InstanceCounterBlock, m_instance.m_counterSet.m_counterSet, m_instance.m_instName)); } Int32 CounterOffset = 0; foreach (KeyValuePair<Int32, CounterType> CounterDef in m_instance.m_counterSet.m_idToCounter) { CounterData thisCounterData = new CounterData((Int64 *) (m_dataBlock + CounterOffset * sizeof(Int64))); m_counters.Add(CounterDef.Key, thisCounterData); // ArgumentNullException - CounterName is NULL // ArgumentException - CounterName already exists. uint Status = UnsafeNativeMethods.PerfSetCounterRefValue( m_instance.m_counterSet.m_provider.m_hProvider, m_instance.m_nativeInst, (uint) CounterDef.Key, (void *) (m_dataBlock + CounterOffset * sizeof(Int64))); if (Status != (uint) UnsafeNativeMethods.ERROR_SUCCESS) { Dispose(true); // ERROR_INVALID_PARAMETER or ERROR_NOT_FOUND switch (Status) { case (uint) UnsafeNativeMethods.ERROR_NOT_FOUND: throw new InvalidOperationException(SR.GetString(SR.Perflib_InvalidOperation_CounterRefValue, m_instance.m_counterSet.m_counterSet, CounterDef.Key, m_instance.m_instName)); default: throw new Win32Exception((int) Status); } } CounterOffset ++; } } } [System.Security.SecurityCritical] public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } [System.Security.SecurityCritical] ~CounterSetInstanceCounterDataSet() { Dispose(false); } [System.Security.SecurityCritical] private void Dispose(bool disposing) { if (Interlocked.Exchange(ref m_disposed, 1) == 0) { unsafe { if (m_dataBlock != null) { // Need to free allocated heap memory that is used to store all raw counter data. Marshal.FreeHGlobal((System.IntPtr)m_dataBlock); m_dataBlock = null; } } } } /// <summary> /// CounterId indexer to access specific CounterData object. /// </summary> /// <param name="counterId">CounterId that matches one CounterSet::AddCounter()call</param> /// <returns>CounterData object with matched counterId</returns> public CounterData this[Int32 counterId] { get { if (m_disposed != 0) { return null; } try { return m_counters[counterId]; } catch (KeyNotFoundException) { return null; } catch { throw; } } } /// <summary> /// CounterName indexer to access specific CounterData object. /// </summary> /// <param name="counterName">CounterName that matches one CounterSet::AddCounter() call</param> /// <returns>CounterData object with matched counterName</returns> [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public CounterData this[String counterName] { get { if (counterName == null) { throw new ArgumentNullException("CounterName"); } if (counterName.Length == 0) { throw new ArgumentNullException("CounterName"); } if (m_disposed != 0) { return null; } try { Int32 CounterId = m_instance.m_counterSet.m_stringToId[counterName]; try { return m_counters[CounterId]; } catch (KeyNotFoundException) { return null; } catch { throw; } } catch (KeyNotFoundException) { return null; } catch { throw; } } } } }
using Signum.Entities.Workflow; using Signum.Engine.Operations; using Signum.Entities; using Signum.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using System.Linq.Expressions; namespace Signum.Engine.Workflow { public partial class WorkflowBuilder { private partial class PoolBuilder { public XmlEntity<WorkflowPoolEntity> pool; private Dictionary<Lite<WorkflowLaneEntity>, LaneBuilder> lanes; private List<XmlEntity<WorkflowConnectionEntity>> sequenceFlows; //Contains all the connections internal to the pool INCLUDING the internals to each lane public PoolBuilder(WorkflowPoolEntity p, IEnumerable<LaneBuilder> laneBuilders, IEnumerable<XmlEntity<WorkflowConnectionEntity>> sequenceFlows) { this.pool = new XmlEntity<WorkflowPoolEntity>(p); this.lanes = laneBuilders.ToDictionary(a => a.lane.Entity.ToLite()); this.sequenceFlows = sequenceFlows.ToList(); } public void ApplyChanges(XElement processElement, Locator locator) { var sequenceFlows = processElement.Elements(bpmn + "sequenceFlow").ToDictionary(a => a.Attribute("id")!.Value); var oldSequenceFlows = this.sequenceFlows.ToDictionaryEx(a => a.bpmnElementId, "sequenceFlows"); Synchronizer.Synchronize(sequenceFlows, oldSequenceFlows, null, (id, osf) => { this.sequenceFlows.Remove(osf); osf.Entity.Delete(WorkflowConnectionOperation.Delete); }, (id, sf, osf) => { var newFrom = locator.FindEntity(sf.Attribute("sourceRef")!.Value); var newTo = locator.FindEntity(sf.Attribute("targetRef")!.Value); if(!newFrom.Is(osf.Entity.From) || !newTo.Is(osf.Entity.To)) { osf.Entity.InDB().UnsafeUpdate() .Set(a => a.From, a => newFrom) .Set(a => a.To, a => newTo) .Execute(); osf.Entity.From = newFrom!; osf.Entity.To = newTo!; osf.Entity.SetCleanModified(false); } }); var oldLanes = this.lanes.Values.ToDictionaryEx(a => a.lane.bpmnElementId, "lanes"); var lanes = processElement.Element(bpmn + "laneSet")!.Elements(bpmn + "lane").ToDictionaryEx(a => a.Attribute("id")!.Value); Synchronizer.Synchronize(lanes, oldLanes, createNew: (id, l) => { var wl = new WorkflowLaneEntity { Xml = new WorkflowXmlEmbedded(), Pool = this.pool.Entity }.ApplyXml(l, locator); var lb = new LaneBuilder(wl, Enumerable.Empty<WorkflowActivityEntity>(), Enumerable.Empty<WorkflowEventEntity>(), Enumerable.Empty<WorkflowGatewayEntity>(), Enumerable.Empty<XmlEntity<WorkflowConnectionEntity>>()); lb.ApplyChanges(processElement, l, locator); this.lanes.Add(wl.ToLite(), lb); }, removeOld: null, merge: (id, l, ol) => { var wl = ol.lane.Entity.ApplyXml(l, locator); ol.ApplyChanges(processElement, l, locator); }); Synchronizer.Synchronize(lanes, oldLanes, createNew: null, removeOld: (id, ol) => { ol.ApplyChanges(processElement, ol.lane.Element, locator); this.lanes.Remove(ol.lane.Entity.ToLite()); ol.lane.Entity.Delete(WorkflowLaneOperation.Delete); }, merge: null); Synchronizer.Synchronize(sequenceFlows, oldSequenceFlows, (id, sf) => { var wc = new WorkflowConnectionEntity { Xml = new WorkflowXmlEmbedded() }.ApplyXml(sf, locator); this.sequenceFlows.Add(new XmlEntity<WorkflowConnectionEntity>(wc)); }, null, (id, sf, osf) => { osf.Entity.ApplyXml(sf, locator); }); } public IWorkflowNodeEntity? FindEntity(string bpmElementId) { return this.lanes.Values.Select(lb => lb.FindEntity(bpmElementId)).NotNull().SingleOrDefault(); } internal XElement GetParticipantElement() { return new XElement(bpmn + "participant", new XAttribute("id", pool.bpmnElementId), new XAttribute("name", pool.Entity.Name), new XAttribute("processRef", "Process_" + pool.bpmnElementId)); } internal XElement GetProcessElement() { return new XElement(bpmn + "process", new XAttribute("id", "Process_" + pool.bpmnElementId), new XAttribute("isExecutable", "false"), new XElement(bpmn + "laneSet", lanes.Values.Select(l => l.GetLaneSetElement()).ToList()), lanes.Values.SelectMany(e => e.GetNodesElement()).ToList(), GetSequenceFlowsElement()); } internal List<XElement> GetDiagramElements() { List<XElement> res = new List<XElement>(); res.Add(pool.Element); res.AddRange(lanes.Values.SelectMany(a => a.GetDiagramElement()).ToList()); res.AddRange(sequenceFlows.Select(a => a.Element)); return res; } internal LaneBuilder GetLaneBuilder(Lite<WorkflowLaneEntity> l) { return lanes.GetOrThrow(l); } private List<XElement> GetSequenceFlowsElement() { return sequenceFlows.Select(a => new XElement(bpmn + "sequenceFlow", new XAttribute("id", a.bpmnElementId), a.Entity.Name.HasText() ? new XAttribute("name", a.Entity.Name) : null!, new XAttribute("sourceRef", GetLaneBuilder(a.Entity.From.Lane.ToLite()).GetBpmnElementId(a.Entity.From)), new XAttribute("targetRef", GetLaneBuilder(a.Entity.To.Lane.ToLite()).GetBpmnElementId(a.Entity.To)) )).ToList(); } internal void DeleteAll(Locator? locator) { foreach (var lb in lanes.Values) { lb.DeleteAll(locator); } this.pool.Entity.Delete(WorkflowPoolOperation.Delete); } internal void DeleteCaseActivities(Expression<Func<CaseEntity, bool>> filter) { foreach (var lb in lanes.Values) lb.DeleteCaseActivities(filter); } internal IEnumerable<XmlEntity<WorkflowActivityEntity>> GetAllActivities() { return this.lanes.Values.SelectMany(la => la.GetActivities()); } internal List<LaneBuilder> GetLanes() { return this.lanes.Values.ToList(); } internal List<XmlEntity<WorkflowConnectionEntity>> GetSequenceFlows() { return this.sequenceFlows; } internal void Clone(WorkflowEntity wf, Dictionary<IWorkflowNodeEntity, IWorkflowNodeEntity> nodes) { var oldPool = this.pool.Entity; var newPool = new WorkflowPoolEntity { Workflow = wf, Name = oldPool.Name, BpmnElementId = oldPool.BpmnElementId, Xml = oldPool.Xml, }.Save(); foreach (var lb in this.lanes.Values) { lb.Clone(newPool, nodes); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Twice.Models.Scheduling; using Twice.Resources; using Twice.Utilities; using Twice.ViewModels.Validation; namespace Twice.ViewModels.Twitter { internal class ScheduleInformationViewModel : ValidationViewModel, IScheduleInformationViewModel { public ScheduleInformationViewModel( IScheduler scheduler, IDateProvider dateProvider ) { DateProvider = dateProvider; Scheduler = scheduler; Validate( () => ScheduleDate ) .If( () => IsTweetScheduled ) .Check( dt => dt.Date >= dateProvider.Now.Date ) .Message( Strings.DateMustBeInTheFuture ); Validate( () => ScheduleTime ) .If( () => IsTweetScheduled ) .Check( dt => dt.TimeOfDay >= dateProvider.Now.TimeOfDay || ScheduleDate.Date > DateProvider.Now.Date ) .Message( Strings.DateMustBeInTheFuture ); Validate( () => DeletionDate ) .If( () => IsDeletionScheduled ) .Check( dt => dt.Date >= dateProvider.Now.Date ) .Message( Strings.DateMustBeInTheFuture ); Validate( () => DeletionTime ) .If( () => IsDeletionScheduled ) .Check( dt => dt.TimeOfDay >= dateProvider.Now.TimeOfDay || DeletionDate.Date > DateProvider.Now.Date ) .Message( Strings.DateMustBeInTheFuture ); Validate( () => DeletionDate ) .If( () => IsDeletionScheduled && IsTweetScheduled ) .Check( dt => dt.Date >= ScheduleDate.Date ) .Message( Strings.DateMustBeInTheFuture ); Validate( () => DeletionTime ) .If( () => IsDeletionScheduled && IsTweetScheduled ) .Check( dt => dt.TimeOfDay >= ScheduleDate.TimeOfDay || DeletionDate.Date > ScheduleDate.Date ) .Message( Strings.DateMustBeInTheFuture ); } public DateTime DeletionDate { [DebuggerStepThrough] get { return _DeletionDate; } set { if( _DeletionDate == value ) { return; } _DeletionDate = value; RaisePropertyChanged(); RaisePropertyChanged( nameof(DeletionTime) ); } } public DateTime DeletionTime { [DebuggerStepThrough] get { return _DeletionTime; } set { if( _DeletionTime == value ) { return; } _DeletionTime = value; RaisePropertyChanged(); RaisePropertyChanged( nameof(DeletionDate) ); } } public bool IsDeletionScheduled { [DebuggerStepThrough] get { return _IsDeletionScheduled; } set { if( _IsDeletionScheduled == value ) { return; } _IsDeletionScheduled = value; RaisePropertyChanged(); if( value ) { IsTweetScheduled = false; } } } public bool IsTweetScheduled { [DebuggerStepThrough] get { return _IsTweetScheduled; } set { if( _IsTweetScheduled == value ) { return; } _IsTweetScheduled = value; RaisePropertyChanged(); if( value ) { IsDeletionScheduled = false; } } } public void ResetSchedule() { ScheduleDate = DateProvider.Now.Date; ScheduleTime = DateProvider.Now.Date; DeletionDate = DateProvider.Now.Date; DeletionTime = DateProvider.Now.Date; IsTweetScheduled = false; IsDeletionScheduled = false; } public DateTime ScheduleDate { [DebuggerStepThrough] get { return _ScheduleDate; } set { if( _ScheduleDate == value ) { return; } _ScheduleDate = value; RaisePropertyChanged(); RaisePropertyChanged( nameof(ScheduleTime) ); } } public void ScheduleDeletion( List<Tuple<ulong, ulong>> tweetIds, string text ) { var job = new SchedulerJob { JobType = SchedulerJobType.DeleteStatus, IdsToDelete = tweetIds.Select( t => t.Item1 ).ToList(), AccountIds = tweetIds.Select( t => t.Item2 ).ToList(), TargetTime = DeletionDate + DeletionTime.TimeOfDay, Text = text }; Scheduler.AddJob( job ); } public DateTime ScheduleTime { [DebuggerStepThrough] get { return _ScheduleTime; } set { if( _ScheduleTime == value ) { return; } _ScheduleTime = value; RaisePropertyChanged(); RaisePropertyChanged( nameof(ScheduleDate) ); } } public void ScheduleTweet( string text, ulong? inReplyTo, IEnumerable<ulong> accountIds, IEnumerable<string> mediaFileNames ) { var job = new SchedulerJob { JobType = SchedulerJobType.CreateStatus, Text = text, AccountIds = accountIds.ToList(), TargetTime = ScheduleDate + ScheduleTime.TimeOfDay, InReplyToStatus = inReplyTo ?? 0, FilesToAttach = mediaFileNames.ToList() }; Scheduler.AddJob( job ); } public IScheduler Scheduler { get; } private readonly IDateProvider DateProvider; [DebuggerBrowsable( DebuggerBrowsableState.Never )] private DateTime _DeletionDate; [DebuggerBrowsable( DebuggerBrowsableState.Never )] private DateTime _DeletionTime; [DebuggerBrowsable( DebuggerBrowsableState.Never )] private bool _IsDeletionScheduled; [DebuggerBrowsable( DebuggerBrowsableState.Never )] private bool _IsTweetScheduled; [DebuggerBrowsable( DebuggerBrowsableState.Never )] private DateTime _ScheduleDate; [DebuggerBrowsable( DebuggerBrowsableState.Never )] private DateTime _ScheduleTime; } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Tests.Common.Builders.Extensions; using Umbraco.Cms.Tests.Common.Builders.Interfaces; namespace Umbraco.Cms.Tests.Common.Builders { public abstract class ContentTypeBaseBuilder<TParent, TType> : ChildBuilderBase<TParent, TType>, IBuildPropertyGroups, IWithIdBuilder, IWithKeyBuilder, IWithAliasBuilder, IWithNameBuilder, IWithParentIdBuilder, IWithParentContentTypeBuilder, IWithPathBuilder, IWithLevelBuilder, IWithSortOrderBuilder, IWithCreatorIdBuilder, IWithCreateDateBuilder, IWithUpdateDateBuilder, IWithDescriptionBuilder, IWithIconBuilder, IWithThumbnailBuilder, IWithTrashedBuilder, IWithIsContainerBuilder where TParent : IBuildContentTypes { private int? _id; private Guid? _key; private string _alias; private string _name; private int? _parentId; private IContentTypeComposition _parent; private int? _level; private string _path; private int? _sortOrder; private int? _creatorId; private DateTime? _createDate; private DateTime? _updateDate; private string _description; private string _icon; private string _thumbnail; private bool? _trashed; private bool? _isContainer; protected IShortStringHelper ShortStringHelper => new DefaultShortStringHelper(new DefaultShortStringHelperConfig()); public ContentTypeBaseBuilder(TParent parentBuilder) : base(parentBuilder) { } protected int GetId() => _id ?? 0; protected Guid GetKey() => _key ?? Guid.NewGuid(); protected DateTime GetCreateDate() => _createDate ?? DateTime.Now; protected DateTime GetUpdateDate() => _updateDate ?? DateTime.Now; protected string GetName() => _name ?? Guid.NewGuid().ToString(); protected string GetAlias() => _alias ?? GetName().ToCamelCase(); protected int GetParentId() => _parentId ?? -1; protected IContentTypeComposition GetParent() => _parent ?? null; protected int GetLevel() => _level ?? 0; protected string GetPath() => _path ?? _path ?? $"-1,{GetId()}"; protected int GetSortOrder() => _sortOrder ?? 0; protected string GetDescription() => _description ?? string.Empty; protected string GetIcon() => _icon ?? "icon-document"; protected string GetThumbnail() => _thumbnail ?? "folder.png"; protected int GetCreatorId() => _creatorId ?? 0; protected bool GetTrashed() => _trashed ?? false; protected bool GetIsContainer() => _isContainer ?? false; protected void BuildPropertyGroups(ContentTypeCompositionBase contentType, IEnumerable<PropertyGroup> propertyGroups) { foreach (PropertyGroup propertyGroup in propertyGroups) { contentType.PropertyGroups.Add(propertyGroup); } } protected void BuildPropertyTypeIds(ContentTypeCompositionBase contentType, int? propertyTypeIdsIncrementingFrom) { if (propertyTypeIdsIncrementingFrom.HasValue) { var i = propertyTypeIdsIncrementingFrom.Value; foreach (IPropertyType propertyType in contentType.PropertyTypes) { propertyType.Id = ++i; } } } public static void EnsureAllIds(ContentTypeCompositionBase contentType, int seedId) { // Ensure everything has IDs (it will have if builder is used to create the object, but still useful to reset // and ensure there are no clashes). contentType.Id = seedId; var itemid = seedId + 1; foreach (PropertyGroup propertyGroup in contentType.PropertyGroups) { propertyGroup.Id = itemid++; } foreach (IPropertyType propertyType in contentType.PropertyTypes) { propertyType.Id = itemid++; } } int? IWithIdBuilder.Id { get => _id; set => _id = value; } Guid? IWithKeyBuilder.Key { get => _key; set => _key = value; } string IWithAliasBuilder.Alias { get => _alias; set => _alias = value; } string IWithNameBuilder.Name { get => _name; set => _name = value; } int? IWithParentIdBuilder.ParentId { get => _parentId; set { _parent = null; _parentId = value; } } IContentTypeComposition IWithParentContentTypeBuilder.Parent { get => _parent; set { _parentId = null; _parent = value; } } int? IWithLevelBuilder.Level { get => _level; set => _level = value; } string IWithPathBuilder.Path { get => _path; set => _path = value; } int? IWithSortOrderBuilder.SortOrder { get => _sortOrder; set => _sortOrder = value; } int? IWithCreatorIdBuilder.CreatorId { get => _creatorId; set => _creatorId = value; } DateTime? IWithCreateDateBuilder.CreateDate { get => _createDate; set => _createDate = value; } DateTime? IWithUpdateDateBuilder.UpdateDate { get => _updateDate; set => _updateDate = value; } string IWithDescriptionBuilder.Description { get => _description; set => _description = value; } string IWithIconBuilder.Icon { get => _icon; set => _icon = value; } string IWithThumbnailBuilder.Thumbnail { get => _thumbnail; set => _thumbnail = value; } bool? IWithTrashedBuilder.Trashed { get => _trashed; set => _trashed = value; } bool? IWithIsContainerBuilder.IsContainer { get => _isContainer; set => _isContainer = value; } } }
using System; using System.Collections.Generic; using System.Text; namespace iControl { //======================================================================= // Enums //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.AddressType", Namespace = "urn:iControl")] public enum GlobalLBAddressType { ATYPE_UNSET, ATYPE_STAR_ADDRESS_STAR_PORT, ATYPE_STAR_ADDRESS_EXPLICIT_PORT, ATYPE_EXPLICIT_ADDRESS_EXPLICIT_PORT, ATYPE_STAR_ADDRESS, ATYPE_EXPLICIT_ADDRESS, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.AutoConfigurationState", Namespace = "urn:iControl")] public enum GlobalLBAutoConfigurationState { AUTOCONFIG_DISABLED, AUTOCONFIG_ENABLED, AUTOCONFIG_ENABLED_AUTODELETE_DISABLED, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.AvailabilityDependency", Namespace = "urn:iControl")] public enum GlobalLBAvailabilityDependency { AVAILABILITY_DEPENDENCY_NONE, AVAILABILITY_DEPENDENCY_SERVER, AVAILABILITY_DEPENDENCY_LINK, AVAILABILITY_DEPENDENCY_DATA_CENTER, AVAILABILITY_DEPENDENCY_WIDE_IP, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.DNSReturnCode", Namespace = "urn:iControl")] public enum GlobalLBDNSReturnCode { RETURN_CODE_UNKNOWN, RETURN_CODE_NO_ERROR, RETURN_CODE_FORMAT_ERROR, RETURN_CODE_SERVER_FAILURE, RETURN_CODE_NON_EXISTENT_DOMAIN, RETURN_CODE_NOT_IMPLEMENTED, RETURN_CODE_REFUSED, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.DomainNameCheckMode", Namespace = "urn:iControl")] public enum GlobalLBDomainNameCheckMode { DOMAIN_NAME_CHECK_MODE_UNKNOWN, DOMAIN_NAME_CHECK_MODE_NONE, DOMAIN_NAME_CHECK_MODE_STRICT, DOMAIN_NAME_CHECK_MODE_ALLOW_UNDERSCORES, DOMAIN_NAME_CHECK_MODE_IDN_COMPATIBLE, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.GTMQueryType", Namespace = "urn:iControl")] public enum GlobalLBGTMQueryType { GTM_QUERY_TYPE_UNKNOWN, GTM_QUERY_TYPE_A, GTM_QUERY_TYPE_CNAME, GTM_QUERY_TYPE_MX, GTM_QUERY_TYPE_AAAA, GTM_QUERY_TYPE_SRV, GTM_QUERY_TYPE_NAPTR, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.HardwareSecurityModuleType", Namespace = "urn:iControl")] public enum GlobalLBHardwareSecurityModuleType { HARDWARE_SECURITY_MODULE_TYPE_UNKNOWN, HARDWARE_SECURITY_MODULE_TYPE_NONE, HARDWARE_SECURITY_MODULE_TYPE_INTERNAL, HARDWARE_SECURITY_MODULE_TYPE_EXTERNAL, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.LBDecisionLogVerbosity", Namespace = "urn:iControl")] public enum GlobalLBLBDecisionLogVerbosity { LB_DECISION_LOG_UNKNOWN, LB_DECISION_LOG_NONE, LB_DECISION_POOL_SELECTION, LB_DECISION_POOL_TRAVERSAL, LB_DECISION_PM_SELECTION, LB_DECISION_PM_TRAVERSAL, LB_DECISION_LOG_ALL, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.LBMethod", Namespace = "urn:iControl")] public enum GlobalLBLBMethod { LB_METHOD_RETURN_TO_DNS, LB_METHOD_NULL, LB_METHOD_ROUND_ROBIN, LB_METHOD_RATIO, LB_METHOD_TOPOLOGY, LB_METHOD_STATIC_PERSIST, LB_METHOD_GLOBAL_AVAILABILITY, LB_METHOD_VS_CAPACITY, LB_METHOD_LEAST_CONN, LB_METHOD_LOWEST_RTT, LB_METHOD_LOWEST_HOPS, LB_METHOD_PACKET_RATE, LB_METHOD_CPU, LB_METHOD_HIT_RATIO, LB_METHOD_QOS, LB_METHOD_BPS, LB_METHOD_DROP_PACKET, LB_METHOD_EXPLICIT_IP, LB_METHOD_CONNECTION_RATE, LB_METHOD_VS_SCORE, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.LDNSProbeProtocol", Namespace = "urn:iControl")] public enum GlobalLBLDNSProbeProtocol { LDNS_PROBE_PROTOCOL_ICMP, LDNS_PROBE_PROTOCOL_TCP, LDNS_PROBE_PROTOCOL_UDP, LDNS_PROBE_PROTOCOL_DNS_DOT, LDNS_PROBE_PROTOCOL_DNS_REV, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.LinkWeightType", Namespace = "urn:iControl")] public enum GlobalLBLinkWeightType { LINK_WEIGHT_TYPE_RATIO, LINK_WEIGHT_TYPE_COST, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.MetricLimitType", Namespace = "urn:iControl")] public enum GlobalLBMetricLimitType { METRIC_LIMIT_CPU_USAGE, METRIC_LIMIT_MEMORY_AVAILABLE, METRIC_LIMIT_BITS_PER_SECOND, METRIC_LIMIT_PACKETS_PER_SECOND, METRIC_LIMIT_CONNECTIONS, METRIC_LIMIT_CONNECTIONS_PER_SECOND, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.MonitorAssociationRemovalRule", Namespace = "urn:iControl")] public enum GlobalLBMonitorAssociationRemovalRule { REMOVE_EXPLICIT_MONITOR_ASSOCIATION, REMOVE_ALL_MONITOR_ASSOCIATION, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.MonitorInstanceStateType", Namespace = "urn:iControl")] public enum GlobalLBMonitorInstanceStateType { INSTANCE_STATE_UNCHECKED, INSTANCE_STATE_CHECKING, INSTANCE_STATE_UP, INSTANCE_STATE_DOWN, INSTANCE_STATE_FORCED_DOWN, INSTANCE_STATE_DISABLED, INSTANCE_STATE_DOWN_BY_IRULE, INSTANCE_STATE_DOWN_WAIT_FOR_MANUAL_RESUME, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.MonitorRuleType", Namespace = "urn:iControl")] public enum GlobalLBMonitorRuleType { MONITOR_RULE_TYPE_UNDEFINED, MONITOR_RULE_TYPE_NONE, MONITOR_RULE_TYPE_SINGLE, MONITOR_RULE_TYPE_AND_LIST, MONITOR_RULE_TYPE_M_OF_N, MONITOR_RULE_TYPE_M_FROM_N, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.ProberSelectionType", Namespace = "urn:iControl")] public enum GlobalLBProberSelectionType { PROBER_SELECTION_UNKNOWN, PROBER_SELECTION_INSIDE_DATACENTER, PROBER_SELECTION_OUTSIDE_DATACENTER, PROBER_SELECTION_POOL, PROBER_SELECTION_ANY_AVAILABLE, PROBER_SELECTION_INHERIT, PROBER_SELECTION_NONE, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.RegionDBType", Namespace = "urn:iControl")] public enum GlobalLBRegionDBType { REGION_DB_TYPE_USER_DEFINED, REGION_DB_TYPE_ACL, REGION_DB_TYPE_ISP, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.RegionType", Namespace = "urn:iControl")] public enum GlobalLBRegionType { REGION_TYPE_CIDR, REGION_TYPE_REGION, REGION_TYPE_CONTINENT, REGION_TYPE_COUNTRY, REGION_TYPE_STATE, REGION_TYPE_POOL, REGION_TYPE_DATA_CENTER, REGION_TYPE_ISP_REGION, REGION_TYPE_GEOIP_ISP, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.ServerType", Namespace = "urn:iControl")] public enum GlobalLBServerType { SERVER_TYPE_BIGIP_STANDALONE, SERVER_TYPE_BIGIP_REDUNDANT, SERVER_TYPE_GENERIC_LOAD_BALANCER, SERVER_TYPE_ALTEON_ACE_DIRECTOR, SERVER_TYPE_CISCO_CSS, SERVER_TYPE_CISCO_LOCAL_DIRECTOR_V2, SERVER_TYPE_CISCO_LOCAL_DIRECTOR_V3, SERVER_TYPE_CISCO_SERVER_LOAD_BALANCER, SERVER_TYPE_EXTREME, SERVER_TYPE_FOUNDRY_SERVER_IRON, SERVER_TYPE_GENERIC_HOST, SERVER_TYPE_CACHEFLOW, SERVER_TYPE_NETAPP, SERVER_TYPE_WINDOWS_2000, SERVER_TYPE_NT4, SERVER_TYPE_SOLARIS, SERVER_TYPE_RADWARE, SERVER_TYPE_BIGIP, } //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.MetricLimit", Namespace = "urn:iControl")] public partial class GlobalLBMetricLimit { private GlobalLBMetricLimitType typeField; public GlobalLBMetricLimitType type { get { return this.typeField; } set { this.typeField = value; } } private long valueField; public long value { get { return this.valueField; } set { this.valueField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.MonitorIPPort", Namespace = "urn:iControl")] public partial class GlobalLBMonitorIPPort { private GlobalLBAddressType address_typeField; public GlobalLBAddressType address_type { get { return this.address_typeField; } set { this.address_typeField = value; } } private CommonIPPortDefinition ipportField; public CommonIPPortDefinition ipport { get { return this.ipportField; } set { this.ipportField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.MonitorInstance", Namespace = "urn:iControl")] public partial class GlobalLBMonitorInstance { private string template_nameField; public string template_name { get { return this.template_nameField; } set { this.template_nameField = value; } } private GlobalLBMonitorIPPort instance_definitionField; public GlobalLBMonitorIPPort instance_definition { get { return this.instance_definitionField; } set { this.instance_definitionField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.MonitorInstanceState", Namespace = "urn:iControl")] public partial class GlobalLBMonitorInstanceState { private GlobalLBMonitorInstance instanceField; public GlobalLBMonitorInstance instance { get { return this.instanceField; } set { this.instanceField = value; } } private GlobalLBMonitorInstanceStateType instance_stateField; public GlobalLBMonitorInstanceStateType instance_state { get { return this.instance_stateField; } set { this.instance_stateField = value; } } private bool enabled_stateField; public bool enabled_state { get { return this.enabled_stateField; } set { this.enabled_stateField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.MonitorRule", Namespace = "urn:iControl")] public partial class GlobalLBMonitorRule { private GlobalLBMonitorRuleType typeField; public GlobalLBMonitorRuleType type { get { return this.typeField; } set { this.typeField = value; } } private long quorumField; public long quorum { get { return this.quorumField; } set { this.quorumField = value; } } private string [] monitor_templatesField; public string [] monitor_templates { get { return this.monitor_templatesField; } set { this.monitor_templatesField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.MonitorRuleV2", Namespace = "urn:iControl")] public partial class GlobalLBMonitorRuleV2 { private GlobalLBMonitorRuleType typeField; public GlobalLBMonitorRuleType type { get { return this.typeField; } set { this.typeField = value; } } private long quorumField; public long quorum { get { return this.quorumField; } set { this.quorumField = value; } } private long prober_countField; public long prober_count { get { return this.prober_countField; } set { this.prober_countField = value; } } private string [] monitor_templatesField; public string [] monitor_templates { get { return this.monitor_templatesField; } set { this.monitor_templatesField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.PoolID", Namespace = "urn:iControl")] public partial class GlobalLBPoolID { private string pool_nameField; public string pool_name { get { return this.pool_nameField; } set { this.pool_nameField = value; } } private GlobalLBGTMQueryType pool_typeField; public GlobalLBGTMQueryType pool_type { get { return this.pool_typeField; } set { this.pool_typeField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.ProberSelection", Namespace = "urn:iControl")] public partial class GlobalLBProberSelection { private GlobalLBProberSelectionType prober_preferenceField; public GlobalLBProberSelectionType prober_preference { get { return this.prober_preferenceField; } set { this.prober_preferenceField = value; } } private GlobalLBProberSelectionType prober_fallbackField; public GlobalLBProberSelectionType prober_fallback { get { return this.prober_fallbackField; } set { this.prober_fallbackField = value; } } private string prober_poolField; public string prober_pool { get { return this.prober_poolField; } set { this.prober_poolField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.VirtualServerDefinition", Namespace = "urn:iControl")] public partial class GlobalLBVirtualServerDefinition { private string nameField; public string name { get { return this.nameField; } set { this.nameField = value; } } private string addressField; public string address { get { return this.addressField; } set { this.addressField = value; } } private long portField; public long port { get { return this.portField; } set { this.portField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.VirtualServerID", Namespace = "urn:iControl")] public partial class GlobalLBVirtualServerID { private string nameField; public string name { get { return this.nameField; } set { this.nameField = value; } } private string serverField; public string server { get { return this.serverField; } set { this.serverField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.WideIPID", Namespace = "urn:iControl")] public partial class GlobalLBWideIPID { private string wideip_nameField; public string wideip_name { get { return this.wideip_nameField; } set { this.wideip_nameField = value; } } private GlobalLBGTMQueryType wideip_typeField; public GlobalLBGTMQueryType wideip_type { get { return this.wideip_typeField; } set { this.wideip_typeField = value; } } }; }
// 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.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Analytics { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.DataLake; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for DataLakeStoreAccountsOperations. /// </summary> public static partial class DataLakeStoreAccountsOperationsExtensions { /// <summary> /// Gets the specified Data Lake Store account details in the specified Data /// Lake Analytics account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account from which to retrieve the Data /// Lake Store account details. /// </param> /// <param name='dataLakeStoreAccountName'> /// The name of the Data Lake Store account to retrieve /// </param> public static DataLakeStoreAccountInfo Get(this IDataLakeStoreAccountsOperations operations, string resourceGroupName, string accountName, string dataLakeStoreAccountName) { return operations.GetAsync(resourceGroupName, accountName, dataLakeStoreAccountName).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified Data Lake Store account details in the specified Data /// Lake Analytics account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account from which to retrieve the Data /// Lake Store account details. /// </param> /// <param name='dataLakeStoreAccountName'> /// The name of the Data Lake Store account to retrieve /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DataLakeStoreAccountInfo> GetAsync(this IDataLakeStoreAccountsOperations operations, string resourceGroupName, string accountName, string dataLakeStoreAccountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, accountName, dataLakeStoreAccountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the Data Lake Analytics account specified to remove the specified /// Data Lake Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account from which to remove the Data /// Lake Store account. /// </param> /// <param name='dataLakeStoreAccountName'> /// The name of the Data Lake Store account to remove /// </param> public static void Delete(this IDataLakeStoreAccountsOperations operations, string resourceGroupName, string accountName, string dataLakeStoreAccountName) { operations.DeleteAsync(resourceGroupName, accountName, dataLakeStoreAccountName).GetAwaiter().GetResult(); } /// <summary> /// Updates the Data Lake Analytics account specified to remove the specified /// Data Lake Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account from which to remove the Data /// Lake Store account. /// </param> /// <param name='dataLakeStoreAccountName'> /// The name of the Data Lake Store account to remove /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IDataLakeStoreAccountsOperations operations, string resourceGroupName, string accountName, string dataLakeStoreAccountName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, dataLakeStoreAccountName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Updates the specified Data Lake Analytics account to include the additional /// Data Lake Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to which to add the Data Lake /// Store account. /// </param> /// <param name='dataLakeStoreAccountName'> /// The name of the Data Lake Store account to add. /// </param> /// <param name='parameters'> /// The details of the Data Lake Store account. /// </param> public static void Add(this IDataLakeStoreAccountsOperations operations, string resourceGroupName, string accountName, string dataLakeStoreAccountName, AddDataLakeStoreParameters parameters = default(AddDataLakeStoreParameters)) { operations.AddAsync(resourceGroupName, accountName, dataLakeStoreAccountName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Updates the specified Data Lake Analytics account to include the additional /// Data Lake Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to which to add the Data Lake /// Store account. /// </param> /// <param name='dataLakeStoreAccountName'> /// The name of the Data Lake Store account to add. /// </param> /// <param name='parameters'> /// The details of the Data Lake Store account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task AddAsync(this IDataLakeStoreAccountsOperations operations, string resourceGroupName, string accountName, string dataLakeStoreAccountName, AddDataLakeStoreParameters parameters = default(AddDataLakeStoreParameters), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.AddWithHttpMessagesAsync(resourceGroupName, accountName, dataLakeStoreAccountName, parameters, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets the first page of Data Lake Store accounts linked to the specified /// Data Lake Analytics account. The response includes a link to the next page, /// if any. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account for which to list Data Lake /// Store accounts. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='select'> /// OData Select statement. Limits the properties on each entry to just those /// requested, e.g. Categories?$select=CategoryName,Description. Optional. /// </param> /// <param name='count'> /// The Boolean value of true or false to request a count of the matching /// resources included with the resources in the response, e.g. /// Categories?$count=true. Optional. /// </param> public static IPage<DataLakeStoreAccountInfo> ListByAccount(this IDataLakeStoreAccountsOperations operations, string resourceGroupName, string accountName, ODataQuery<DataLakeStoreAccountInfo> odataQuery = default(ODataQuery<DataLakeStoreAccountInfo>), string select = default(string), bool? count = default(bool?)) { return ((IDataLakeStoreAccountsOperations)operations).ListByAccountAsync(resourceGroupName, accountName, odataQuery, select, count).GetAwaiter().GetResult(); } /// <summary> /// Gets the first page of Data Lake Store accounts linked to the specified /// Data Lake Analytics account. The response includes a link to the next page, /// if any. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account for which to list Data Lake /// Store accounts. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='select'> /// OData Select statement. Limits the properties on each entry to just those /// requested, e.g. Categories?$select=CategoryName,Description. Optional. /// </param> /// <param name='count'> /// The Boolean value of true or false to request a count of the matching /// resources included with the resources in the response, e.g. /// Categories?$count=true. Optional. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<DataLakeStoreAccountInfo>> ListByAccountAsync(this IDataLakeStoreAccountsOperations operations, string resourceGroupName, string accountName, ODataQuery<DataLakeStoreAccountInfo> odataQuery = default(ODataQuery<DataLakeStoreAccountInfo>), string select = default(string), bool? count = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAccountWithHttpMessagesAsync(resourceGroupName, accountName, odataQuery, select, count, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the first page of Data Lake Store accounts linked to the specified /// Data Lake Analytics account. The response includes a link to the next page, /// if any. /// </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<DataLakeStoreAccountInfo> ListByAccountNext(this IDataLakeStoreAccountsOperations operations, string nextPageLink) { return operations.ListByAccountNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets the first page of Data Lake Store accounts linked to the specified /// Data Lake Analytics account. The response includes a link to the next page, /// if any. /// </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<DataLakeStoreAccountInfo>> ListByAccountNextAsync(this IDataLakeStoreAccountsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAccountNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/*************************************************************************** * GstPlayerEngine.cs * * Copyright (C) 2005-2006 Novell, Inc. * Written by Aaron Bockover <aaron@abock.org> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Runtime.InteropServices; using Mono.Unix; using Banshee.Base; using Banshee.MediaEngine; using Banshee.Gstreamer; public static class PluginModuleEntry { public static Type [] GetTypes() { return new Type [] { typeof(Banshee.MediaEngine.Gstreamer.GstreamerPlayerEngine) }; } } namespace Banshee.MediaEngine.Gstreamer { internal delegate void GstPlaybackEosCallback(IntPtr engine); internal delegate void GstPlaybackErrorCallback(IntPtr engine, uint domain, int code, IntPtr error, IntPtr debug); internal delegate void GstPlaybackStateChangedCallback(IntPtr engine, int old_state, int new_state, int pending_state); internal delegate void GstPlaybackIterateCallback(IntPtr engine); internal delegate void GstPlaybackBufferingCallback(IntPtr engine, int buffering_progress); internal enum GstCoreError { Failed = 1, TooLazy, NotImplemented, StateChange, Pad, Thread, Negotiation, Event, Seek, Caps, Tag, MissingPlugin, Clock, NumErrors } internal enum GstLibraryError { Failed = 1, Init, Shutdown, Settings, Encode, NumErrors } internal enum GstResourceError { Failed = 1, TooLazy, NotFound, Busy, OpenRead, OpenWrite, OpenReadWrite, Close, Read, Write, Seek, Sync, Settings, NoSpaceLeft, NumErrors } internal enum GstStreamError { Failed = 1, TooLazy, NotImplemented, TypeNotFound, WrongType, CodecNotFound, Decode, Encode, Demux, Mux, Format, NumErrors } public class GstreamerPlayerEngine : PlayerEngine { private uint GST_CORE_ERROR = 0; private uint GST_LIBRARY_ERROR = 0; private uint GST_RESOURCE_ERROR = 0; private uint GST_STREAM_ERROR = 0; private HandleRef handle; private GstPlaybackEosCallback eos_callback; private GstPlaybackErrorCallback error_callback; private GstPlaybackStateChangedCallback state_changed_callback; private GstPlaybackIterateCallback iterate_callback; private GstPlaybackBufferingCallback buffering_callback; private GstTaggerTagFoundCallback tag_found_callback; private bool buffering_finished; public GstreamerPlayerEngine() { IntPtr ptr = gst_playback_new(); if(ptr == IntPtr.Zero) { throw new ApplicationException(Catalog.GetString("Could not initialize GStreamer library")); } handle = new HandleRef(this, ptr); gst_playback_get_error_quarks(out GST_CORE_ERROR, out GST_LIBRARY_ERROR, out GST_RESOURCE_ERROR, out GST_STREAM_ERROR); eos_callback = new GstPlaybackEosCallback(OnEos); error_callback = new GstPlaybackErrorCallback(OnError); state_changed_callback = new GstPlaybackStateChangedCallback(OnStateChanged); iterate_callback = new GstPlaybackIterateCallback(OnIterate); buffering_callback = new GstPlaybackBufferingCallback(OnBuffering); tag_found_callback = new GstTaggerTagFoundCallback(OnTagFound); gst_playback_set_eos_callback(handle, eos_callback); gst_playback_set_iterate_callback(handle, iterate_callback); gst_playback_set_error_callback(handle, error_callback); gst_playback_set_state_changed_callback(handle, state_changed_callback); gst_playback_set_buffering_callback(handle, buffering_callback); gst_playback_set_tag_found_callback(handle, tag_found_callback); } public override void Dispose() { base.Dispose(); gst_playback_free(handle); } public override void Close() { gst_playback_stop(handle); base.Close(); } protected override void OpenUri(SafeUri uri) { IntPtr uri_ptr = GLib.Marshaller.StringToPtrGStrdup(uri.AbsoluteUri); gst_playback_open(handle, uri_ptr); GLib.Marshaller.Free(uri_ptr); } public override void Play() { gst_playback_play(handle); OnStateChanged(PlayerEngineState.Playing); } public override void Pause() { gst_playback_pause(handle); OnStateChanged(PlayerEngineState.Paused); } public override IntPtr [] GetBaseElements() { IntPtr [] elements = new IntPtr[3]; if(gst_playback_get_pipeline_elements(handle, out elements[0], out elements[1], out elements[2])) { return elements; } return null; } private void OnEos(IntPtr engine) { Close(); OnEventChanged(PlayerEngineEvent.EndOfStream); } private void OnIterate(IntPtr engine) { OnEventChanged(PlayerEngineEvent.Iterate); } private void OnError(IntPtr engine, uint domain, int code, IntPtr error, IntPtr debug) { Close(); string error_message = error == IntPtr.Zero ? Catalog.GetString("Unknown Error") : GLib.Marshaller.Utf8PtrToString(error); if(domain == GST_RESOURCE_ERROR) { GstResourceError domain_code = (GstResourceError)code; if(CurrentTrack != null) { switch(domain_code) { case GstResourceError.NotFound: CurrentTrack.PlaybackError = TrackPlaybackError.ResourceNotFound; break; default: break; } } Console.WriteLine("GStreamer resource error: {0}", domain_code); } else if(domain == GST_STREAM_ERROR) { GstStreamError domain_code = (GstStreamError)code; if(CurrentTrack != null) { switch(domain_code) { case GstStreamError.CodecNotFound: CurrentTrack.PlaybackError = TrackPlaybackError.CodecNotFound; break; default: break; } } Console.WriteLine("GStreamer stream error: {0}", domain_code); } else if(domain == GST_CORE_ERROR) { GstCoreError domain_code = (GstCoreError)code; if(CurrentTrack != null) { switch(domain_code) { case GstCoreError.MissingPlugin: CurrentTrack.PlaybackError = TrackPlaybackError.CodecNotFound; break; default: break; } } Console.WriteLine("GStreamer core error: {0}", (GstCoreError)code); } else if(domain == GST_LIBRARY_ERROR) { Console.WriteLine("GStreamer library error: {0}", (GstLibraryError)code); } OnEventChanged(PlayerEngineEvent.Error, error_message); } private void OnStateChanged(IntPtr engine, int new_state, int old_state, int pending_state) { } private void OnBuffering(IntPtr engine, int progress) { if(buffering_finished && progress >= 100) { return; } buffering_finished = progress >= 100; OnEventChanged(PlayerEngineEvent.Buffering, Catalog.GetString("Buffering"), (double)progress / 100.0); } private void OnTagFound(string tagName, ref GLib.Value value, IntPtr userData) { OnTagFound(GstTagger.ProcessNativeTagResult(tagName, ref value)); } public override ushort Volume { get { return (ushort)gst_playback_get_volume(handle); } set { gst_playback_set_volume(handle, (int)value); OnEventChanged(PlayerEngineEvent.Volume); } } public override uint Position { get { return (uint)gst_playback_get_position(handle) / 1000; } set { gst_playback_set_position(handle, (ulong)value * 1000); OnEventChanged(PlayerEngineEvent.Seek); } } public override bool CanSeek { get { return gst_playback_can_seek(handle); } } public override uint Length { get { return (uint)gst_playback_get_duration(handle) / 1000; } } public override string Id { get { return "gstreamer"; } } public override string Name { get { return "GStreamer 0.10"; } } private static string [] source_capabilities = { "file", "http", "cdda" }; public override IEnumerable SourceCapabilities { get { return source_capabilities; } } private static string [] decoder_capabilities = { "ogg", "wma", "asf", "flac" }; public override IEnumerable ExplicitDecoderCapabilities { get { return decoder_capabilities; } } [DllImport("libbanshee")] private static extern IntPtr gst_playback_new(); [DllImport("libbanshee")] private static extern void gst_playback_free(HandleRef engine); [DllImport("libbanshee")] private static extern void gst_playback_set_eos_callback(HandleRef engine, GstPlaybackEosCallback cb); [DllImport("libbanshee")] private static extern void gst_playback_set_error_callback(HandleRef engine, GstPlaybackErrorCallback cb); [DllImport("libbanshee")] private static extern void gst_playback_set_state_changed_callback(HandleRef engine, GstPlaybackStateChangedCallback cb); [DllImport("libbanshee")] private static extern void gst_playback_set_iterate_callback(HandleRef engine, GstPlaybackIterateCallback cb); [DllImport("libbanshee")] private static extern void gst_playback_set_buffering_callback(HandleRef engine, GstPlaybackBufferingCallback cb); [DllImport("libbanshee")] private static extern void gst_playback_set_tag_found_callback(HandleRef engine, GstTaggerTagFoundCallback cb); [DllImport("libbanshee")] private static extern void gst_playback_open(HandleRef engine, IntPtr uri); [DllImport("libbanshee")] private static extern void gst_playback_stop(HandleRef engine); [DllImport("libbanshee")] private static extern void gst_playback_pause(HandleRef engine); [DllImport("libbanshee")] private static extern void gst_playback_play(HandleRef engine); [DllImport("libbanshee")] private static extern void gst_playback_set_volume(HandleRef engine, int volume); [DllImport("libbanshee")] private static extern int gst_playback_get_volume(HandleRef engine); [DllImport("libbanshee")] private static extern bool gst_playback_can_seek(HandleRef engine); [DllImport("libbanshee")] private static extern void gst_playback_set_position(HandleRef engine, ulong time_ms); [DllImport("libbanshee")] private static extern ulong gst_playback_get_position(HandleRef engine); [DllImport("libbanshee")] private static extern ulong gst_playback_get_duration(HandleRef engine); [DllImport("libbanshee")] private static extern bool gst_playback_get_pipeline_elements(HandleRef engine, out IntPtr playbin, out IntPtr audiobin, out IntPtr audiotee); [DllImport("libbanshee")] private static extern void gst_playback_get_error_quarks(out uint core, out uint library, out uint resource, out uint stream); } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace CS2JSWeb.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// // MRWeapon.cs // // Author: // Steve Jakab <> // // Copyright (c) 2014 Steve Jakab // // 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 UnityEngine; using System; using System.Collections; using System.Text; using AssemblyCSharp; namespace PortableRealm { public class MRWeapon : MRItem { #region Constants public enum eWeaponType { Striking, Missile } #endregion #region Properties public int Length { get{ return mLength; } } public bool IsMissile { get{ return mIsMissile; } } public MRGame.eStrength AlertedStrength { get { return mAlertedStrength; } } public MRGame.eStrength UnalertedStrength { get { return mUnalertedStrength; } } public MRGame.eStrength CurrentStrength { get { return Alerted ? mAlertedStrength : mUnalertedStrength; } } public int AlertedSharpness { get{ return mAlertedSharpness; } } public int UnalertedSharpness { get{ return mUnalertedSharpness; } } public int CurrentSharpness { get{ return Alerted ? AlertedSharpness : UnalertedSharpness; } } public int AlertedSpeed { get{ return mAlertedSpeed; } } public int UnalertedSpeed { get{ return mUnalertedSpeed; } } public int CurrentSpeed { get{ return Alerted ? AlertedSpeed : UnalertedSpeed; } } public bool Alerted { get{ return mAlerted; } set{ mAlerted = value; } } public Nullable<MRGame.eNatives> NativeOwner { get{ return mNativeOwner; } set{ mNativeOwner = value; } } public override int SortValue { get{ return (int)MRGame.eSortValue.Weapon; } } #endregion #region Methods public MRWeapon() { } public MRWeapon(JSONObject data, int index) : base((JSONObject)data["MRItem"], index) { mAlerted = false; mLength = ((JSONNumber)data["length"]).IntValue; string strength = ((JSONString)data["astrength"]).Value; if (strength.Length > 0) mAlertedStrength = strength.Strength(); else mAlertedStrength = MRGame.eStrength.Chit; strength = ((JSONString)data["istrength"]).Value; if (strength.Length > 0) mUnalertedStrength = strength.Strength(); else mUnalertedStrength = MRGame.eStrength.Chit; mAlertedSharpness = ((JSONNumber)data["asharp"]).IntValue; mUnalertedSharpness = ((JSONNumber)data["isharp"]).IntValue; mAlertedSpeed = ((JSONNumber)data["aspeed"]).IntValue; mUnalertedSpeed = ((JSONNumber)data["ispeed"]).IntValue; mIsMissile = ((JSONBoolean)data["missile"]).Value; bool isTreasure = ((JSONBoolean)data["treasure"]).Value; mCounter = (GameObject)MRGame.Instantiate(MRGame.TheGame.mediumCounterPrototype); string imageName = ((JSONString)data["image"]).Value; Sprite texture = (Sprite)Resources.Load("Textures/" + imageName, typeof(Sprite)); SpriteRenderer[] sprites = mCounter.GetComponentsInChildren<SpriteRenderer>(); foreach (SpriteRenderer sprite in sprites) { if (sprite.gameObject.name == "FrontSide") { if (isTreasure) sprite.color = MRGame.yellow; else sprite.color = MRGame.offWhite; } else if (sprite.gameObject.name == "BackSide") { if (isTreasure) sprite.color = MRGame.gold; else sprite.color = MRGame.red; } else if (sprite.gameObject.name == "FrontSymbol") { sprite.sprite = texture; } else if (sprite.gameObject.name == "BackSymbol") { sprite.sprite = texture; } } StringBuilder buffer = new StringBuilder(); TextMesh[] texts = mCounter.GetComponentsInChildren<TextMesh>(); foreach (TextMesh text in texts) { if (text.gameObject.name == "FrontText") { buffer.Length = 0; buffer.Append(mUnalertedStrength.ToChitString()); if (mUnalertedSpeed > 0) buffer.Append(mUnalertedSpeed); for (int i = 0; i < mUnalertedSharpness; ++i) buffer.Append("*"); text.text = buffer.ToString(); } else if (text.gameObject.name == "BackText") { buffer.Length = 0; buffer.Append(mAlertedStrength.ToChitString()); if (mAlertedSpeed > 0) buffer.Append(mAlertedSpeed); for (int i = 0; i < mAlertedSharpness; ++i) buffer.Append("*"); text.text = buffer.ToString(); } } } // Update is called once per frame public override void Update () { base.Update(); Vector3 orientation = mCounter.transform.localEulerAngles; if (mAlerted) orientation.y = 180f; else orientation.y = 0; mCounter.transform.localEulerAngles = orientation; } public override bool Load(JSONObject root) { if (!base.Load(root)) return false; if (root["alert"] != null) mAlerted = ((JSONBoolean)root["alert"]).Value; return true; } public override void Save(JSONObject root) { base.Save(root); root["alert"] = new JSONBoolean(mAlerted); } #endregion #region Members private MRGame.eStrength mAlertedStrength; private MRGame.eStrength mUnalertedStrength; private int mAlertedSharpness; private int mUnalertedSharpness; private int mAlertedSpeed; private int mUnalertedSpeed; private int mLength; private bool mIsMissile; private bool mAlerted; private Nullable<MRGame.eNatives> mNativeOwner; #endregion } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // UIPermission.cs // // <OWNER>[....]</OWNER> // namespace System.Security.Permissions { using System; using System.Security; using System.Security.Util; using System.IO; using System.Runtime.Serialization; using System.Reflection; using System.Collections; using System.Globalization; using System.Diagnostics.Contracts; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public enum UIPermissionWindow { // No window use allowed at all. NoWindows = 0x0, // Only allow safe subwindow use (for embedded components). SafeSubWindows = 0x01, // Safe top-level window use only (see specification for details). SafeTopLevelWindows = 0x02, // All windows and all event may be used. AllWindows = 0x03, } [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public enum UIPermissionClipboard { // No clipboard access is allowed. NoClipboard = 0x0, // Paste from the same app domain only. OwnClipboard = 0x1, // Any clipboard access is allowed. AllClipboard = 0x2, } [System.Runtime.InteropServices.ComVisible(true)] [Serializable] sealed public class UIPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission { //------------------------------------------------------ // // PRIVATE STATE DATA // //------------------------------------------------------ private UIPermissionWindow m_windowFlag; private UIPermissionClipboard m_clipboardFlag; //------------------------------------------------------ // // PUBLIC CONSTRUCTORS // //------------------------------------------------------ public UIPermission(PermissionState state) { if (state == PermissionState.Unrestricted) { SetUnrestricted( true ); } else if (state == PermissionState.None) { SetUnrestricted( false ); Reset(); } else { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); } } public UIPermission(UIPermissionWindow windowFlag, UIPermissionClipboard clipboardFlag ) { VerifyWindowFlag( windowFlag ); VerifyClipboardFlag( clipboardFlag ); m_windowFlag = windowFlag; m_clipboardFlag = clipboardFlag; } public UIPermission(UIPermissionWindow windowFlag ) { VerifyWindowFlag( windowFlag ); m_windowFlag = windowFlag; } public UIPermission(UIPermissionClipboard clipboardFlag ) { VerifyClipboardFlag( clipboardFlag ); m_clipboardFlag = clipboardFlag; } //------------------------------------------------------ // // PUBLIC ACCESSOR METHODS // //------------------------------------------------------ public UIPermissionWindow Window { set { VerifyWindowFlag(value); m_windowFlag = value; } get { return m_windowFlag; } } public UIPermissionClipboard Clipboard { set { VerifyClipboardFlag(value); m_clipboardFlag = value; } get { return m_clipboardFlag; } } //------------------------------------------------------ // // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS // //------------------------------------------------------ private static void VerifyWindowFlag(UIPermissionWindow flag) { if (flag < UIPermissionWindow.NoWindows || flag > UIPermissionWindow.AllWindows) { throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)flag)); } Contract.EndContractBlock(); } private static void VerifyClipboardFlag(UIPermissionClipboard flag) { if (flag < UIPermissionClipboard.NoClipboard || flag > UIPermissionClipboard.AllClipboard) { throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)flag)); } Contract.EndContractBlock(); } private void Reset() { m_windowFlag = UIPermissionWindow.NoWindows; m_clipboardFlag = UIPermissionClipboard.NoClipboard; } private void SetUnrestricted( bool unrestricted ) { if (unrestricted) { m_windowFlag = UIPermissionWindow.AllWindows; m_clipboardFlag = UIPermissionClipboard.AllClipboard; } } #if false //------------------------------------------------------ // // OBJECT METHOD OVERRIDES // //------------------------------------------------------ public String ToString() { #if _DEBUG StringBuilder sb = new StringBuilder(); sb.Append("UIPermission("); if (IsUnrestricted()) { sb.Append("Unrestricted"); } else { sb.Append(m_stateNameTableWindow[m_windowFlag]); sb.Append(", "); sb.Append(m_stateNameTableClipboard[m_clipboardFlag]); } sb.Append(")"); return sb.ToString(); #else return super.ToString(); #endif } #endif //------------------------------------------------------ // // CODEACCESSPERMISSION IMPLEMENTATION // //------------------------------------------------------ public bool IsUnrestricted() { return m_windowFlag == UIPermissionWindow.AllWindows && m_clipboardFlag == UIPermissionClipboard.AllClipboard; } //------------------------------------------------------ // // IPERMISSION IMPLEMENTATION // //------------------------------------------------------ public override bool IsSubsetOf(IPermission target) { if (target == null) { // Only safe subset if this is empty return m_windowFlag == UIPermissionWindow.NoWindows && m_clipboardFlag == UIPermissionClipboard.NoClipboard; } try { UIPermission operand = (UIPermission)target; if (operand.IsUnrestricted()) return true; else if (this.IsUnrestricted()) return false; else return this.m_windowFlag <= operand.m_windowFlag && this.m_clipboardFlag <= operand.m_clipboardFlag; } catch (InvalidCastException) { throw new ArgumentException( Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) ); } } public override IPermission Intersect(IPermission target) { if (target == null) { return null; } else if (!VerifyType(target)) { throw new ArgumentException( Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) ); } UIPermission operand = (UIPermission)target; UIPermissionWindow isectWindowFlags = m_windowFlag < operand.m_windowFlag ? m_windowFlag : operand.m_windowFlag; UIPermissionClipboard isectClipboardFlags = m_clipboardFlag < operand.m_clipboardFlag ? m_clipboardFlag : operand.m_clipboardFlag; if (isectWindowFlags == UIPermissionWindow.NoWindows && isectClipboardFlags == UIPermissionClipboard.NoClipboard) return null; else return new UIPermission(isectWindowFlags, isectClipboardFlags); } public override IPermission Union(IPermission target) { if (target == null) { return this.Copy(); } else if (!VerifyType(target)) { throw new ArgumentException( Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) ); } UIPermission operand = (UIPermission)target; UIPermissionWindow isectWindowFlags = m_windowFlag > operand.m_windowFlag ? m_windowFlag : operand.m_windowFlag; UIPermissionClipboard isectClipboardFlags = m_clipboardFlag > operand.m_clipboardFlag ? m_clipboardFlag : operand.m_clipboardFlag; if (isectWindowFlags == UIPermissionWindow.NoWindows && isectClipboardFlags == UIPermissionClipboard.NoClipboard) return null; else return new UIPermission(isectWindowFlags, isectClipboardFlags); } public override IPermission Copy() { return new UIPermission(this.m_windowFlag, this.m_clipboardFlag); } #if FEATURE_CAS_POLICY public override SecurityElement ToXml() { SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.UIPermission" ); if (!IsUnrestricted()) { if (m_windowFlag != UIPermissionWindow.NoWindows) { esd.AddAttribute( "Window", Enum.GetName( typeof( UIPermissionWindow ), m_windowFlag ) ); } if (m_clipboardFlag != UIPermissionClipboard.NoClipboard) { esd.AddAttribute( "Clipboard", Enum.GetName( typeof( UIPermissionClipboard ), m_clipboardFlag ) ); } } else { esd.AddAttribute( "Unrestricted", "true" ); } return esd; } public override void FromXml(SecurityElement esd) { CodeAccessPermission.ValidateElement( esd, this ); if (XMLUtil.IsUnrestricted( esd )) { SetUnrestricted( true ); return; } m_windowFlag = UIPermissionWindow.NoWindows; m_clipboardFlag = UIPermissionClipboard.NoClipboard; String window = esd.Attribute( "Window" ); if (window != null) m_windowFlag = (UIPermissionWindow)Enum.Parse( typeof( UIPermissionWindow ), window ); String clipboard = esd.Attribute( "Clipboard" ); if (clipboard != null) m_clipboardFlag = (UIPermissionClipboard)Enum.Parse( typeof( UIPermissionClipboard ), clipboard ); } #endif // FEATURE_CAS_POLICY /// <internalonly/> int IBuiltInPermission.GetTokenIndex() { return UIPermission.GetTokenIndex(); } internal static int GetTokenIndex() { return BuiltInPermissionIndex.UIPermissionIndex; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Controls.Primitives; using System.Windows.Media; using Xwt.Accessibility; using Xwt.Backends; namespace Xwt.WPFBackend { partial class AccessibleBackend : IAccessibleBackend { UIElement element; IAccessibleEventSink eventSink; ApplicationContext context; IList<object> nativeChildren = new List<object> (); public bool IsAccessible { get; set; } private string identifier; public string Identifier { get { return AutomationProperties.GetAutomationId (element); } set { identifier = value; AutomationProperties.SetAutomationId (element, value); } } private string label; public string Label { get { return AutomationProperties.GetName (element); } set { label = value; AutomationProperties.SetName (element, value); } } private string description; public string Description { get { return AutomationProperties.GetHelpText (element); } set { description = value; AutomationProperties.SetHelpText (element, value); } } private Widget labelWidget; public Widget LabelWidget { set { labelWidget = value; AutomationProperties.SetLabeledBy (element, (Toolkit.GetBackend (value) as WidgetBackend)?.Widget); } } /// <summary> /// In some cases (just Popovers currently) we need to wait to set the automation properties until the element /// that needs them comes into existence (a PopoverRoot in the case of a Popover, when it's shown). This is /// used for that delayed initialization. /// </summary> /// <param name="element">UIElement on which to set the properties</param> public void InitAutomationProperties (UIElement element) { if (identifier != null) AutomationProperties.SetAutomationId (element, identifier); if (label != null) AutomationProperties.SetName (element, label); if (description != null) AutomationProperties.SetHelpText (element, description); if (labelWidget != null) AutomationProperties.SetLabeledBy (element, (Toolkit.GetBackend (labelWidget) as WidgetBackend)?.Widget); } public string Title { get; set; } public string Value { get; set; } public Role Role { get; set; } = Role.Custom; public Uri Uri { get; set; } public Rectangle Bounds { get; set; } public string RoleDescription { get; set; } public void DisableEvent (object eventId) { } public void EnableEvent (object eventId) { } public void Initialize (IWidgetBackend parentWidget, IAccessibleEventSink eventSink) { if (parentWidget.NativeWidget is WpfLabel) Initialize (((WpfLabel)parentWidget.NativeWidget).TextBlock, eventSink); else Initialize (parentWidget.NativeWidget, eventSink); var wpfBackend = parentWidget as WidgetBackend; if (wpfBackend != null) wpfBackend.HasAccessibleObject = true; } public void Initialize (IPopoverBackend parentPopover, IAccessibleEventSink eventSink) { var popoverBackend = (PopoverBackend) parentPopover; Popup popup = popoverBackend.NativeWidget; Initialize (popup, eventSink); } public void Initialize(IMenuBackend parentMenu, IAccessibleEventSink eventSync) { var menuBackend = (MenuBackend)parentMenu; // If the menu hasn't been creaetd yet (true for ContextMenus, generally created on demand // when displayed), then instead set the a11y properties on the DummyAccessibilityUIElement; // they'll be copied to the actual menu later when it's created if (menuBackend.NativeMenu != null) Initialize(menuBackend.NativeMenu, eventSink); else if (menuBackend.DummyAccessibilityUIElement != null) Initialize (menuBackend.DummyAccessibilityUIElement, eventSink); } public void Initialize (IMenuItemBackend parentMenuItem, IAccessibleEventSink eventSink) { var menuItemBackend = (MenuItemBackend)parentMenuItem; Initialize (menuItemBackend.MenuItem, eventSink); } public void Initialize (object parentWidget, IAccessibleEventSink eventSink) { this.element = parentWidget as UIElement; if (element == null) throw new ArgumentException ("Widget is not a UIElement"); this.eventSink = eventSink; } public void InitializeBackend (object frontend, ApplicationContext context) { this.context = context; } internal void PerformInvoke () { context.InvokeUserCode (() => eventSink.OnPress ()); } // The following child methods are only supported for Canvas based widgets public void AddChild (object nativeChild) { if (element is CustomCanvas && nativeChild is AutomationPeer) ((CustomCanvas)element).AutomationPeer?.AddChild ((AutomationPeer)nativeChild); else nativeChildren.Add (nativeChild); } public void RemoveAllChildren () { if (element is CustomCanvas) ((CustomCanvas)element).AutomationPeer?.RemoveAllChildren (); else nativeChildren.Clear (); } public void RemoveChild (object nativeChild) { if (element is CustomCanvas && nativeChild is AutomationPeer) ((CustomCanvas)element).AutomationPeer?.RemoveChild ((AutomationPeer)nativeChild); else nativeChildren.Remove (nativeChild); } public IEnumerable<object> GetChildren () { if (element is CustomCanvas) return ((CustomCanvas)element).AutomationPeer.GetChildren (); else return nativeChildren; } public static AutomationControlType RoleToControlType (Role role) { switch (role) { case Role.Button: case Role.MenuButton: case Role.ToggleButton: return AutomationControlType.Button; case Role.CheckBox: return AutomationControlType.CheckBox; case Role.RadioButton: return AutomationControlType.RadioButton; case Role.RadioGroup: return AutomationControlType.Group; case Role.ComboBox: return AutomationControlType.ComboBox; case Role.List: return AutomationControlType.List; case Role.Popup: case Role.ToolTip: return AutomationControlType.ToolTip; case Role.ToolBar: return AutomationControlType.ToolBar; case Role.Label: return AutomationControlType.Text; case Role.Link: return AutomationControlType.Hyperlink; case Role.Image: return AutomationControlType.Image; case Role.Cell: return AutomationControlType.DataItem; case Role.Table: return AutomationControlType.DataGrid; case Role.Paned: return AutomationControlType.Pane; default: return AutomationControlType.Custom; } } } }
using UnityEditor; using UnityEngine; using System.Collections.Generic; using MORPH3D.COSTUMING; using MORPH3D.CONSTANTS; using MORPH3D; using System; using MORPH3D.FOUNDATIONS; namespace MORPH3D.EDITORS { /// <summary> /// Used internally to check for updates triggered by a user in the editor for a blendshape /// </summary> public struct EditorMorphState { public float value; public bool attached; public bool dirty; public bool dirtyValue; public bool dirtyAttached; } [CustomEditor (typeof(M3DCharacterManager))] public class M3DCharacterManagerEditor : Editor { protected M3DCharacterManager charMan = null; protected bool showMorphs = false; //internally used for the twirl down of "Morphs" in the inspector panel protected bool showContentPacks = false; protected bool showAllClothing = false; protected bool showAllClothingGroups = false; protected bool[] showClothingGroups = null; protected int selectedClothingName = 0; protected string selectedBlendShape = ""; protected bool showMorphTypeGroups = false; protected bool showAttachmentPoints = false; protected bool[] showAttachmentPointsGroups = null; protected string[] selectedPropsNames = null; protected string selectedNewAttachmentPointName = ""; protected bool showHair = false; protected bool showAdvanced = false; public override void OnInspectorGUI() { #region just_stuff serializedObject.Update (); if(charMan == null) charMan = (M3DCharacterManager)target; if(charMan == null || !charMan.isAwake) { GUILayout.Label("Your figure must be in the scene to edit settings"); return; } GUIStyle m3dDefaultButtonStyle = new GUIStyle(GUI.skin.button); m3dDefaultButtonStyle.margin = new RectOffset(10,10,5,5); m3dDefaultButtonStyle.padding = new RectOffset(5, 5, 5, 5); #endregion just_stuff #region LOD float lod; lod = EditorGUILayout.Slider("LOD", charMan.currentLODLevel, 0, 1); if(lod != charMan.currentLODLevel) { Undo.RecordObject(charMan, "Change LOD"); charMan.SetLODLevel(lod); EditorUtility.SetDirty(charMan); } EditorGUILayout.Space(); #endregion LOD #region morphs showMorphs = EditorGUILayout.Foldout(showMorphs, "Morphs"); if (showMorphs) { //SerializedObject so = new SerializedObject(charMan.coreMorphs); //so.Update(); charMan.coreMorphs.SortIfNeeded(); EditorGUI.indentLevel++; GUILayout.BeginHorizontal(); selectedBlendShape = GUILayout.TextField(selectedBlendShape, GUI.skin.FindStyle("ToolbarSeachTextField")); if (GUILayout.Button("", GUI.skin.FindStyle("ToolbarSeachCancelButton"))) { selectedBlendShape = ""; GUI.FocusControl(null); } GUILayout.EndHorizontal(); EditorGUILayout.Space(); if (GUILayout.Button("Reset All", m3dDefaultButtonStyle)) { Undo.RecordObject(charMan, "Change Morph"); for (int i = 0; i < charMan.coreMorphs.morphs.Count; i++) { if (charMan.coreMorphs.morphs[i].attached) { charMan.SetBlendshapeValue(charMan.coreMorphs.morphs[i].name, 0); } } EditorUtility.SetDirty(charMan); } EditorGUILayout.Space(); if (GUILayout.Button("Detach All", m3dDefaultButtonStyle)) { Undo.RecordObject(charMan, "Detach All Morphs"); charMan.RemoveAllMorphs(); EditorUtility.SetDirty(charMan); } EditorGUILayout.Space(); List<MORPH3D.FOUNDATIONS.Morph> dirtyMorphValues = new List<MORPH3D.FOUNDATIONS.Morph>(); List<MORPH3D.FOUNDATIONS.Morph> dirtyMorphAttachments = new List<MORPH3D.FOUNDATIONS.Morph>(); List<MORPH3D.FOUNDATIONS.Morph> dirtyMorphDettachments = new List<MORPH3D.FOUNDATIONS.Morph>(); EditorMorphs(charMan.coreMorphs.morphs, dirtyMorphValues, dirtyMorphAttachments, dirtyMorphDettachments); if (dirtyMorphDettachments.Count > 0 || dirtyMorphAttachments.Count > 0 || dirtyMorphValues.Count > 0) { Undo.RecordObject(charMan.coreMorphs, "Change Morph"); charMan.coreMorphs.DettachMorphs(dirtyMorphDettachments.ToArray()); charMan.coreMorphs.AttachMorphs(dirtyMorphAttachments.ToArray(), false, false, null); charMan.coreMorphs.SyncMorphValues(dirtyMorphValues.ToArray(), null); charMan.SyncAllBlendShapes(); //so.ApplyModifiedProperties(); EditorUtility.SetDirty(charMan.coreMorphs); } EditorGUILayout.Space(); EditorGUI.indentLevel--; } #endregion #region Morph Groups var body = charMan.gameObject.GetComponentInChildren<CIbody>(); var morphTypeGroup = MorphGroupService.GetMorphGroups(body.dazName); if (morphTypeGroup != null) { showMorphTypeGroups = EditorGUILayout.Foldout(showMorphTypeGroups, "Morph Groups"); if (showMorphTypeGroups) { charMan.coreMorphs.SortIfNeeded(); EditorGUI.indentLevel++; foreach (var group in morphTypeGroup.SubGroups.Values) { ShowMorphTypeGroup(group); } EditorGUI.indentLevel--; } } #endregion #region contentPacks showContentPacks = EditorGUILayout.Foldout (showContentPacks, "Content Packs"); if(showContentPacks) { EditorGUI.indentLevel++; List<ContentPack> allPacks = charMan.GetAllContentPacks(); for(int i = 0; i < allPacks.Count; i++) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(allPacks[i].name); if(GUILayout.Button("X")) { Undo.RecordObject(charMan, "Remove Bundle"); charMan.RemoveContentPack(allPacks[i]); EditorUtility.SetDirty(charMan); } EditorGUILayout.EndHorizontal(); } /* CostumeItem tempPack = null; tempPack = (CostumeItem)EditorGUILayout.ObjectField("New", tempPack, typeof(CostumeItem), true); if(tempPack != null) { ContentPack packScript = new ContentPack(tempPack.gameObject); Undo.RecordObject(charMan, "Add Bundle"); charMan.AddContentPack(packScript); EditorUtility.SetDirty(charMan); } */ GameObject tempPack = null; tempPack = (GameObject)EditorGUILayout.ObjectField("New", tempPack, typeof(GameObject), true); if(tempPack != null) { string tPPath = AssetDatabase.GetAssetPath(tempPack); if (tPPath.EndsWith(".fbx")) { //if we dropped an fbx, try replacing it with a matching .prefab instead tPPath = tPPath.Replace(".fbx", ".prefab"); GameObject prefabObj = AssetDatabase.LoadAssetAtPath<GameObject>(tPPath); if(prefabObj != null) { tempPack = prefabObj; } } ContentPack packScript = new ContentPack(tempPack,false); Undo.RecordObject(charMan, "Add Bundle"); charMan.AddContentPack(packScript); EditorUtility.SetDirty(charMan); } if(GUILayout.Button("Import Selected From Project Pane", m3dDefaultButtonStyle)) { string[] guids = Selection.assetGUIDs; List<string> paths = new List<string>(); foreach(string guid in guids) { string path = AssetDatabase.GUIDToAssetPath(guid); if (System.IO.Directory.Exists(path)) { string[] prefabPaths = System.IO.Directory.GetFiles(path, "*.prefab", System.IO.SearchOption.AllDirectories); for(int i = 0; i < prefabPaths.Length; i++) { string dirtyPath = prefabPaths[i]; dirtyPath = dirtyPath.Replace(@"\", "/"); paths.Add(dirtyPath); } } } foreach (string path in paths) { if (path.EndsWith(".prefab")) { GameObject go = AssetDatabase.LoadAssetAtPath<GameObject>(path); CostumeItem ci = go.GetComponent<CostumeItem>(); if (ci != null) { ContentPack packScript = new ContentPack(go, false); Undo.RecordObject(charMan, "Add Bundle"); charMan.AddContentPack(packScript); EditorUtility.SetDirty(charMan); } } } } if(GUILayout.Button("Clear Lingering Content Packs", m3dDefaultButtonStyle)) { charMan.RemoveRogueContent(); } EditorGUI.indentLevel--; } EditorGUILayout.Space(); #endregion contentPacks #region hair showHair = EditorGUILayout.Foldout (showHair, "Hair"); if(showHair) { EditorGUI.indentLevel++; List<MORPH3D.COSTUMING.CIhair> allHair = charMan.GetAllHair(); foreach(MORPH3D.COSTUMING.CIhair mesh in allHair) { if(DisplayHair(mesh)) { Undo.RecordObject(charMan, "Toggle Hair"); mesh.SetVisibility(!mesh.isVisible); // data.SetVisibilityOnHairItem(mesh.ID, !mesh.isVisible); EditorUtility.SetDirty(charMan); } } EditorGUI.indentLevel--; } EditorGUILayout.Space(); #endregion hair #region clothing showAllClothing = EditorGUILayout.Foldout (showAllClothing, "Clothing"); if(showAllClothing) { EditorGUI.indentLevel++; List<CIclothing> allClothing = null; allClothing = charMan.GetAllClothing(); foreach(CIclothing mesh in allClothing) { // bool tempLock; bool temp = DisplayClothingMesh(mesh); // if(tempLock != mesh.isLocked) // { // Undo.RecordObject(data, "Lock Clothing"); // if(tempLock) // data.LockClothingItem(mesh.ID); // else // data.UnlockClothingItem(mesh.ID); // EditorUtility.SetDirty(data); // } if(temp) { Undo.RecordObject(charMan, "Toggle Clothing"); charMan.SetClothingVisibility(mesh.ID, !mesh.isVisible); EditorUtility.SetDirty(charMan); } } EditorGUI.indentLevel--; } EditorGUILayout.Space(); #endregion clothing #region props CIattachmentPoint[] attachmentPoints = charMan.GetAllAttachmentPoints(); // Debug.Log("AP LENGTH:"+attachmentPoints.Length); if(showAttachmentPointsGroups == null || showAttachmentPointsGroups.Length != attachmentPoints.Length) showAttachmentPointsGroups = new bool[attachmentPoints.Length]; /* if(selectedProps == null || selectedProps.Length != attachmentPoints.Length) selectedProps = new int[attachmentPoints.Length]; */ if(selectedPropsNames == null || selectedPropsNames.Length != attachmentPoints.Length) selectedPropsNames = new string[attachmentPoints.Length]; List<CIprop> props = charMan.GetAllLoadedProps(); Dictionary<string, string> idToName = new Dictionary<string, string>(); string[] propsNames = new string[]{}; if(props != null){ propsNames = new string[props.Count]; } for (int i = 0; i < propsNames.Length; i++) { propsNames[i] = props[i].dazName + "|" + props[i].ID; idToName[props[i].ID] = props[i].dazName; } showAttachmentPoints = EditorGUILayout.Foldout (showAttachmentPoints, "Attachment Points"); if(showAttachmentPoints) { int deleteAttachment = -1; EditorGUI.indentLevel++; for(int i = 0; i < attachmentPoints.Length; i++) { EditorGUILayout.BeginHorizontal(); showAttachmentPointsGroups[i] = EditorGUILayout.Foldout (showAttachmentPointsGroups[i], attachmentPoints[i].attachmentPointName); GUILayout.FlexibleSpace(); if(GUILayout.Button("X", GUILayout.Width(45))) deleteAttachment = i; GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); if(showAttachmentPointsGroups[i]) { EditorGUI.indentLevel++; CIprop[] activeProps = attachmentPoints[i].getAttachmentArray(); int destroyProp = -1; for(int x = 0; x < activeProps.Length; x++) { if(DisplayProp(activeProps[x])) destroyProp = x; } if(destroyProp >= 0) { Undo.RecordObject(charMan, "Destroy Prop"); charMan.DetachPropFromAttachmentPoint(activeProps[destroyProp].ID, attachmentPoints[i].attachmentPointName); EditorUtility.SetDirty(charMan); } // Debug.Log("GF"); if(propsNames.Length > 0) { // Debug.Log("FDFG"); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); string propDisplay = !string.IsNullOrEmpty(selectedPropsNames[i]) ? idToName[selectedPropsNames[i]] : null; EditorGUILayout.LabelField("Add Prop:", GUILayout.Width(150)); EditorGUILayout.LabelField(propDisplay, GUILayout.Width(150)); if(selectedPropsNames[i] != "" && selectedPropsNames[i] != null && charMan.GetLoadedPropByName(selectedPropsNames[i]) == null) selectedPropsNames[i] = ""; if(GUILayout.Button("Search")) { int num = i; SearchableWindow.Init(delegate(string newName) { string id = newName; int pos = newName.LastIndexOf('|'); if (pos >= 0) { id = newName.Substring(pos + 1); } selectedPropsNames[num] = id; }, propsNames); } if(selectedPropsNames[i] != "" && selectedPropsNames[i] != null && GUILayout.Button("Add")) { Undo.RecordObject(charMan, "Attach Prop"); //UnityEngine.Debug.Log("Prop:" + selectedPropsNames[i]); charMan.AttachPropToAttachmentPoint(selectedPropsNames[i], attachmentPoints[i].attachmentPointName); EditorUtility.SetDirty(charMan); selectedPropsNames[i] = ""; } GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); /* EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); selectedProps[i] = EditorGUILayout.Popup (selectedProps[i], propsNames, GUILayout.Width(150)); if(GUILayout.Button("Add")) { Undo.RecordObject(data, "Attach Prop"); data.AttachPropToAttachmentPoint(propsNames[selectedProps[i]], attachmentPoints[i].attachmentPointName); EditorUtility.SetDirty(data); selectedProps[i] = 0; } GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); */ } EditorGUILayout.Space(); EditorGUI.indentLevel--; } } if(deleteAttachment >= 0) { Undo.RecordObject(attachmentPoints[deleteAttachment], "Delete Attachment Point"); charMan.DeleteAttachmentPoint(attachmentPoints[deleteAttachment].attachmentPointName); } EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("New Point:", GUILayout.Width(150)); EditorGUILayout.LabelField(selectedNewAttachmentPointName, GUILayout.Width(150)); Transform tempBone = charMan.GetBoneByName (selectedNewAttachmentPointName); if(selectedNewAttachmentPointName != "" && selectedNewAttachmentPointName != null && tempBone == null) selectedNewAttachmentPointName = ""; if(GUILayout.Button("Search")) { SearchableWindow.Init(delegate(string newName) { selectedNewAttachmentPointName = newName; }, charMan.GetAllBonesNames()); } if(selectedNewAttachmentPointName != "" && selectedNewAttachmentPointName != null && tempBone != null && GUILayout.Button("Add")) { Undo.RecordObject(tempBone.gameObject, "New Attachment Point"); charMan.CreateAttachmentPointOnBone(selectedNewAttachmentPointName, null); selectedNewAttachmentPointName = ""; } GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); /* EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); selectedNewAttachmentPointName = EditorGUILayout.TextField("New Point Bone Name", selectedNewAttachmentPointName); if(GUILayout.Button("Add") && selectedNewAttachmentPointName != "") { Transform bone = data.boneService.getBoneByName (selectedNewAttachmentPointName); if(bone != null) { Undo.RecordObject(bone.gameObject, "New Attachment Point"); data.CreateAttachmentPointOnBone(selectedNewAttachmentPointName); } selectedNewAttachmentPointName = ""; } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); selectedNewAttachmentPoint = (GameObject)EditorGUILayout.ObjectField("New Attachemnt Point", selectedNewAttachmentPoint, typeof(GameObject), true); if(selectedNewAttachmentPoint != null && !selectedNewAttachmentPoint.activeInHierarchy) selectedNewAttachmentPoint = null; if(GUILayout.Button("Add") && selectedNewAttachmentPoint != null) { if(selectedNewAttachmentPoint.GetComponent<CIattachmentPoint>() == null) { Undo.RecordObject(selectedNewAttachmentPoint, "New Attachment Point"); data.CreateAttachmentPointFromGameObject(selectedNewAttachmentPoint); } selectedNewAttachmentPoint = null; } EditorGUILayout.EndHorizontal(); */ EditorGUI.indentLevel--; } EditorGUILayout.Space(); #endregion props #region advanced showAdvanced = EditorGUILayout.Foldout(showAdvanced, "Advanced"); if (showAdvanced) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Recalculate Bounds Frequency"); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); List<BoundsOptionsIndex> boundsOptions = new List<BoundsOptionsIndex>(); boundsOptions.Add(new BoundsOptionsIndex(0, COSTUME_BOUNDS_UPDATE_FREQUENCY.NEVER, null)); boundsOptions.Add(new BoundsOptionsIndex(1, COSTUME_BOUNDS_UPDATE_FREQUENCY.ON_ATTACH, null)); boundsOptions.Add(new BoundsOptionsIndex(2, COSTUME_BOUNDS_UPDATE_FREQUENCY.ON_MORPH, null)); int currentSlot = 0; string[] boundsOptionsText = new string[boundsOptions.Count]; for(int i = 0; i < boundsOptions.Count; i++) { if(boundsOptions[i].frequency == charMan.CostumeBoundsUpdateFrequency) { currentSlot = i; } boundsOptionsText[i] = boundsOptions[i].display; } Undo.RecordObject(charMan, "Alter Bounds Frequency"); int boundsSlot = EditorGUILayout.Popup(currentSlot, boundsOptionsText); charMan.CostumeBoundsUpdateFrequency = boundsOptions[boundsSlot].frequency; EditorUtility.SetDirty(charMan); EditorGUILayout.EndHorizontal(); //We're not quite ready to support this w/o having documentation about it /* if (charMan.alphaInjection != null) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Alpha Injection"); EditorGUILayout.EndHorizontal(); if (GUILayout.Button("Force Current Mats into Buffer (use non-instanced mats)", m3dDefaultButtonStyle)) { Undo.RecordObject(charMan.alphaInjection, "Force Update AI"); charMan.alphaInjection.ForceCurrentMaterialsIntoOriginals(); EditorUtility.SetDirty(charMan.alphaInjection); } } */ } #endregion } #region morphs_display public void ShowMorphTypeGroup(FOUNDATIONS.MorphGroup group) { group.IsOpenInEditor = EditorGUILayout.Foldout(group.IsOpenInEditor, group.Key); if (group.IsOpenInEditor) { EditorGUI.indentLevel++; foreach (var key in group.SubGroups.Keys) { ShowMorphTypeGroup(group.SubGroups[key]); } Predicate<FOUNDATIONS.Morph> morphIsInThisGroup = (morph) => group.Morphs.ContainsKey(morph.name); var morphs = charMan.coreMorphs.morphs.FindAll(morphIsInThisGroup); EditorMorphs(morphs); EditorGUI.indentLevel--; } } protected void EditorMorphs(List<FOUNDATIONS.Morph> morphs) { List<FOUNDATIONS.Morph> dirtyMorphValues = new List<FOUNDATIONS.Morph>(); List<FOUNDATIONS.Morph> dirtyMorphAttachments = new List<FOUNDATIONS.Morph>(); List<FOUNDATIONS.Morph> dirtyMorphDettachments = new List<FOUNDATIONS.Morph>(); EditorMorphs(morphs, dirtyMorphValues, dirtyMorphAttachments, dirtyMorphDettachments); if (dirtyMorphDettachments.Count > 0 || dirtyMorphAttachments.Count > 0 || dirtyMorphValues.Count > 0) { charMan.coreMorphs.DettachMorphs(dirtyMorphDettachments.ToArray()); charMan.coreMorphs.AttachMorphs(dirtyMorphAttachments.ToArray(), false, false, null); charMan.coreMorphs.SyncMorphValues(dirtyMorphValues.ToArray(), null); charMan.SyncAllBlendShapes(); } } protected void EditorMorphs(List<MORPH3D.FOUNDATIONS.Morph> morphs, List<MORPH3D.FOUNDATIONS.Morph> dirtyMorphValues, List<MORPH3D.FOUNDATIONS.Morph> dirtyMorphAttachments, List<MORPH3D.FOUNDATIONS.Morph> dirtyMorphDettachments) { string searchKey = null; if (!String.IsNullOrEmpty(selectedBlendShape)) { searchKey = selectedBlendShape.ToLower(); } for (int i = 0; i < morphs.Count; i++) { MORPH3D.FOUNDATIONS.Morph morph = morphs[i]; if (!String.IsNullOrEmpty(selectedBlendShape)) { if(!morph.name.ToLower().Contains(searchKey) && !morph.displayName.ToLower().Contains(searchKey) && !morph.localName.ToLower().Contains(searchKey)) { continue; } } EditorMorphState ems = HandleEditorMorphState(morph); if (ems.dirty) { //we need to update this morph if (ems.dirtyAttached) { if (ems.attached) { morph.attached = true; dirtyMorphAttachments.Add(morph); } else { morph.attached = false; dirtyMorphDettachments.Add(morph); } } if (ems.dirtyValue) { morph.value = ems.value; if (!morph.attached && ems.value > 0f) { //if it wasn't attached and the slider is not 0 attach it morph.attached = true; dirtyMorphAttachments.Add(morph); } dirtyMorphValues.Add(morph); } //replace the object with our modified one, why doesn't c# support references for local vars.... this is stupid morphs[i] = morph; //Debug.Log("Morph: " + morph.name + " | " + morph.value + " | " + data.coreMorphs.morphs[i].value + " | " + (ems.dirtyValue ? " DIRTY VALUE " : "") + (ems.dirtyAttached ? " DIRTY ATTACH " : "") ); } } } ///// <summary> ///// Renders the Morph Panel ///// </summary> //protected void HandleMorphsPane() //{ // List<MORPH3D.FOUNDATIONS.Morph> dirtyMorphValues = new List<MORPH3D.FOUNDATIONS.Morph>(); // List<MORPH3D.FOUNDATIONS.Morph> dirtyMorphAttachments = new List<MORPH3D.FOUNDATIONS.Morph>(); // List<MORPH3D.FOUNDATIONS.Morph> dirtyMorphDettachments = new List<MORPH3D.FOUNDATIONS.Morph>(); // for (int i = 0; i < charMan.coreMorphs.morphs.Count; i++) // { // if (selectedBlendShape != "" && // charMan.coreMorphs.morphs[i].displayName.IndexOf(selectedBlendShape, StringComparison.OrdinalIgnoreCase) < 0) // { // continue; // } // MORPH3D.FOUNDATIONS.Morph morph = charMan.coreMorphs.morphs[i]; // EditorMorphState ems = HandleEditorMorphState(morph); // if (ems.dirty) // { // //we need to update this morph // if (ems.dirtyAttached) // { // if (ems.attached) // { // morph.attached = true; // dirtyMorphAttachments.Add(morph); // } // else // { // morph.attached = false; // dirtyMorphDettachments.Add(morph); // } // } // if (ems.dirtyValue) // { // morph.value = ems.value; // if(!morph.attached && ems.value > 0f) // { // //if it wasn't attached and the slider is not 0 attach it // morph.attached = true; // dirtyMorphAttachments.Add(morph); // } // dirtyMorphValues.Add(morph); // } // //replace the object with our modified one, why doesn't c# support references for local vars.... this is stupid // charMan.coreMorphs.morphs[i] = morph; // //Debug.Log("Morph: " + morph.name + " | " + morph.value + " | " + data.coreMorphs.morphs[i].value + " | " + (ems.dirtyValue ? " DIRTY VALUE " : "") + (ems.dirtyAttached ? " DIRTY ATTACH " : "") ); // } // } // if (dirtyMorphDettachments.Count > 0 || dirtyMorphAttachments.Count > 0 || dirtyMorphValues.Count > 0) // { // charMan.coreMorphs.DettachMorphs(dirtyMorphDettachments.ToArray()); // charMan.coreMorphs.AttachMorphs(dirtyMorphAttachments.ToArray()); // charMan.coreMorphs.SyncMorphValues(dirtyMorphValues.ToArray()); // charMan.SyncAllBlendShapes(); // } //} protected EditorMorphState HandleEditorMorphState(MORPH3D.FOUNDATIONS.Morph morph) { EditorMorphState ems = new EditorMorphState(); ems.dirty = false; GUILayoutOption[] optionsLabel = new GUILayoutOption[] { GUILayout.MaxWidth(200.0f), GUILayout.MinWidth(25.0f), GUILayout.ExpandWidth(false) }; GUILayoutOption[] optionsSlider = new GUILayoutOption[] { GUILayout.ExpandWidth(true) }; GUILayoutOption[] optionsKey = new GUILayoutOption[] { GUILayout.MaxWidth(200.0f), GUILayout.MinWidth(0.0f), GUILayout.Height(EditorGUIUtility.singleLineHeight) }; GUILayoutOption[] optionsToggle = new GUILayoutOption[] { GUILayout.Width(40f), GUILayout.ExpandWidth(false) }; EditorGUILayout.BeginHorizontal(); //Show the slider between 0% and 100% for the morph EditorGUILayout.LabelField(morph.displayName, optionsLabel); ems.value = EditorGUILayout.Slider(morph.value, 0f, 100f, optionsSlider); //Show the checkbox for if this morph should be installed to the figure/mesh ems.attached = EditorGUILayout.Toggle(morph.attached, optionsToggle); //most efficient way, but not necessarily the most accurate way //ems.attached = EditorGUILayout.Toggle(charMan.coreMorphs.morphGroups["Attached"].Contains(morph)); //most accurate way but not O(1); //has a property changed? if (ems.attached != morph.attached) { ems.dirtyAttached = true; ems.dirty = true; } if (Mathf.Abs(ems.value - morph.value) > 0.001f) { ems.dirtyValue = true; ems.dirty = true; } EditorGUILayout.SelectableLabel(morph.localName, EditorStyles.textField, optionsKey); EditorGUILayout.EndHorizontal(); return ems; } #endregion #region clothing_display protected bool DisplayClothingMesh(MORPH3D.COSTUMING.CIclothing mesh) { bool result; EditorGUILayout.BeginHorizontal(); string labelStr = String.IsNullOrEmpty(mesh.name) ? mesh.ID : mesh.name; EditorGUILayout.LabelField (labelStr, GUILayout.Width(150)); if(mesh.isVisible) GUILayout.Space (60); result = GUILayout.Button ((mesh.isVisible) ? "Disable" : "Enable", GUILayout.Width(60)); if(!mesh.isVisible) GUILayout.Space (60); // if (mesh.isVisible) // lockItem = EditorGUILayout.Toggle (mesh.isLocked); // else // lockItem = mesh.isLocked; EditorGUILayout.EndHorizontal(); return result; } #endregion clothing_display #region props_display protected bool DisplayProp(MORPH3D.COSTUMING.CIprop prop) { bool result; EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField (prop.dazName, GUILayout.Width(180)); GUILayout.Space (60); result = GUILayout.Button ("Disable", GUILayout.Width(60)); EditorGUILayout.EndHorizontal(); return result; } #endregion props_display #region hair_display protected bool DisplayHair(MORPH3D.COSTUMING.CIhair mesh) { bool result; EditorGUILayout.BeginHorizontal(); string labelStr = String.IsNullOrEmpty(mesh.name) ? mesh.ID : mesh.name; EditorGUILayout.LabelField (labelStr, GUILayout.Width(150)); if(mesh.isVisible) GUILayout.Space (60); result = GUILayout.Button ((mesh.isVisible) ? "Disable" : "Enable", GUILayout.Width(60)); if(!mesh.isVisible) GUILayout.Space (60); EditorGUILayout.EndHorizontal(); return result; } #endregion hair_display protected struct BoundsOptionsIndex { public int index; public COSTUME_BOUNDS_UPDATE_FREQUENCY frequency; public string display; public BoundsOptionsIndex(int index, COSTUME_BOUNDS_UPDATE_FREQUENCY frequency, string display) { this.index = index; this.frequency = frequency; this.display = display == null ? frequency.ToString() : display; } } } }
/* * [The "BSD license"] * Copyright (c) 2013 Terence Parr * Copyright (c) 2013 Sam Harwell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using Antlr4.Runtime.Atn; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Sharpen; namespace Antlr4.Runtime.Atn { #pragma warning disable 0659 // 'class' overrides Object.Equals(object o) but does not override Object.GetHashCode() public class ArrayPredictionContext : PredictionContext { [NotNull] public readonly PredictionContext[] parents; [NotNull] public readonly int[] returnStates; internal ArrayPredictionContext(PredictionContext[] parents, int[] returnStates) : base(CalculateHashCode(parents, returnStates)) { System.Diagnostics.Debug.Assert(parents.Length == returnStates.Length); System.Diagnostics.Debug.Assert(returnStates.Length > 1 || returnStates[0] != EmptyFullStateKey, "Should be using PredictionContext.EMPTY instead."); this.parents = parents; this.returnStates = returnStates; } internal ArrayPredictionContext(PredictionContext[] parents, int[] returnStates, int hashCode) : base(hashCode) { System.Diagnostics.Debug.Assert(parents.Length == returnStates.Length); System.Diagnostics.Debug.Assert(returnStates.Length > 1 || returnStates[0] != EmptyFullStateKey, "Should be using PredictionContext.EMPTY instead."); this.parents = parents; this.returnStates = returnStates; } public override PredictionContext GetParent(int index) { return parents[index]; } public override int GetReturnState(int index) { return returnStates[index]; } public override int FindReturnState(int returnState) { return System.Array.BinarySearch(returnStates, returnState); } public override int Size { get { return returnStates.Length; } } public override bool IsEmpty { get { return false; } } public override bool HasEmpty { get { return returnStates[returnStates.Length - 1] == EmptyFullStateKey; } } protected internal override PredictionContext AddEmptyContext() { if (HasEmpty) { return this; } PredictionContext[] parents2 = Arrays.CopyOf(parents, parents.Length + 1); int[] returnStates2 = Arrays.CopyOf(returnStates, returnStates.Length + 1); parents2[parents2.Length - 1] = PredictionContext.EmptyFull; returnStates2[returnStates2.Length - 1] = PredictionContext.EmptyFullStateKey; return new Antlr4.Runtime.Atn.ArrayPredictionContext(parents2, returnStates2); } protected internal override PredictionContext RemoveEmptyContext() { if (!HasEmpty) { return this; } if (returnStates.Length == 2) { return new SingletonPredictionContext(parents[0], returnStates[0]); } else { PredictionContext[] parents2 = Arrays.CopyOf(parents, parents.Length - 1); int[] returnStates2 = Arrays.CopyOf(returnStates, returnStates.Length - 1); return new Antlr4.Runtime.Atn.ArrayPredictionContext(parents2, returnStates2); } } public override PredictionContext AppendContext(PredictionContext suffix, PredictionContextCache contextCache) { return AppendContext(this, suffix, new PredictionContext.IdentityHashMap()); } private static PredictionContext AppendContext(PredictionContext context, PredictionContext suffix, PredictionContext.IdentityHashMap visited) { if (suffix.IsEmpty) { if (IsEmptyLocal(suffix)) { if (context.HasEmpty) { return EmptyLocal; } throw new NotSupportedException("what to do here?"); } return context; } if (suffix.Size != 1) { throw new NotSupportedException("Appending a tree suffix is not yet supported."); } PredictionContext result; if (!visited.TryGetValue(context, out result)) { if (context.IsEmpty) { result = suffix; } else { int parentCount = context.Size; if (context.HasEmpty) { parentCount--; } PredictionContext[] updatedParents = new PredictionContext[parentCount]; int[] updatedReturnStates = new int[parentCount]; for (int i = 0; i < parentCount; i++) { updatedReturnStates[i] = context.GetReturnState(i); } for (int i_1 = 0; i_1 < parentCount; i_1++) { updatedParents[i_1] = AppendContext(context.GetParent(i_1), suffix, visited); } if (updatedParents.Length == 1) { result = new SingletonPredictionContext(updatedParents[0], updatedReturnStates[0]); } else { System.Diagnostics.Debug.Assert(updatedParents.Length > 1); result = new Antlr4.Runtime.Atn.ArrayPredictionContext(updatedParents, updatedReturnStates); } if (context.HasEmpty) { result = PredictionContext.Join(result, suffix); } } visited[context] = result; } return result; } public override bool Equals(object o) { if (this == o) { return true; } else { if (!(o is Antlr4.Runtime.Atn.ArrayPredictionContext)) { return false; } } if (this.GetHashCode() != o.GetHashCode()) { return false; } // can't be same if hash is different Antlr4.Runtime.Atn.ArrayPredictionContext other = (Antlr4.Runtime.Atn.ArrayPredictionContext)o; return Equals(other, new HashSet<PredictionContextCache.IdentityCommutativePredictionContextOperands>()); } private bool Equals(Antlr4.Runtime.Atn.ArrayPredictionContext other, HashSet<PredictionContextCache.IdentityCommutativePredictionContextOperands> visited) { Stack<PredictionContext> selfWorkList = new Stack<PredictionContext>(); Stack<PredictionContext> otherWorkList = new Stack<PredictionContext>(); selfWorkList.Push(this); otherWorkList.Push(other); while (selfWorkList.Count > 0) { PredictionContextCache.IdentityCommutativePredictionContextOperands operands = new PredictionContextCache.IdentityCommutativePredictionContextOperands(selfWorkList.Pop(), otherWorkList.Pop()); if (!visited.Add(operands)) { continue; } int selfSize = operands.X.Size; if (selfSize == 0) { if (!operands.X.Equals(operands.Y)) { return false; } continue; } int otherSize = operands.Y.Size; if (selfSize != otherSize) { return false; } for (int i = 0; i < selfSize; i++) { if (operands.X.GetReturnState(i) != operands.Y.GetReturnState(i)) { return false; } PredictionContext selfParent = operands.X.GetParent(i); PredictionContext otherParent = operands.Y.GetParent(i); if (selfParent.GetHashCode() != otherParent.GetHashCode()) { return false; } if (selfParent != otherParent) { selfWorkList.Push(selfParent); otherWorkList.Push(otherParent); } } } return true; } } }
using XenAdmin.Controls.DataGridViewEx; using System.Windows.Forms; namespace XenAdmin.SettingsPanels { partial class HostPowerONEditPage { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(HostPowerONEditPage)); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); this.groupBoxMode = new System.Windows.Forms.GroupBox(); this.radioButtonDisabled = new System.Windows.Forms.RadioButton(); this.radioButtonWakeonLAN = new System.Windows.Forms.RadioButton(); this.radioButtonILO = new System.Windows.Forms.RadioButton(); this.radioButtonDRAC = new System.Windows.Forms.RadioButton(); this.radioButtonCustom = new System.Windows.Forms.RadioButton(); this.textBoxCustom = new System.Windows.Forms.TextBox(); this.groupBoxCredentials = new System.Windows.Forms.GroupBox(); this.tableLayoutPanelCredentials = new System.Windows.Forms.TableLayoutPanel(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.textBoxInterface = new System.Windows.Forms.TextBox(); this.textBoxUser = new System.Windows.Forms.TextBox(); this.textBoxPassword = new System.Windows.Forms.TextBox(); this.dataGridView1 = new XenAdmin.SettingsPanels.HostPowerONEditPage.DataGridViewKey(); this.ColumnKey = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnValue = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.label4 = new System.Windows.Forms.Label(); this.groupBoxMode.SuspendLayout(); this.groupBoxCredentials.SuspendLayout(); this.tableLayoutPanelCredentials.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout(); // // groupBoxMode // this.groupBoxMode.Controls.Add(this.radioButtonDisabled); this.groupBoxMode.Controls.Add(this.radioButtonWakeonLAN); this.groupBoxMode.Controls.Add(this.radioButtonILO); this.groupBoxMode.Controls.Add(this.radioButtonDRAC); this.groupBoxMode.Controls.Add(this.radioButtonCustom); this.groupBoxMode.Controls.Add(this.textBoxCustom); resources.ApplyResources(this.groupBoxMode, "groupBoxMode"); this.groupBoxMode.Name = "groupBoxMode"; this.groupBoxMode.TabStop = false; // // radioButtonDisabled // resources.ApplyResources(this.radioButtonDisabled, "radioButtonDisabled"); this.radioButtonDisabled.Checked = true; this.radioButtonDisabled.Name = "radioButtonDisabled"; this.radioButtonDisabled.TabStop = true; this.radioButtonDisabled.UseVisualStyleBackColor = true; this.radioButtonDisabled.CheckedChanged += new System.EventHandler(this.radioButtonDisabled_CheckedChanged); // // radioButtonWakeonLAN // resources.ApplyResources(this.radioButtonWakeonLAN, "radioButtonWakeonLAN"); this.radioButtonWakeonLAN.Name = "radioButtonWakeonLAN"; this.radioButtonWakeonLAN.UseVisualStyleBackColor = true; this.radioButtonWakeonLAN.CheckedChanged += new System.EventHandler(this.radioButtonWakeonLAN_CheckedChanged); // // radioButtonILO // resources.ApplyResources(this.radioButtonILO, "radioButtonILO"); this.radioButtonILO.Name = "radioButtonILO"; this.radioButtonILO.UseVisualStyleBackColor = true; this.radioButtonILO.CheckedChanged += new System.EventHandler(this.radioButtonILO_CheckedChanged); // // radioButtonDRAC // resources.ApplyResources(this.radioButtonDRAC, "radioButtonDRAC"); this.radioButtonDRAC.Name = "radioButtonDRAC"; this.radioButtonDRAC.UseVisualStyleBackColor = true; this.radioButtonDRAC.CheckedChanged += new System.EventHandler(this.radioButtonDRAC_CheckedChanged); // // radioButtonCustom // resources.ApplyResources(this.radioButtonCustom, "radioButtonCustom"); this.radioButtonCustom.Name = "radioButtonCustom"; this.radioButtonCustom.UseVisualStyleBackColor = true; this.radioButtonCustom.CheckedChanged += new System.EventHandler(this.radioButtonCustom_CheckedChanged); // // textBoxCustom // resources.ApplyResources(this.textBoxCustom, "textBoxCustom"); this.textBoxCustom.Name = "textBoxCustom"; this.textBoxCustom.Click += new System.EventHandler(this.textBoxCustom_Click); // // groupBoxCredentials // this.groupBoxCredentials.Controls.Add(this.tableLayoutPanelCredentials); resources.ApplyResources(this.groupBoxCredentials, "groupBoxCredentials"); this.groupBoxCredentials.Name = "groupBoxCredentials"; this.groupBoxCredentials.TabStop = false; // // tableLayoutPanelCredentials // resources.ApplyResources(this.tableLayoutPanelCredentials, "tableLayoutPanelCredentials"); this.tableLayoutPanelCredentials.Controls.Add(this.label1, 0, 0); this.tableLayoutPanelCredentials.Controls.Add(this.label2, 0, 1); this.tableLayoutPanelCredentials.Controls.Add(this.label3, 0, 2); this.tableLayoutPanelCredentials.Controls.Add(this.textBoxInterface, 1, 0); this.tableLayoutPanelCredentials.Controls.Add(this.textBoxUser, 1, 1); this.tableLayoutPanelCredentials.Controls.Add(this.textBoxPassword, 1, 2); this.tableLayoutPanelCredentials.Name = "tableLayoutPanelCredentials"; // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // textBoxInterface // resources.ApplyResources(this.textBoxInterface, "textBoxInterface"); this.textBoxInterface.Name = "textBoxInterface"; // // textBoxUser // resources.ApplyResources(this.textBoxUser, "textBoxUser"); this.textBoxUser.Name = "textBoxUser"; // // textBoxPassword // resources.ApplyResources(this.textBoxPassword, "textBoxPassword"); this.textBoxPassword.Name = "textBoxPassword"; this.textBoxPassword.UseSystemPasswordChar = true; // // dataGridView1 // this.dataGridView1.AllowUserToOrderColumns = true; this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; this.dataGridView1.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.ColumnKey, this.ColumnValue}); dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Window; dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.ControlText; dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Control; dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.ControlText; dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.False; this.dataGridView1.DefaultCellStyle = dataGridViewCellStyle1; resources.ApplyResources(this.dataGridView1, "dataGridView1"); this.dataGridView1.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter; this.dataGridView1.MaximumSize = new System.Drawing.Size(0, 120); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dataGridView1.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellEndEdit); // // ColumnKey // resources.ApplyResources(this.ColumnKey, "ColumnKey"); this.ColumnKey.Name = "ColumnKey"; // // ColumnValue // resources.ApplyResources(this.ColumnValue, "ColumnValue"); this.ColumnValue.Name = "ColumnValue"; // // label4 // resources.ApplyResources(this.label4, "label4"); this.label4.Name = "label4"; // // HostPowerONEditPage // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.Controls.Add(this.label4); this.Controls.Add(this.groupBoxMode); this.Controls.Add(this.groupBoxCredentials); this.Name = "HostPowerONEditPage"; this.groupBoxMode.ResumeLayout(false); this.groupBoxMode.PerformLayout(); this.groupBoxCredentials.ResumeLayout(false); this.tableLayoutPanelCredentials.ResumeLayout(false); this.tableLayoutPanelCredentials.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false); } #endregion protected System.Windows.Forms.RadioButton radioButtonWakeonLAN; protected System.Windows.Forms.RadioButton radioButtonILO; protected System.Windows.Forms.RadioButton radioButtonDisabled; protected System.Windows.Forms.TextBox textBoxCustom; protected System.Windows.Forms.RadioButton radioButtonCustom; protected System.Windows.Forms.RadioButton radioButtonDRAC; protected System.Windows.Forms.GroupBox groupBoxCredentials; protected System.Windows.Forms.TableLayoutPanel tableLayoutPanelCredentials; protected System.Windows.Forms.Label label1; protected System.Windows.Forms.Label label2; protected System.Windows.Forms.Label label3; protected System.Windows.Forms.TextBox textBoxInterface; protected System.Windows.Forms.TextBox textBoxUser; protected System.Windows.Forms.TextBox textBoxPassword; protected System.Windows.Forms.DataGridViewTextBoxColumn ColumnKey; protected System.Windows.Forms.DataGridViewTextBoxColumn ColumnValue; protected DataGridViewKey dataGridView1; protected GroupBox groupBoxMode; protected Label label4; } }
using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using Nop.Core.Domain.Orders; using Nop.Core.Domain.Payments; using Nop.Services.Orders; namespace Nop.Services.Payments { /// <summary> /// Payment extensions /// </summary> public static class PaymentExtensions { /// <summary> /// Is payment method active? /// </summary> /// <param name="paymentMethod">Payment method</param> /// <param name="paymentSettings">Payment settings</param> /// <returns>Result</returns> public static bool IsPaymentMethodActive(this IPaymentMethod paymentMethod, PaymentSettings paymentSettings) { if (paymentMethod == null) throw new ArgumentNullException("paymentMethod"); if (paymentSettings == null) throw new ArgumentNullException("paymentSettings"); if (paymentSettings.ActivePaymentMethodSystemNames == null) return false; foreach (string activeMethodSystemName in paymentSettings.ActivePaymentMethodSystemNames) if (paymentMethod.PluginDescriptor.SystemName.Equals(activeMethodSystemName, StringComparison.InvariantCultureIgnoreCase)) return true; return false; } /// <summary> /// Calculate payment method fee /// </summary> /// <param name="paymentMethod">Payment method</param> /// <param name="orderTotalCalculationService">Order total calculation service</param> /// <param name="cart">Shopping cart</param> /// <param name="fee">Fee value</param> /// <param name="usePercentage">Is fee amount specified as percentage or fixed value?</param> /// <returns>Result</returns> public static decimal CalculateAdditionalFee(this IPaymentMethod paymentMethod, IOrderTotalCalculationService orderTotalCalculationService, IList<ShoppingCartItem> cart, decimal fee, bool usePercentage) { if (paymentMethod == null) throw new ArgumentNullException("paymentMethod"); if (fee <= 0) return fee; var result = decimal.Zero; if (usePercentage) { //percentage var orderTotalWithoutPaymentFee = orderTotalCalculationService.GetShoppingCartTotal(cart, usePaymentMethodAdditionalFee: false); result = (decimal)((((float)orderTotalWithoutPaymentFee) * ((float)fee)) / 100f); } else { //fixed value result = fee; } return result; } /// <summary> /// Serialize CustomValues of ProcessPaymentRequest /// </summary> /// <param name="request">Request</param> /// <returns>Serialized CustomValues</returns> public static string SerializeCustomValues(this ProcessPaymentRequest request) { if (request == null) throw new ArgumentNullException("request"); if (request.CustomValues.Count == 0) return null; //XmlSerializer won't serialize objects that implement IDictionary by default. //http://msdn.microsoft.com/en-us/magazine/cc164135.aspx //also see http://ropox.ru/tag/ixmlserializable/ (Russian language) var ds = new DictionarySerializer(request.CustomValues); var xs = new XmlSerializer(typeof(DictionarySerializer)); using (var textWriter = new StringWriter()) { using (var xmlWriter = XmlWriter.Create(textWriter)) { xs.Serialize(xmlWriter, ds); } var result = textWriter.ToString(); return result; } } /// <summary> /// Deerialize CustomValues of Order /// </summary> /// <param name="order">Order</param> /// <returns>Serialized CustomValues CustomValues</returns> public static Dictionary<string, object> DeserializeCustomValues(this Order order) { if (order == null) throw new ArgumentNullException("order"); var request = new ProcessPaymentRequest(); return request.DeserializeCustomValues(order.CustomValuesXml); } /// <summary> /// Deerialize CustomValues of ProcessPaymentRequest /// </summary> /// <param name="request">Request</param> /// <param name="customValuesXml">Serialized CustomValues</param> /// <returns>Serialized CustomValues CustomValues</returns> public static Dictionary<string, object> DeserializeCustomValues(this ProcessPaymentRequest request, string customValuesXml) { if (string.IsNullOrWhiteSpace(customValuesXml)) { return new Dictionary<string, object>(); } var serializer = new XmlSerializer(typeof(DictionarySerializer)); using (var textReader = new StringReader(customValuesXml)) { using (var xmlReader = XmlReader.Create(textReader)) { var ds = serializer.Deserialize(xmlReader) as DictionarySerializer; if (ds != null) return ds.Dictionary; return new Dictionary<string, object>(); } } } /// <summary> /// Dictonary serializer /// </summary> public class DictionarySerializer : IXmlSerializable { public Dictionary<string, object> Dictionary; public DictionarySerializer() { this.Dictionary = new Dictionary<string, object>(); } public DictionarySerializer(Dictionary<string, object> dictionary) { this.Dictionary = dictionary; } public void WriteXml(XmlWriter writer) { if (Dictionary.Count == 0) return; foreach (var key in this.Dictionary.Keys) { writer.WriteStartElement("item"); writer.WriteElementString("key", key); var value = this.Dictionary[key]; //please note that we use ToString() for objects here //of course, we can Serialize them //but let's keep it simple and leave it for developers to handle it //just put required serialization into ToString method of your object(s) //because some objects don't implement ISerializable //the question is how should we deserialize null values? writer.WriteElementString("value", value != null ? value.ToString() : null); writer.WriteEndElement(); } } public void ReadXml(XmlReader reader) { bool wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) return; while (reader.NodeType != XmlNodeType.EndElement) { reader.ReadStartElement("item"); string key = reader.ReadElementString("key"); string value = reader.ReadElementString("value"); this.Dictionary.Add(key, value); reader.ReadEndElement(); reader.MoveToContent(); } reader.ReadEndElement(); } public XmlSchema GetSchema() { return null; } } } }
// // CGContextPDF.cs: Implements the managed CGContextPDF // // Authors: Mono Team // // Copyright 2009-2010 Novell, Inc // Copyright 2011, 2012 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Drawing; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; using MonoMac.Foundation; using MonoMac.CoreFoundation; namespace MonoMac.CoreGraphics { public class CGPDFPageInfo { static IntPtr kCGPDFContextMediaBox; static IntPtr kCGPDFContextCropBox; static IntPtr kCGPDFContextBleedBox; static IntPtr kCGPDFContextTrimBox; static IntPtr kCGPDFContextArtBox; static CGPDFPageInfo () { IntPtr h = Dlfcn.dlopen (Constants.CoreGraphicsLibrary, 0); try { kCGPDFContextMediaBox = Dlfcn.GetIndirect (h, "kCGPDFContextMediaBox"); kCGPDFContextCropBox = Dlfcn.GetIndirect (h, "kCGPDFContextCropBox"); kCGPDFContextBleedBox = Dlfcn.GetIndirect (h, "kCGPDFContextBleedBox"); kCGPDFContextTrimBox = Dlfcn.GetIndirect (h, "kCGPDFContextTrimBox"); kCGPDFContextArtBox = Dlfcn.GetIndirect (h, "kCGPDFContextArtBox"); } finally { Dlfcn.dlclose (h); } } public RectangleF? MediaBox { get; set; } public RectangleF? CropBox { get; set; } public RectangleF? BleedBox { get; set; } public RectangleF? TrimBox { get; set; } public RectangleF? ArtBox { get; set; } static void Add (NSMutableDictionary dict, IntPtr key, RectangleF? val) { if (!val.HasValue) return; NSData data; unsafe { RectangleF f = val.Value; RectangleF *pf = &f; data = NSData.FromBytes ((IntPtr) pf, 16); } dict.LowlevelSetObject (data, key); } internal virtual NSMutableDictionary ToDictionary () { var ret = new NSMutableDictionary (); Add (ret, kCGPDFContextMediaBox, MediaBox); Add (ret, kCGPDFContextCropBox, CropBox); Add (ret, kCGPDFContextBleedBox, BleedBox); Add (ret, kCGPDFContextTrimBox, TrimBox); Add (ret, kCGPDFContextArtBox, ArtBox); return ret; } } public class CGPDFInfo : CGPDFPageInfo { static IntPtr kCGPDFContextTitle; static IntPtr kCGPDFContextAuthor; static IntPtr kCGPDFContextSubject; static IntPtr kCGPDFContextKeywords; static IntPtr kCGPDFContextCreator; static IntPtr kCGPDFContextOwnerPassword; static IntPtr kCGPDFContextUserPassword; static IntPtr kCGPDFContextEncryptionKeyLength; static IntPtr kCGPDFContextAllowsPrinting; static IntPtr kCGPDFContextAllowsCopying; #if false static IntPtr kCGPDFContextOutputIntent; static IntPtr kCGPDFXOutputIntentSubtype; static IntPtr kCGPDFXOutputConditionIdentifier; static IntPtr kCGPDFXOutputCondition; static IntPtr kCGPDFXRegistryName; static IntPtr kCGPDFXInfo; static IntPtr kCGPDFXDestinationOutputProfile; static IntPtr kCGPDFContextOutputIntents; #endif static CGPDFInfo () { IntPtr h = Dlfcn.dlopen (Constants.CoreGraphicsLibrary, 0); try { kCGPDFContextTitle = Dlfcn.GetIntPtr (h, "kCGPDFContextTitle"); kCGPDFContextAuthor = Dlfcn.GetIntPtr (h, "kCGPDFContextAuthor"); kCGPDFContextSubject = Dlfcn.GetIntPtr (h, "kCGPDFContextSubject"); kCGPDFContextKeywords = Dlfcn.GetIntPtr (h, "kCGPDFContextKeywords"); kCGPDFContextCreator = Dlfcn.GetIntPtr (h, "kCGPDFContextCreator"); kCGPDFContextOwnerPassword = Dlfcn.GetIntPtr (h, "kCGPDFContextOwnerPassword"); kCGPDFContextUserPassword = Dlfcn.GetIntPtr (h, "kCGPDFContextUserPassword"); kCGPDFContextEncryptionKeyLength = Dlfcn.GetIntPtr (h, "kCGPDFContextEncryptionKeyLength"); kCGPDFContextAllowsPrinting = Dlfcn.GetIntPtr (h, "kCGPDFContextAllowsPrinting"); kCGPDFContextAllowsCopying = Dlfcn.GetIntPtr (h, "kCGPDFContextAllowsCopying"); #if false kCGPDFContextOutputIntent = Dlfcn.GetIntPtr (h, "kCGPDFContextOutputIntent"); kCGPDFXOutputIntentSubtype = Dlfcn.GetIntPtr (h, "kCGPDFXOutputIntentSubtype"); kCGPDFXOutputConditionIdentifier = Dlfcn.GetIntPtr (h, "kCGPDFXOutputConditionIdentifier"); kCGPDFXOutputCondition = Dlfcn.GetIntPtr (h, "kCGPDFXOutputCondition"); kCGPDFXRegistryName = Dlfcn.GetIntPtr (h, "kCGPDFXRegistryName"); kCGPDFXInfo = Dlfcn.GetIntPtr (h, "kCGPDFXInfo"); kCGPDFXDestinationOutputProfile = Dlfcn.GetIntPtr (h, "kCGPDFXDestinationOutputProfile"); kCGPDFContextOutputIntents = Dlfcn.GetIntPtr (h, "kCGPDFContextOutputIntents"); #endif } finally { Dlfcn.dlclose (h); } } public string Title { get; set; } public string Author { get; set; } public string Subject { get; set; } public string [] Keywords { get; set; } public string Creator { get; set; } public string OwnerPassword { get; set; } public string UserPassword { get; set; } public int? EncryptionKeyLength { get; set; } public bool? AllowsPrinting { get; set; } public bool? AllowsCopying { get; set; } //public NSDictionary OutputIntent { get; set; } internal override NSMutableDictionary ToDictionary () { var ret = base.ToDictionary (); if (Title != null) ret.LowlevelSetObject ((NSString) Title, kCGPDFContextTitle); if (Author != null) ret.LowlevelSetObject ((NSString) Author, kCGPDFContextAuthor); if (Subject != null) ret.LowlevelSetObject ((NSString) Subject, kCGPDFContextSubject); if (Keywords != null && Keywords.Length > 0){ if (Keywords.Length == 1) ret.LowlevelSetObject ((NSString) Keywords [0], kCGPDFContextKeywords); else ret.LowlevelSetObject (NSArray.FromStrings (Keywords), kCGPDFContextKeywords); } if (Creator != null) ret.LowlevelSetObject ((NSString) Creator, kCGPDFContextCreator); if (OwnerPassword != null) ret.LowlevelSetObject ((NSString) OwnerPassword, kCGPDFContextOwnerPassword); if (UserPassword != null) ret.LowlevelSetObject ((NSString) UserPassword, kCGPDFContextUserPassword); if (EncryptionKeyLength.HasValue) ret.LowlevelSetObject (NSNumber.FromInt32 (EncryptionKeyLength.Value), kCGPDFContextEncryptionKeyLength); if (AllowsPrinting.HasValue && AllowsPrinting.Value == false) ret.LowlevelSetObject (CFBoolean.False.Handle, kCGPDFContextAllowsPrinting); if (AllowsCopying.HasValue && AllowsCopying.Value == false) ret.LowlevelSetObject (CFBoolean.False.Handle, kCGPDFContextAllowsCopying); return ret; } } public class CGContextPDF : CGContext { bool closed; [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGPDFContextCreateWithURL (IntPtr url, ref RectangleF rect, IntPtr dictionary); [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGPDFContextCreateWithURL (IntPtr url, IntPtr rect, IntPtr dictionary); public CGContextPDF (NSUrl url, RectangleF mediaBox, CGPDFInfo info) { if (url == null) throw new ArgumentNullException ("url"); handle = CGPDFContextCreateWithURL (url.Handle, ref mediaBox, info == null ? IntPtr.Zero : info.ToDictionary ().Handle); } public CGContextPDF (NSUrl url, RectangleF mediaBox) { if (url == null) throw new ArgumentNullException ("url"); handle = CGPDFContextCreateWithURL (url.Handle, ref mediaBox, IntPtr.Zero); } public CGContextPDF (NSUrl url, CGPDFInfo info) { if (url == null) throw new ArgumentNullException ("url"); handle = CGPDFContextCreateWithURL (url.Handle, IntPtr.Zero, info == null ? IntPtr.Zero : info.ToDictionary ().Handle); } public CGContextPDF (NSUrl url) { if (url == null) throw new ArgumentNullException ("url"); handle = CGPDFContextCreateWithURL (url.Handle, IntPtr.Zero, IntPtr.Zero); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGPDFContextClose(IntPtr handle); public void Close () { if (closed) return; CGPDFContextClose (handle); closed = true; } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGPDFContextBeginPage (IntPtr handle, IntPtr dict); public void BeginPage (CGPDFPageInfo info) { CGPDFContextBeginPage (handle, info == null ? IntPtr.Zero : info.ToDictionary ().Handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGPDFContextEndPage (IntPtr handle); public void EndPage () { CGPDFContextEndPage (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGPDFContextAddDocumentMetadata (IntPtr handle, IntPtr nsDataHandle); public void AddDocumentMetadata (NSData data) { if (data == null) return; CGPDFContextAddDocumentMetadata (handle, data.Handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGPDFContextSetURLForRect (IntPtr handle, IntPtr urlh, RectangleF rect); public void SetUrl (NSUrl url, RectangleF region) { if (url == null) throw new ArgumentNullException ("url"); CGPDFContextSetURLForRect (handle, url.Handle, region); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGPDFContextAddDestinationAtPoint (IntPtr handle, IntPtr cfstring, PointF point); public void AddDestination (string name, PointF point) { if (name == null) throw new ArgumentNullException ("name"); CGPDFContextAddDestinationAtPoint (handle, new NSString (name).Handle, point); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGPDFContextSetDestinationForRect (IntPtr handle, IntPtr cfstr, RectangleF rect); public void SetDestination (string name, RectangleF rect) { if (name == null) throw new ArgumentNullException ("name"); CGPDFContextSetDestinationForRect (handle, new NSString (name).Handle, rect); } protected override void Dispose (bool disposing) { if (disposing) Close (); base.Dispose (disposing); } } }
using System; using System.Collections; using System.IO; using Org.BouncyCastle.Crypto.Agreement; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Encoders; namespace Org.BouncyCastle.Crypto.Tls { public abstract class TlsDHUtilities { internal static readonly BigInteger Two = BigInteger.Two; /* * TODO[draft-ietf-tls-negotiated-ff-dhe-01] Move these groups to DHStandardGroups once reaches RFC */ private static BigInteger FromHex(String hex) { return new BigInteger(1, Hex.Decode(hex)); } private static DHParameters FromSafeP(String hexP) { BigInteger p = FromHex(hexP), q = p.ShiftRight(1); return new DHParameters(p, Two, q); } private static readonly string draft_ffdhe2432_p = "FFFFFFFFFFFFFFFFADF85458A2BB4A9AAFDC5620273D3CF1" + "D8B9C583CE2D3695A9E13641146433FBCC939DCE249B3EF9" + "7D2FE363630C75D8F681B202AEC4617AD3DF1ED5D5FD6561" + "2433F51F5F066ED0856365553DED1AF3B557135E7F57C935" + "984F0C70E0E68B77E2A689DAF3EFE8721DF158A136ADE735" + "30ACCA4F483A797ABC0AB182B324FB61D108A94BB2C8E3FB" + "B96ADAB760D7F4681D4F42A3DE394DF4AE56EDE76372BB19" + "0B07A7C8EE0A6D709E02FCE1CDF7E2ECC03404CD28342F61" + "9172FE9CE98583FF8E4F1232EEF28183C3FE3B1B4C6FAD73" + "3BB5FCBC2EC22005C58EF1837D1683B2C6F34A26C1B2EFFA" + "886B4238611FCFDCDE355B3B6519035BBC34F4DEF99C0238" + "61B46FC9D6E6C9077AD91D2691F7F7EE598CB0FAC186D91C" + "AEFE13098533C8B3FFFFFFFFFFFFFFFF"; internal static readonly DHParameters draft_ffdhe2432 = FromSafeP(draft_ffdhe2432_p); private static readonly string draft_ffdhe3072_p = "FFFFFFFFFFFFFFFFADF85458A2BB4A9AAFDC5620273D3CF1" + "D8B9C583CE2D3695A9E13641146433FBCC939DCE249B3EF9" + "7D2FE363630C75D8F681B202AEC4617AD3DF1ED5D5FD6561" + "2433F51F5F066ED0856365553DED1AF3B557135E7F57C935" + "984F0C70E0E68B77E2A689DAF3EFE8721DF158A136ADE735" + "30ACCA4F483A797ABC0AB182B324FB61D108A94BB2C8E3FB" + "B96ADAB760D7F4681D4F42A3DE394DF4AE56EDE76372BB19" + "0B07A7C8EE0A6D709E02FCE1CDF7E2ECC03404CD28342F61" + "9172FE9CE98583FF8E4F1232EEF28183C3FE3B1B4C6FAD73" + "3BB5FCBC2EC22005C58EF1837D1683B2C6F34A26C1B2EFFA" + "886B4238611FCFDCDE355B3B6519035BBC34F4DEF99C0238" + "61B46FC9D6E6C9077AD91D2691F7F7EE598CB0FAC186D91C" + "AEFE130985139270B4130C93BC437944F4FD4452E2D74DD3" + "64F2E21E71F54BFF5CAE82AB9C9DF69EE86D2BC522363A0D" + "ABC521979B0DEADA1DBF9A42D5C4484E0ABCD06BFA53DDEF" + "3C1B20EE3FD59D7C25E41D2B66C62E37FFFFFFFFFFFFFFFF"; internal static readonly DHParameters draft_ffdhe3072 = FromSafeP(draft_ffdhe3072_p); private static readonly string draft_ffdhe4096_p = "FFFFFFFFFFFFFFFFADF85458A2BB4A9AAFDC5620273D3CF1" + "D8B9C583CE2D3695A9E13641146433FBCC939DCE249B3EF9" + "7D2FE363630C75D8F681B202AEC4617AD3DF1ED5D5FD6561" + "2433F51F5F066ED0856365553DED1AF3B557135E7F57C935" + "984F0C70E0E68B77E2A689DAF3EFE8721DF158A136ADE735" + "30ACCA4F483A797ABC0AB182B324FB61D108A94BB2C8E3FB" + "B96ADAB760D7F4681D4F42A3DE394DF4AE56EDE76372BB19" + "0B07A7C8EE0A6D709E02FCE1CDF7E2ECC03404CD28342F61" + "9172FE9CE98583FF8E4F1232EEF28183C3FE3B1B4C6FAD73" + "3BB5FCBC2EC22005C58EF1837D1683B2C6F34A26C1B2EFFA" + "886B4238611FCFDCDE355B3B6519035BBC34F4DEF99C0238" + "61B46FC9D6E6C9077AD91D2691F7F7EE598CB0FAC186D91C" + "AEFE130985139270B4130C93BC437944F4FD4452E2D74DD3" + "64F2E21E71F54BFF5CAE82AB9C9DF69EE86D2BC522363A0D" + "ABC521979B0DEADA1DBF9A42D5C4484E0ABCD06BFA53DDEF" + "3C1B20EE3FD59D7C25E41D2B669E1EF16E6F52C3164DF4FB" + "7930E9E4E58857B6AC7D5F42D69F6D187763CF1D55034004" + "87F55BA57E31CC7A7135C886EFB4318AED6A1E012D9E6832" + "A907600A918130C46DC778F971AD0038092999A333CB8B7A" + "1A1DB93D7140003C2A4ECEA9F98D0ACC0A8291CDCEC97DCF" + "8EC9B55A7F88A46B4DB5A851F44182E1C68A007E5E655F6A" + "FFFFFFFFFFFFFFFF"; internal static readonly DHParameters draft_ffdhe4096 = FromSafeP(draft_ffdhe4096_p); private static readonly string draft_ffdhe6144_p = "FFFFFFFFFFFFFFFFADF85458A2BB4A9AAFDC5620273D3CF1" + "D8B9C583CE2D3695A9E13641146433FBCC939DCE249B3EF9" + "7D2FE363630C75D8F681B202AEC4617AD3DF1ED5D5FD6561" + "2433F51F5F066ED0856365553DED1AF3B557135E7F57C935" + "984F0C70E0E68B77E2A689DAF3EFE8721DF158A136ADE735" + "30ACCA4F483A797ABC0AB182B324FB61D108A94BB2C8E3FB" + "B96ADAB760D7F4681D4F42A3DE394DF4AE56EDE76372BB19" + "0B07A7C8EE0A6D709E02FCE1CDF7E2ECC03404CD28342F61" + "9172FE9CE98583FF8E4F1232EEF28183C3FE3B1B4C6FAD73" + "3BB5FCBC2EC22005C58EF1837D1683B2C6F34A26C1B2EFFA" + "886B4238611FCFDCDE355B3B6519035BBC34F4DEF99C0238" + "61B46FC9D6E6C9077AD91D2691F7F7EE598CB0FAC186D91C" + "AEFE130985139270B4130C93BC437944F4FD4452E2D74DD3" + "64F2E21E71F54BFF5CAE82AB9C9DF69EE86D2BC522363A0D" + "ABC521979B0DEADA1DBF9A42D5C4484E0ABCD06BFA53DDEF" + "3C1B20EE3FD59D7C25E41D2B669E1EF16E6F52C3164DF4FB" + "7930E9E4E58857B6AC7D5F42D69F6D187763CF1D55034004" + "87F55BA57E31CC7A7135C886EFB4318AED6A1E012D9E6832" + "A907600A918130C46DC778F971AD0038092999A333CB8B7A" + "1A1DB93D7140003C2A4ECEA9F98D0ACC0A8291CDCEC97DCF" + "8EC9B55A7F88A46B4DB5A851F44182E1C68A007E5E0DD902" + "0BFD64B645036C7A4E677D2C38532A3A23BA4442CAF53EA6" + "3BB454329B7624C8917BDD64B1C0FD4CB38E8C334C701C3A" + "CDAD0657FCCFEC719B1F5C3E4E46041F388147FB4CFDB477" + "A52471F7A9A96910B855322EDB6340D8A00EF092350511E3" + "0ABEC1FFF9E3A26E7FB29F8C183023C3587E38DA0077D9B4" + "763E4E4B94B2BBC194C6651E77CAF992EEAAC0232A281BF6" + "B3A739C1226116820AE8DB5847A67CBEF9C9091B462D538C" + "D72B03746AE77F5E62292C311562A846505DC82DB854338A" + "E49F5235C95B91178CCF2DD5CACEF403EC9D1810C6272B04" + "5B3B71F9DC6B80D63FDD4A8E9ADB1E6962A69526D43161C1" + "A41D570D7938DAD4A40E329CD0E40E65FFFFFFFFFFFFFFFF"; internal static readonly DHParameters draft_ffdhe6144 = FromSafeP(draft_ffdhe6144_p); private static readonly string draft_ffdhe8192_p = "FFFFFFFFFFFFFFFFADF85458A2BB4A9AAFDC5620273D3CF1" + "D8B9C583CE2D3695A9E13641146433FBCC939DCE249B3EF9" + "7D2FE363630C75D8F681B202AEC4617AD3DF1ED5D5FD6561" + "2433F51F5F066ED0856365553DED1AF3B557135E7F57C935" + "984F0C70E0E68B77E2A689DAF3EFE8721DF158A136ADE735" + "30ACCA4F483A797ABC0AB182B324FB61D108A94BB2C8E3FB" + "B96ADAB760D7F4681D4F42A3DE394DF4AE56EDE76372BB19" + "0B07A7C8EE0A6D709E02FCE1CDF7E2ECC03404CD28342F61" + "9172FE9CE98583FF8E4F1232EEF28183C3FE3B1B4C6FAD73" + "3BB5FCBC2EC22005C58EF1837D1683B2C6F34A26C1B2EFFA" + "886B4238611FCFDCDE355B3B6519035BBC34F4DEF99C0238" + "61B46FC9D6E6C9077AD91D2691F7F7EE598CB0FAC186D91C" + "AEFE130985139270B4130C93BC437944F4FD4452E2D74DD3" + "64F2E21E71F54BFF5CAE82AB9C9DF69EE86D2BC522363A0D" + "ABC521979B0DEADA1DBF9A42D5C4484E0ABCD06BFA53DDEF" + "3C1B20EE3FD59D7C25E41D2B669E1EF16E6F52C3164DF4FB" + "7930E9E4E58857B6AC7D5F42D69F6D187763CF1D55034004" + "87F55BA57E31CC7A7135C886EFB4318AED6A1E012D9E6832" + "A907600A918130C46DC778F971AD0038092999A333CB8B7A" + "1A1DB93D7140003C2A4ECEA9F98D0ACC0A8291CDCEC97DCF" + "8EC9B55A7F88A46B4DB5A851F44182E1C68A007E5E0DD902" + "0BFD64B645036C7A4E677D2C38532A3A23BA4442CAF53EA6" + "3BB454329B7624C8917BDD64B1C0FD4CB38E8C334C701C3A" + "CDAD0657FCCFEC719B1F5C3E4E46041F388147FB4CFDB477" + "A52471F7A9A96910B855322EDB6340D8A00EF092350511E3" + "0ABEC1FFF9E3A26E7FB29F8C183023C3587E38DA0077D9B4" + "763E4E4B94B2BBC194C6651E77CAF992EEAAC0232A281BF6" + "B3A739C1226116820AE8DB5847A67CBEF9C9091B462D538C" + "D72B03746AE77F5E62292C311562A846505DC82DB854338A" + "E49F5235C95B91178CCF2DD5CACEF403EC9D1810C6272B04" + "5B3B71F9DC6B80D63FDD4A8E9ADB1E6962A69526D43161C1" + "A41D570D7938DAD4A40E329CCFF46AAA36AD004CF600C838" + "1E425A31D951AE64FDB23FCEC9509D43687FEB69EDD1CC5E" + "0B8CC3BDF64B10EF86B63142A3AB8829555B2F747C932665" + "CB2C0F1CC01BD70229388839D2AF05E454504AC78B758282" + "2846C0BA35C35F5C59160CC046FD8251541FC68C9C86B022" + "BB7099876A460E7451A8A93109703FEE1C217E6C3826E52C" + "51AA691E0E423CFC99E9E31650C1217B624816CDAD9A95F9" + "D5B8019488D9C0A0A1FE3075A577E23183F81D4A3F2FA457" + "1EFC8CE0BA8A4FE8B6855DFE72B0A66EDED2FBABFBE58A30" + "FAFABE1C5D71A87E2F741EF8C1FE86FEA6BBFDE530677F0D" + "97D11D49F7A8443D0822E506A9F4614E011E2A94838FF88C" + "D68C8BB7C5C6424CFFFFFFFFFFFFFFFF"; internal static readonly DHParameters draft_ffdhe8192 = FromSafeP(draft_ffdhe8192_p); public static void AddNegotiatedDheGroupsClientExtension(IDictionary extensions, byte[] dheGroups) { extensions[ExtensionType.negotiated_ff_dhe_groups] = CreateNegotiatedDheGroupsClientExtension(dheGroups); } public static void AddNegotiatedDheGroupsServerExtension(IDictionary extensions, byte dheGroup) { extensions[ExtensionType.negotiated_ff_dhe_groups] = CreateNegotiatedDheGroupsServerExtension(dheGroup); } public static byte[] GetNegotiatedDheGroupsClientExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.negotiated_ff_dhe_groups); return extensionData == null ? null : ReadNegotiatedDheGroupsClientExtension(extensionData); } public static short GetNegotiatedDheGroupsServerExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.negotiated_ff_dhe_groups); return extensionData == null ? (short)-1 : (short)ReadNegotiatedDheGroupsServerExtension(extensionData); } public static byte[] CreateNegotiatedDheGroupsClientExtension(byte[] dheGroups) { if (dheGroups == null || dheGroups.Length < 1 || dheGroups.Length > 255) throw new TlsFatalAlert(AlertDescription.internal_error); return TlsUtilities.EncodeUint8ArrayWithUint8Length(dheGroups); } public static byte[] CreateNegotiatedDheGroupsServerExtension(byte dheGroup) { return new byte[]{ dheGroup }; } public static byte[] ReadNegotiatedDheGroupsClientExtension(byte[] extensionData) { if (extensionData == null) throw new ArgumentNullException("extensionData"); MemoryStream buf = new MemoryStream(extensionData, false); byte length = TlsUtilities.ReadUint8(buf); if (length < 1) throw new TlsFatalAlert(AlertDescription.decode_error); byte[] dheGroups = TlsUtilities.ReadUint8Array(length, buf); TlsProtocol.AssertEmpty(buf); return dheGroups; } public static byte ReadNegotiatedDheGroupsServerExtension(byte[] extensionData) { if (extensionData == null) throw new ArgumentNullException("extensionData"); if (extensionData.Length != 1) throw new TlsFatalAlert(AlertDescription.decode_error); return extensionData[0]; } public static DHParameters GetParametersForDHEGroup(short dheGroup) { switch (dheGroup) { case FiniteFieldDheGroup.ffdhe2432: return draft_ffdhe2432; case FiniteFieldDheGroup.ffdhe3072: return draft_ffdhe3072; case FiniteFieldDheGroup.ffdhe4096: return draft_ffdhe4096; case FiniteFieldDheGroup.ffdhe6144: return draft_ffdhe6144; case FiniteFieldDheGroup.ffdhe8192: return draft_ffdhe8192; default: return null; } } public static bool ContainsDheCipherSuites(int[] cipherSuites) { for (int i = 0; i < cipherSuites.Length; ++i) { if (IsDheCipherSuite(cipherSuites[i])) return true; } return false; } public static bool IsDheCipherSuite(int cipherSuite) { switch (cipherSuite) { /* * RFC 2246 */ case CipherSuite.TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_DES_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_DES_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA: /* * RFC 3268 */ case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA: /* * RFC 5932 */ case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256: /* * RFC 4162 */ case CipherSuite.TLS_DHE_DSS_WITH_SEED_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_SEED_CBC_SHA: /* * RFC 4279 */ case CipherSuite.TLS_DHE_PSK_WITH_RC4_128_SHA: case CipherSuite.TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA: /* * RFC 4785 */ case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA: /* * RFC 5246 */ case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: /* * RFC 5288 */ case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384: /* * RFC 5487 */ case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384: /* * RFC 6367 */ case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384: /* * RFC 6655 */ case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8: /* * draft-agl-tls-chacha20poly1305-04 */ case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256: /* * draft-josefsson-salsa20-tls-04 */ case CipherSuite.TLS_DHE_PSK_WITH_ESTREAM_SALSA20_SHA1: case CipherSuite.TLS_DHE_PSK_WITH_SALSA20_SHA1: case CipherSuite.TLS_DHE_RSA_WITH_ESTREAM_SALSA20_SHA1: case CipherSuite.TLS_DHE_RSA_WITH_SALSA20_SHA1: return true; default: return false; } } public static bool AreCompatibleParameters(DHParameters a, DHParameters b) { return a.P.Equals(b.P) && a.G.Equals(b.G); } public static byte[] CalculateDHBasicAgreement(DHPublicKeyParameters publicKey, DHPrivateKeyParameters privateKey) { DHBasicAgreement basicAgreement = new DHBasicAgreement(); basicAgreement.Init(privateKey); BigInteger agreementValue = basicAgreement.CalculateAgreement(publicKey); /* * RFC 5246 8.1.2. Leading bytes of Z that contain all zero bits are stripped before it is * used as the pre_master_secret. */ return BigIntegers.AsUnsignedByteArray(agreementValue); } public static AsymmetricCipherKeyPair GenerateDHKeyPair(SecureRandom random, DHParameters dhParams) { DHBasicKeyPairGenerator dhGen = new DHBasicKeyPairGenerator(); dhGen.Init(new DHKeyGenerationParameters(random, dhParams)); return dhGen.GenerateKeyPair(); } public static DHPrivateKeyParameters GenerateEphemeralClientKeyExchange(SecureRandom random, DHParameters dhParams, Stream output) { AsymmetricCipherKeyPair kp = GenerateDHKeyPair(random, dhParams); DHPublicKeyParameters dhPublic = (DHPublicKeyParameters)kp.Public; WriteDHParameter(dhPublic.Y, output); return (DHPrivateKeyParameters)kp.Private; } public static DHPrivateKeyParameters GenerateEphemeralServerKeyExchange(SecureRandom random, DHParameters dhParams, Stream output) { AsymmetricCipherKeyPair kp = GenerateDHKeyPair(random, dhParams); DHPublicKeyParameters dhPublic = (DHPublicKeyParameters)kp.Public; new ServerDHParams(dhPublic).Encode(output); return (DHPrivateKeyParameters)kp.Private; } public static DHPublicKeyParameters ValidateDHPublicKey(DHPublicKeyParameters key) { BigInteger Y = key.Y; DHParameters parameters = key.Parameters; BigInteger p = parameters.P; BigInteger g = parameters.G; if (!p.IsProbablePrime(2)) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } if (g.CompareTo(Two) < 0 || g.CompareTo(p.Subtract(Two)) > 0) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } if (Y.CompareTo(Two) < 0 || Y.CompareTo(p.Subtract(Two)) > 0) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } // TODO See RFC 2631 for more discussion of Diffie-Hellman validation return key; } public static BigInteger ReadDHParameter(Stream input) { return new BigInteger(1, TlsUtilities.ReadOpaque16(input)); } public static void WriteDHParameter(BigInteger x, Stream output) { TlsUtilities.WriteOpaque16(BigIntegers.AsUnsignedByteArray(x), output); } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using System.Text.RegularExpressions; #if TESTHELPER namespace MvcContrib.TestHelper #else namespace MvcContrib.UI.InputBuilder.Helpers #endif { public static class ReflectionHelper { public static string ToSeparatedWords(this string value) { return Regex.Replace(value, "([A-Z][a-z])", " $1").Trim(); } //public static string BuildIdFrom(Expression expression) //{ // Expression expressionToCheck = expression; // var tokens = new List<string>(); // bool done = false; // bool accessedMember = false; // while (!done) // { // switch (expressionToCheck.NodeType) // { // case ExpressionType.Convert: // accessedMember = false; // expressionToCheck = ((UnaryExpression)expressionToCheck).Operand; // break; // case ExpressionType.ArrayIndex: // var binaryExpression = (BinaryExpression)expressionToCheck; // Expression indexExpression = binaryExpression.Right; // Delegate indexAction = Expression.Lambda(indexExpression).Compile(); // var value = (int)indexAction.DynamicInvoke(); // if (accessedMember) // { // tokens.Add("_"); // } // tokens.Add(string.Format("_{0}_", value)); // accessedMember = false; // expressionToCheck = binaryExpression.Left; // break; // case ExpressionType.Lambda: // var lambdaExpression = (LambdaExpression)expressionToCheck; // accessedMember = false; // expressionToCheck = lambdaExpression.Body; // break; // case ExpressionType.MemberAccess: // var memberExpression = (MemberExpression)expressionToCheck; // if (accessedMember) // { // tokens.Add("_"); // } // tokens.Add(memberExpression.Member.Name); // if (memberExpression.Expression == null) // { // done = true; // } // else // { // accessedMember = true; // expressionToCheck = memberExpression.Expression; // } // break; // default: // done = true; // break; // } // } // tokens.Reverse(); // string result = string.Join(string.Empty, tokens.ToArray()); // return result; //} public static PropertyInfo FindProperty(LambdaExpression lambdaExpression) { Expression expressionToCheck = lambdaExpression; bool done = false; while (!done) { switch (expressionToCheck.NodeType) { case ExpressionType.Convert: expressionToCheck = ((UnaryExpression)expressionToCheck).Operand; break; case ExpressionType.Lambda: expressionToCheck = lambdaExpression.Body; break; case ExpressionType.MemberAccess: var propertyInfo = ((MemberExpression)expressionToCheck).Member as PropertyInfo; return propertyInfo; default: done = true; break; } } return null; } public static string BuildNameFrom(Expression expression) { Expression expressionToCheck = expression; var tokens = new List<string>(); bool done = false; bool accessedMember = false; while (!done) { switch (expressionToCheck.NodeType) { case ExpressionType.Convert: accessedMember = false; expressionToCheck = ((UnaryExpression)expressionToCheck).Operand; break; case ExpressionType.ArrayIndex: var binaryExpression = (BinaryExpression)expressionToCheck; Expression indexExpression = binaryExpression.Right; Delegate indexAction = Expression.Lambda(indexExpression).Compile(); var value = (int)indexAction.DynamicInvoke(); if (accessedMember) { tokens.Add("."); } tokens.Add(string.Format("[{0}]", value)); accessedMember = false; expressionToCheck = binaryExpression.Left; break; case ExpressionType.Lambda: var lambdaExpression = (LambdaExpression)expressionToCheck; accessedMember = false; expressionToCheck = lambdaExpression.Body; break; case ExpressionType.MemberAccess: var memberExpression = (MemberExpression)expressionToCheck; if (accessedMember) { tokens.Add("."); } tokens.Add(memberExpression.Member.Name); if (memberExpression.Expression == null) { done = true; } else { accessedMember = true; expressionToCheck = memberExpression.Expression; } break; default: done = true; break; } } tokens.Reverse(); string result = string.Join(string.Empty, tokens.ToArray()); return result; } public static PropertyInfo FindPropertyFromExpression(LambdaExpression lambdaExpression) { Expression expressionToCheck = lambdaExpression; var tokens = new List<string>(); bool done = false; bool accessedMember = false; while(!done) { switch(expressionToCheck.NodeType) { case ExpressionType.Convert: expressionToCheck = ((UnaryExpression)expressionToCheck).Operand; break; case ExpressionType.Lambda: expressionToCheck = lambdaExpression.Body; break; case ExpressionType.MemberAccess: var propertyInfo = ((MemberExpression)expressionToCheck).Member as PropertyInfo; return propertyInfo; case ExpressionType.ArrayIndex: var binaryExpression = (BinaryExpression)expressionToCheck; var indexExpression = binaryExpression.Right; Delegate indexAction = Expression.Lambda(indexExpression).Compile(); int value = (int)indexAction.DynamicInvoke(); if (accessedMember) { tokens.Add("."); } tokens.Add(string.Format("[{0}]", value)); accessedMember = false; expressionToCheck = binaryExpression.Left; break; default: done = true; break; } } return null; } public static bool IsIndexed(LambdaExpression lambdaExpression) { Expression expressionToCheck = lambdaExpression; bool done = false; while (!done) { switch (expressionToCheck.NodeType) { case ExpressionType.Convert: expressionToCheck = ((UnaryExpression)expressionToCheck).Operand; break; case ExpressionType.Lambda: expressionToCheck = ((LambdaExpression)expressionToCheck).Body; break; case ExpressionType.MemberAccess: return false; case ExpressionType.ArrayIndex: return true; default: done = true; break; } } return false; } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Reflection { public static class __TypeDelegator { public static IObservable<System.Boolean> IsAssignableFrom( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue, IObservable<System.Reflection.TypeInfo> typeInfo) { return Observable.Zip(TypeDelegatorValue, typeInfo, (TypeDelegatorValueLambda, typeInfoLambda) => TypeDelegatorValueLambda.IsAssignableFrom(typeInfoLambda)); } public static IObservable<System.Object> InvokeMember( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue, IObservable<System.String> name, IObservable<System.Reflection.BindingFlags> invokeAttr, IObservable<System.Reflection.Binder> binder, IObservable<System.Object> target, IObservable<System.Object[]> args, IObservable<System.Reflection.ParameterModifier[]> modifiers, IObservable<System.Globalization.CultureInfo> culture, IObservable<System.String[]> namedParameters) { return Observable.Zip(TypeDelegatorValue, name, invokeAttr, binder, target, args, modifiers, culture, namedParameters, (TypeDelegatorValueLambda, nameLambda, invokeAttrLambda, binderLambda, targetLambda, argsLambda, modifiersLambda, cultureLambda, namedParametersLambda) => TypeDelegatorValueLambda.InvokeMember(nameLambda, invokeAttrLambda, binderLambda, targetLambda, argsLambda, modifiersLambda, cultureLambda, namedParametersLambda)); } public static IObservable<System.Reflection.ConstructorInfo[]> GetConstructors( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue, IObservable<System.Reflection.BindingFlags> bindingAttr) { return Observable.Zip(TypeDelegatorValue, bindingAttr, (TypeDelegatorValueLambda, bindingAttrLambda) => TypeDelegatorValueLambda.GetConstructors(bindingAttrLambda)); } public static IObservable<System.Reflection.MethodInfo[]> GetMethods( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue, IObservable<System.Reflection.BindingFlags> bindingAttr) { return Observable.Zip(TypeDelegatorValue, bindingAttr, (TypeDelegatorValueLambda, bindingAttrLambda) => TypeDelegatorValueLambda.GetMethods(bindingAttrLambda)); } public static IObservable<System.Reflection.FieldInfo> GetField( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue, IObservable<System.String> name, IObservable<System.Reflection.BindingFlags> bindingAttr) { return Observable.Zip(TypeDelegatorValue, name, bindingAttr, (TypeDelegatorValueLambda, nameLambda, bindingAttrLambda) => TypeDelegatorValueLambda.GetField(nameLambda, bindingAttrLambda)); } public static IObservable<System.Reflection.FieldInfo[]> GetFields( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue, IObservable<System.Reflection.BindingFlags> bindingAttr) { return Observable.Zip(TypeDelegatorValue, bindingAttr, (TypeDelegatorValueLambda, bindingAttrLambda) => TypeDelegatorValueLambda.GetFields(bindingAttrLambda)); } public static IObservable<System.Type> GetInterface( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue, IObservable<System.String> name, IObservable<System.Boolean> ignoreCase) { return Observable.Zip(TypeDelegatorValue, name, ignoreCase, (TypeDelegatorValueLambda, nameLambda, ignoreCaseLambda) => TypeDelegatorValueLambda.GetInterface(nameLambda, ignoreCaseLambda)); } public static IObservable<System.Type[]> GetInterfaces( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue) { return Observable.Select(TypeDelegatorValue, (TypeDelegatorValueLambda) => TypeDelegatorValueLambda.GetInterfaces()); } public static IObservable<System.Reflection.EventInfo> GetEvent( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue, IObservable<System.String> name, IObservable<System.Reflection.BindingFlags> bindingAttr) { return Observable.Zip(TypeDelegatorValue, name, bindingAttr, (TypeDelegatorValueLambda, nameLambda, bindingAttrLambda) => TypeDelegatorValueLambda.GetEvent(nameLambda, bindingAttrLambda)); } public static IObservable<System.Reflection.EventInfo[]> GetEvents( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue) { return Observable.Select(TypeDelegatorValue, (TypeDelegatorValueLambda) => TypeDelegatorValueLambda.GetEvents()); } public static IObservable<System.Reflection.PropertyInfo[]> GetProperties( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue, IObservable<System.Reflection.BindingFlags> bindingAttr) { return Observable.Zip(TypeDelegatorValue, bindingAttr, (TypeDelegatorValueLambda, bindingAttrLambda) => TypeDelegatorValueLambda.GetProperties(bindingAttrLambda)); } public static IObservable<System.Reflection.EventInfo[]> GetEvents( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue, IObservable<System.Reflection.BindingFlags> bindingAttr) { return Observable.Zip(TypeDelegatorValue, bindingAttr, (TypeDelegatorValueLambda, bindingAttrLambda) => TypeDelegatorValueLambda.GetEvents(bindingAttrLambda)); } public static IObservable<System.Type[]> GetNestedTypes( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue, IObservable<System.Reflection.BindingFlags> bindingAttr) { return Observable.Zip(TypeDelegatorValue, bindingAttr, (TypeDelegatorValueLambda, bindingAttrLambda) => TypeDelegatorValueLambda.GetNestedTypes(bindingAttrLambda)); } public static IObservable<System.Type> GetNestedType( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue, IObservable<System.String> name, IObservable<System.Reflection.BindingFlags> bindingAttr) { return Observable.Zip(TypeDelegatorValue, name, bindingAttr, (TypeDelegatorValueLambda, nameLambda, bindingAttrLambda) => TypeDelegatorValueLambda.GetNestedType(nameLambda, bindingAttrLambda)); } public static IObservable<System.Reflection.MemberInfo[]> GetMember( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue, IObservable<System.String> name, IObservable<System.Reflection.MemberTypes> type, IObservable<System.Reflection.BindingFlags> bindingAttr) { return Observable.Zip(TypeDelegatorValue, name, type, bindingAttr, (TypeDelegatorValueLambda, nameLambda, typeLambda, bindingAttrLambda) => TypeDelegatorValueLambda.GetMember(nameLambda, typeLambda, bindingAttrLambda)); } public static IObservable<System.Reflection.MemberInfo[]> GetMembers( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue, IObservable<System.Reflection.BindingFlags> bindingAttr) { return Observable.Zip(TypeDelegatorValue, bindingAttr, (TypeDelegatorValueLambda, bindingAttrLambda) => TypeDelegatorValueLambda.GetMembers(bindingAttrLambda)); } public static IObservable<System.Type> GetElementType( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue) { return Observable.Select(TypeDelegatorValue, (TypeDelegatorValueLambda) => TypeDelegatorValueLambda.GetElementType()); } public static IObservable<System.Object[]> GetCustomAttributes( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue, IObservable<System.Boolean> inherit) { return Observable.Zip(TypeDelegatorValue, inherit, (TypeDelegatorValueLambda, inheritLambda) => TypeDelegatorValueLambda.GetCustomAttributes(inheritLambda)); } public static IObservable<System.Object[]> GetCustomAttributes( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue, IObservable<System.Type> attributeType, IObservable<System.Boolean> inherit) { return Observable.Zip(TypeDelegatorValue, attributeType, inherit, (TypeDelegatorValueLambda, attributeTypeLambda, inheritLambda) => TypeDelegatorValueLambda.GetCustomAttributes(attributeTypeLambda, inheritLambda)); } public static IObservable<System.Boolean> IsDefined( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue, IObservable<System.Type> attributeType, IObservable<System.Boolean> inherit) { return Observable.Zip(TypeDelegatorValue, attributeType, inherit, (TypeDelegatorValueLambda, attributeTypeLambda, inheritLambda) => TypeDelegatorValueLambda.IsDefined(attributeTypeLambda, inheritLambda)); } public static IObservable<System.Reflection.InterfaceMapping> GetInterfaceMap( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue, IObservable<System.Type> interfaceType) { return Observable.Zip(TypeDelegatorValue, interfaceType, (TypeDelegatorValueLambda, interfaceTypeLambda) => TypeDelegatorValueLambda.GetInterfaceMap(interfaceTypeLambda)); } public static IObservable<System.Guid> get_GUID( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue) { return Observable.Select(TypeDelegatorValue, (TypeDelegatorValueLambda) => TypeDelegatorValueLambda.GUID); } public static IObservable<System.Int32> get_MetadataToken( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue) { return Observable.Select(TypeDelegatorValue, (TypeDelegatorValueLambda) => TypeDelegatorValueLambda.MetadataToken); } public static IObservable<System.Reflection.Module> get_Module( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue) { return Observable.Select(TypeDelegatorValue, (TypeDelegatorValueLambda) => TypeDelegatorValueLambda.Module); } public static IObservable<System.Reflection.Assembly> get_Assembly( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue) { return Observable.Select(TypeDelegatorValue, (TypeDelegatorValueLambda) => TypeDelegatorValueLambda.Assembly); } public static IObservable<System.RuntimeTypeHandle> get_TypeHandle( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue) { return Observable.Select(TypeDelegatorValue, (TypeDelegatorValueLambda) => TypeDelegatorValueLambda.TypeHandle); } public static IObservable<System.String> get_Name( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue) { return Observable.Select(TypeDelegatorValue, (TypeDelegatorValueLambda) => TypeDelegatorValueLambda.Name); } public static IObservable<System.String> get_FullName( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue) { return Observable.Select(TypeDelegatorValue, (TypeDelegatorValueLambda) => TypeDelegatorValueLambda.FullName); } public static IObservable<System.String> get_Namespace( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue) { return Observable.Select(TypeDelegatorValue, (TypeDelegatorValueLambda) => TypeDelegatorValueLambda.Namespace); } public static IObservable<System.String> get_AssemblyQualifiedName( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue) { return Observable.Select(TypeDelegatorValue, (TypeDelegatorValueLambda) => TypeDelegatorValueLambda.AssemblyQualifiedName); } public static IObservable<System.Type> get_BaseType( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue) { return Observable.Select(TypeDelegatorValue, (TypeDelegatorValueLambda) => TypeDelegatorValueLambda.BaseType); } public static IObservable<System.Boolean> get_IsConstructedGenericType( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue) { return Observable.Select(TypeDelegatorValue, (TypeDelegatorValueLambda) => TypeDelegatorValueLambda.IsConstructedGenericType); } public static IObservable<System.Type> get_UnderlyingSystemType( this IObservable<System.Reflection.TypeDelegator> TypeDelegatorValue) { return Observable.Select(TypeDelegatorValue, (TypeDelegatorValueLambda) => TypeDelegatorValueLambda.UnderlyingSystemType); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Xml; using System.Xml.Schema; using System.Reflection; using System.Globalization; using System.Diagnostics; namespace System.Xml.Xsl.Runtime { /// <summary> /// Table of bound extension functions. Once an extension function is bound and entered into the table, future bindings /// will be very fast. This table is not thread-safe. /// </summary> internal class XmlExtensionFunctionTable { private Dictionary<XmlExtensionFunction, XmlExtensionFunction> _table; private XmlExtensionFunction _funcCached; public XmlExtensionFunctionTable() { _table = new Dictionary<XmlExtensionFunction, XmlExtensionFunction>(); } public XmlExtensionFunction Bind(string name, string namespaceUri, int numArgs, Type objectType, BindingFlags flags) { XmlExtensionFunction func; if (_funcCached == null) _funcCached = new XmlExtensionFunction(); // If the extension function already exists in the table, then binding has already been performed _funcCached.Init(name, namespaceUri, numArgs, objectType, flags); if (!_table.TryGetValue(_funcCached, out func)) { // Function doesn't exist, so bind it and enter it into the table func = _funcCached; _funcCached = null; func.Bind(); _table.Add(func, func); } return func; } } /// <summary> /// This internal class contains methods that allow binding to extension functions and invoking them. /// </summary> internal class XmlExtensionFunction { private string _namespaceUri; // Extension object identifier private string _name; // Name of this method private int _numArgs; // Argument count private Type _objectType; // Type of the object which will be searched for matching methods private BindingFlags _flags; // Modifiers that were used to search for a matching signature private int _hashCode; // Pre-computed hashcode private MethodInfo _meth; // MethodInfo for extension function private Type[] _argClrTypes; // Type array for extension function arguments private Type _retClrType; // Type for extension function return value private XmlQueryType[] _argXmlTypes; // XmlQueryType array for extension function arguments private XmlQueryType _retXmlType; // XmlQueryType for extension function return value /// <summary> /// Constructor. /// </summary> public XmlExtensionFunction() { } /// <summary> /// Constructor (directly binds to passed MethodInfo). /// </summary> public XmlExtensionFunction(string name, string namespaceUri, MethodInfo meth) { _name = name; _namespaceUri = namespaceUri; Bind(meth); } /// <summary> /// Constructor. /// </summary> public XmlExtensionFunction(string name, string namespaceUri, int numArgs, Type objectType, BindingFlags flags) { Init(name, namespaceUri, numArgs, objectType, flags); } /// <summary> /// Initialize, but do not bind. /// </summary> public void Init(string name, string namespaceUri, int numArgs, Type objectType, BindingFlags flags) { _name = name; _namespaceUri = namespaceUri; _numArgs = numArgs; _objectType = objectType; _flags = flags; _meth = null; _argClrTypes = null; _retClrType = null; _argXmlTypes = null; _retXmlType = null; // Compute hash code so that it is not recomputed each time GetHashCode() is called _hashCode = namespaceUri.GetHashCode() ^ name.GetHashCode() ^ ((int)flags << 16) ^ (int)numArgs; } /// <summary> /// Once Bind has been successfully called, Method will be non-null. /// </summary> public MethodInfo Method { get { return _meth; } } /// <summary> /// Once Bind has been successfully called, the Clr type of each argument can be accessed. /// Note that this may be different than Method.GetParameterInfo().ParameterType. /// </summary> public Type GetClrArgumentType(int index) { return _argClrTypes[index]; } /// <summary> /// Once Bind has been successfully called, the Clr type of the return value can be accessed. /// Note that this may be different than Method.GetParameterInfo().ReturnType. /// </summary> public Type ClrReturnType { get { return _retClrType; } } /// <summary> /// Once Bind has been successfully called, the inferred Xml types of the arguments can be accessed. /// </summary> public XmlQueryType GetXmlArgumentType(int index) { return _argXmlTypes[index]; } /// <summary> /// Once Bind has been successfully called, the inferred Xml type of the return value can be accessed. /// </summary> public XmlQueryType XmlReturnType { get { return _retXmlType; } } /// <summary> /// Return true if the CLR type specified in the Init() call has a matching method. /// </summary> public bool CanBind() { MethodInfo[] methods = _objectType.GetMethods(_flags); bool ignoreCase = (_flags & BindingFlags.IgnoreCase) != 0; StringComparison comparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; // Find method in object type foreach (MethodInfo methSearch in methods) { if (methSearch.Name.Equals(_name, comparison) && (_numArgs == -1 || methSearch.GetParameters().Length == _numArgs)) { // Binding to generic methods will never succeed if (!methSearch.IsGenericMethodDefinition) return true; } } return false; } /// <summary> /// Bind to the CLR type specified in the Init() call. If a matching method cannot be found, throw an exception. /// </summary> public void Bind() { MethodInfo[] methods = _objectType.GetMethods(_flags); MethodInfo methMatch = null; bool ignoreCase = (_flags & BindingFlags.IgnoreCase) != 0; StringComparison comparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; // Find method in object type foreach (MethodInfo methSearch in methods) { if (methSearch.Name.Equals(_name, comparison) && (_numArgs == -1 || methSearch.GetParameters().Length == _numArgs)) { if (methMatch != null) throw new XslTransformException(/*[XT_037]*/SR.XmlIl_AmbiguousExtensionMethod, _namespaceUri, _name, _numArgs.ToString(CultureInfo.InvariantCulture)); methMatch = methSearch; } } if (methMatch == null) { methods = _objectType.GetMethods(_flags | BindingFlags.NonPublic); foreach (MethodInfo methSearch in methods) { if (methSearch.Name.Equals(_name, comparison) && methSearch.GetParameters().Length == _numArgs) throw new XslTransformException(/*[XT_038]*/SR.XmlIl_NonPublicExtensionMethod, _namespaceUri, _name); } throw new XslTransformException(/*[XT_039]*/SR.XmlIl_NoExtensionMethod, _namespaceUri, _name, _numArgs.ToString(CultureInfo.InvariantCulture)); } if (methMatch.IsGenericMethodDefinition) throw new XslTransformException(/*[XT_040]*/SR.XmlIl_GenericExtensionMethod, _namespaceUri, _name); Debug.Assert(methMatch.ContainsGenericParameters == false); Bind(methMatch); } /// <summary> /// Bind to the specified MethodInfo. /// </summary> private void Bind(MethodInfo meth) { ParameterInfo[] paramInfo = meth.GetParameters(); int i; // Save the MethodInfo _meth = meth; // Get the Clr type of each parameter _argClrTypes = new Type[paramInfo.Length]; for (i = 0; i < paramInfo.Length; i++) _argClrTypes[i] = GetClrType(paramInfo[i].ParameterType); // Get the Clr type of the return value _retClrType = GetClrType(_meth.ReturnType); // Infer an Xml type for each Clr type _argXmlTypes = new XmlQueryType[paramInfo.Length]; for (i = 0; i < paramInfo.Length; i++) { _argXmlTypes[i] = InferXmlType(_argClrTypes[i]); // BUGBUG: // 1. A couple built-in Xslt functions allow Rtf as argument, which is // different from what InferXmlType returns. Until XsltEarlyBound references // a Qil function, we'll work around this case by assuming that all built-in // Xslt functions allow Rtf. // 2. Script arguments should allow node-sets which are not statically known // to be Dod to be passed, so relax static typing in this case. if (_namespaceUri.Length == 0) { if ((object)_argXmlTypes[i] == (object)XmlQueryTypeFactory.NodeNotRtf) _argXmlTypes[i] = XmlQueryTypeFactory.Node; else if ((object)_argXmlTypes[i] == (object)XmlQueryTypeFactory.NodeSDod) _argXmlTypes[i] = XmlQueryTypeFactory.NodeS; } else { if ((object)_argXmlTypes[i] == (object)XmlQueryTypeFactory.NodeSDod) _argXmlTypes[i] = XmlQueryTypeFactory.NodeNotRtfS; } } // Infer an Xml type for the return Clr type _retXmlType = InferXmlType(_retClrType); } /// <summary> /// Convert the incoming arguments to an array of CLR objects, and then invoke the external function on the "extObj" object instance. /// </summary> public object Invoke(object extObj, object[] args) { Debug.Assert(_meth != null, "Must call Bind() before calling Invoke."); Debug.Assert(args.Length == _argClrTypes.Length, "Mismatched number of actual and formal arguments."); try { return _meth.Invoke(extObj, args); } catch (TargetInvocationException e) { throw new XslTransformException(e.InnerException, SR.XmlIl_ExtensionError, _name); } catch (Exception e) { if (!XmlException.IsCatchableException(e)) { throw; } throw new XslTransformException(e, SR.XmlIl_ExtensionError, _name); } } /// <summary> /// Return true if this XmlExtensionFunction has the same values as another XmlExtensionFunction. /// </summary> public override bool Equals(object other) { XmlExtensionFunction that = other as XmlExtensionFunction; Debug.Assert(that != null); // Compare name, argument count, object type, and binding flags return (_hashCode == that._hashCode && _name == that._name && _namespaceUri == that._namespaceUri && _numArgs == that._numArgs && _objectType == that._objectType && _flags == that._flags); } /// <summary> /// Return this object's hash code, previously computed for performance. /// </summary> public override int GetHashCode() { return _hashCode; } /// <summary> /// 1. Map enumerations to the underlying integral type. /// 2. Throw an exception if the type is ByRef /// </summary> private Type GetClrType(Type clrType) { if (clrType.GetTypeInfo().IsEnum) return Enum.GetUnderlyingType(clrType); if (clrType.IsByRef) throw new XslTransformException(/*[XT_050]*/SR.XmlIl_ByRefType, _namespaceUri, _name); return clrType; } /// <summary> /// Infer an Xml type from a Clr type using Xslt infererence rules /// </summary> private XmlQueryType InferXmlType(Type clrType) { return XsltConvert.InferXsltType(clrType); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using StructureMap.Pipeline; using StructureMap.TypeRules; namespace StructureMap.AutoMocking { public interface IAutoMocker<TTargetClass> where TTargetClass : class { /// <summary> /// Gets an instance of the ClassUnderTest with mock objects (or stubs) pushed in for all of its dependencies /// </summary> TTargetClass ClassUnderTest { get; } /// <summary> /// Forces the auto mocking container to use a mock object /// for type T. You may have to do this for concrete types /// </summary> /// <typeparam name="T"></typeparam> void UseMockForType<T>() where T : class; /// <summary> /// Accesses the underlying AutoMockedContainer /// </summary> AutoMockedContainer Container { get; } /// <summary> /// Calling this method will immediately create a "Partial" mock /// for the ClassUnderTest using the "Greediest" constructor. /// </summary> void PartialMockTheClassUnderTest(); /// <summary> /// Gets the mock object for type T that would be injected into the constructor function /// of the ClassUnderTest /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> T Get<T>() where T : class; /// <summary> /// Method to specify the exact object that will be used for /// "pluginType." Useful for stub objects and/or static mocks /// </summary> /// <param name="pluginType"></param> /// <param name="stub"></param> void Inject(Type pluginType, object stub); /// <summary> /// Method to specify the exact object that will be used for /// "pluginType." Useful for stub objects and/or static mocks /// </summary> /// <typeparam name="T"></typeparam> /// <param name="target"></param> void Inject<T>(T target) where T : class; /// <summary> /// Adds an additional mock object for a given T /// Useful for array arguments to the ClassUnderTest /// object /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> T AddAdditionalMockFor<T>() where T : class; /// <summary> /// So that Aaron Jensen can use his concrete HubService object /// Construct whatever T is with all mocks, and make sure that the /// ClassUnderTest gets built with a concrete T /// </summary> /// <typeparam name="T"></typeparam> void UseConcreteClassFor<T>() where T : class; /// <summary> /// Creates, returns, and registers an array of mock objects for type T. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="count"></param> /// <returns></returns> T[] CreateMockArrayFor<T>(int count) where T : class; /// <summary> /// Allows you to "inject" an array of known objects for an /// argument of type T[] in the ClassUnderTest /// </summary> /// <typeparam name="T"></typeparam> /// <param name="stubs"></param> void InjectArray<T>(T[] stubs); } /// <summary> /// The Auto Mocking Container for StructureMap /// </summary> /// <typeparam name="TTargetClass"></typeparam> public class AutoMocker<TTargetClass> : IAutoMocker<TTargetClass> where TTargetClass : class { private TTargetClass _classUnderTest; public AutoMocker(ServiceLocator serviceLocator) { ServiceLocator = serviceLocator; Container = new AutoMockedContainer(ServiceLocator); Container.Configure(x => x.For<TTargetClass>().Use<TTargetClass>()); } protected ServiceLocator ServiceLocator { get; set; } public void UseMockForType<T>() where T : class { var service = ServiceLocator.Service<T>(); Container.Configure(x => x.For<T>().Use(service)); } /// <summary> /// Accesses the underlying AutoMockedContainer /// </summary> public AutoMockedContainer Container { get; protected set; } /// <summary> /// Gets an instance of the ClassUnderTest with mock objects (or stubs) pushed in for all of its dependencies /// </summary> public TTargetClass ClassUnderTest { get { if (_classUnderTest == null) { _classUnderTest = Container.GetInstance<TTargetClass>(); } return _classUnderTest; } } /// <summary> /// Calling this method will immediately create a "Partial" mock /// for the ClassUnderTest using the "Greediest" constructor. /// </summary> public void PartialMockTheClassUnderTest() { _classUnderTest = ServiceLocator.PartialMock<TTargetClass>(getConstructorArgs()); } /// <summary> /// Gets the mock object for type T that would be injected into the constructor function /// of the ClassUnderTest /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T Get<T>() where T : class { return Container.GetInstance<T>(); } /// <summary> /// Method to specify the exact object that will be used for /// "pluginType." Useful for stub objects and/or static mocks /// </summary> /// <param name="pluginType"></param> /// <param name="stub"></param> public void Inject(Type pluginType, object stub) { Container.Inject(pluginType, stub); } /// <summary> /// Method to specify the exact object that will be used for /// "pluginType." Useful for stub objects and/or static mocks /// </summary> /// <typeparam name="T"></typeparam> /// <param name="target"></param> public void Inject<T>(T target) where T : class { Container.Inject(target); } /// <summary> /// Adds an additional mock object for a given T /// Useful for array arguments to the ClassUnderTest /// object /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T AddAdditionalMockFor<T>() where T : class { var mock = ServiceLocator.Service<T>(); Container.Configure(r => r.For(typeof (T)).Add(mock)); return mock; } /// <summary> /// So that Aaron Jensen can use his concrete HubService object /// Construct whatever T is with all mocks, and make sure that the /// ClassUnderTest gets built with a concrete T /// </summary> /// <typeparam name="T"></typeparam> public void UseConcreteClassFor<T>() where T : class { Container.Configure(x => x.For<T>().Use<T>()); } /// <summary> /// Creates, returns, and registers an array of mock objects for type T. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="count"></param> /// <returns></returns> public T[] CreateMockArrayFor<T>(int count) where T : class { var returnValue = new T[count]; for (var i = 0; i < returnValue.Length; i++) { returnValue[i] = ServiceLocator.Service<T>(); } InjectArray(returnValue); return returnValue; } /// <summary> /// Allows you to "inject" an array of known objects for an /// argument of type T[] in the ClassUnderTest /// </summary> /// <typeparam name="T"></typeparam> /// <param name="stubs"></param> public void InjectArray<T>(T[] stubs) { Container.EjectAllInstancesOf<T>(); Container.Configure(x => { foreach (var t in stubs) { x.For(typeof (T)).Add(t); } }); } private object[] getConstructorArgs() { var ctor = new GreediestConstructorSelector().Find(typeof (TTargetClass), new DependencyCollection(), null); var list = new List<object>(); foreach (var parameterInfo in ctor.GetParameters()) { var dependencyType = parameterInfo.ParameterType; if (dependencyType.IsArray) { var builder = typeof (ArrayBuilder<>).CloseAndBuildAs<IEnumerableBuilder>(Container, dependencyType .GetElementType()); list.Add(builder.ToEnumerable()); } else if (dependencyType.Closes(typeof (IEnumerable<>))) { var @interface = dependencyType.FindFirstInterfaceThatCloses(typeof (IEnumerable<>)); var elementType = @interface.GetGenericArguments().First(); var builder = typeof (EnumerableBuilder<>).CloseAndBuildAs<IEnumerableBuilder>(Container, elementType); list.Add(builder.ToEnumerable()); } else { var dependency = Container.GetInstance(dependencyType); list.Add(dependency); } } return list.ToArray(); } } internal interface IEnumerableBuilder { object ToEnumerable(); } internal class ArrayBuilder<T> : IEnumerableBuilder { private readonly IContainer _container; public ArrayBuilder(IContainer container) { _container = container; } public object ToEnumerable() { return _container.GetAllInstances<T>().ToArray(); } } internal class EnumerableBuilder<T> : IEnumerableBuilder { private readonly IContainer _container; public EnumerableBuilder(IContainer container) { _container = container; } public object ToEnumerable() { return _container.GetAllInstances<T>(); } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.IO; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Xml; using System.Reflection; namespace System.Management.Automation { /// <summary> /// Class ProviderHelpProvider implement the help provider for commands. /// </summary> /// <remarks> /// Provider Help information are stored in 'help.xml' files. Location of these files /// can be found from CommandDiscovery. /// </remarks> internal class ProviderHelpProvider : HelpProviderWithCache { /// <summary> /// Constructor for HelpProvider /// </summary> internal ProviderHelpProvider(HelpSystem helpSystem) : base(helpSystem) { _sessionState = helpSystem.ExecutionContext.SessionState; } private readonly SessionState _sessionState; #region Common Properties /// <summary> /// Name of this help provider. /// </summary> /// <value>Name of this help provider.</value> internal override string Name { get { return "Provider Help Provider"; } } /// <summary> /// Help category of this provider. /// </summary> /// <value>Help category of this provider</value> internal override HelpCategory HelpCategory { get { return HelpCategory.Provider; } } #endregion #region Help Provider Interface /// <summary> /// Do exact match help based on the target. /// </summary> /// <param name="helpRequest">help request object</param> internal override IEnumerable<HelpInfo> ExactMatchHelp(HelpRequest helpRequest) { Collection<ProviderInfo> matchingProviders = null; try { matchingProviders = _sessionState.Provider.Get(helpRequest.Target); } catch (ProviderNotFoundException e) { // We distinguish two cases here, // a. If the "Provider" is the only category to search for in this case, // an error will be written. // b. Otherwise, no errors will be written since in end user's mind, // he may mean to search for provider help. if (this.HelpSystem.LastHelpCategory == HelpCategory.Provider) { ErrorRecord errorRecord = new ErrorRecord(e, "ProviderLoadError", ErrorCategory.ResourceUnavailable, null); errorRecord.ErrorDetails = new ErrorDetails(typeof(ProviderHelpProvider).GetTypeInfo().Assembly, "HelpErrors", "ProviderLoadError", helpRequest.Target, e.Message); this.HelpSystem.LastErrors.Add(errorRecord); } } if (matchingProviders != null) { foreach (ProviderInfo providerInfo in matchingProviders) { try { LoadHelpFile(providerInfo); } catch (IOException ioException) { ReportHelpFileError(ioException, helpRequest.Target, providerInfo.HelpFile); } catch (System.Security.SecurityException securityException) { ReportHelpFileError(securityException, helpRequest.Target, providerInfo.HelpFile); } catch (XmlException xmlException) { ReportHelpFileError(xmlException, helpRequest.Target, providerInfo.HelpFile); } HelpInfo helpInfo = GetCache(providerInfo.PSSnapInName + "\\" + providerInfo.Name); if (helpInfo != null) { yield return helpInfo; } } } } private static string GetProviderAssemblyPath(ProviderInfo providerInfo) { if (providerInfo == null) return null; if (providerInfo.ImplementingType == null) return null; return Path.GetDirectoryName(providerInfo.ImplementingType.GetTypeInfo().Assembly.Location); } /// <summary> /// This is a hashtable to track which help files are loaded already. /// /// This will avoid one help file getting loaded again and again. /// (Which should not happen unless some provider is pointing /// to a help file that actually doesn't contain the help for it). /// /// </summary> private readonly Hashtable _helpFiles = new Hashtable(); /// <summary> /// Load help file provided. /// </summary> /// <remarks> /// This will load providerHelpInfo from help file into help cache. /// </remarks> /// <param name="providerInfo">providerInfo for which to locate help.</param> private void LoadHelpFile(ProviderInfo providerInfo) { if (providerInfo == null) { throw PSTraceSource.NewArgumentNullException("providerInfo"); } string helpFile = providerInfo.HelpFile; if (String.IsNullOrEmpty(helpFile) || _helpFiles.Contains(helpFile)) { return; } string helpFileToLoad = helpFile; // Get the mshsnapinfo object for this cmdlet. PSSnapInInfo mshSnapInInfo = providerInfo.PSSnapIn; // Search fallback // 1. If PSSnapInInfo exists, then always look in the application base // of the mshsnapin // Otherwise, // Look in the default search path and cmdlet assembly path Collection<String> searchPaths = new Collection<String>(); if (mshSnapInInfo != null) { Diagnostics.Assert(!string.IsNullOrEmpty(mshSnapInInfo.ApplicationBase), "Application Base is null or empty."); // not minishell case.. // we have to search only in the application base for a mshsnapin... // if you create an absolute path for helpfile, then MUIFileSearcher // will look only in that path. helpFileToLoad = Path.Combine(mshSnapInInfo.ApplicationBase, helpFile); } else if ((providerInfo.Module != null) && (!string.IsNullOrEmpty(providerInfo.Module.Path))) { helpFileToLoad = Path.Combine(providerInfo.Module.ModuleBase, helpFile); } else { searchPaths.Add(GetDefaultShellSearchPath()); searchPaths.Add(GetProviderAssemblyPath(providerInfo)); } string location = MUIFileSearcher.LocateFile(helpFileToLoad, searchPaths); if (String.IsNullOrEmpty(location)) throw new FileNotFoundException(helpFile); XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument( new FileInfo(location), false, /* ignore whitespace, comments, etc. */ null); /* default maxCharactersInDocument */ // Add this file into _helpFiles hashtable to prevent it to be loaded again. _helpFiles[helpFile] = 0; XmlNode helpItemsNode = null; if (doc.HasChildNodes) { for (int i = 0; i < doc.ChildNodes.Count; i++) { XmlNode node = doc.ChildNodes[i]; if (node.NodeType == XmlNodeType.Element && String.Compare(node.Name, "helpItems", StringComparison.OrdinalIgnoreCase) == 0) { helpItemsNode = node; break; } } } if (helpItemsNode == null) return; using (this.HelpSystem.Trace(location)) { if (helpItemsNode.HasChildNodes) { for (int i = 0; i < helpItemsNode.ChildNodes.Count; i++) { XmlNode node = helpItemsNode.ChildNodes[i]; if (node.NodeType == XmlNodeType.Element && String.Compare(node.Name, "providerHelp", StringComparison.OrdinalIgnoreCase) == 0) { HelpInfo helpInfo = ProviderHelpInfo.Load(node); if (helpInfo != null) { this.HelpSystem.TraceErrors(helpInfo.Errors); // Add snapin qualified type name for this command.. // this will enable customizations of the help object. helpInfo.FullHelp.TypeNames.Insert(0, string.Format(CultureInfo.InvariantCulture, "ProviderHelpInfo#{0}#{1}", providerInfo.PSSnapInName, helpInfo.Name)); if (!string.IsNullOrEmpty(providerInfo.PSSnapInName)) { helpInfo.FullHelp.Properties.Add(new PSNoteProperty("PSSnapIn", providerInfo.PSSnapIn)); helpInfo.FullHelp.TypeNames.Insert(1, string.Format(CultureInfo.InvariantCulture, "ProviderHelpInfo#{0}", providerInfo.PSSnapInName)); } AddCache(providerInfo.PSSnapInName + "\\" + helpInfo.Name, helpInfo); } } } } } } /// <summary> /// Search for provider help based on a search target. /// </summary> /// <param name="helpRequest">help request object</param> /// <param name="searchOnlyContent"> /// If true, searches for pattern in the help content. Individual /// provider can decide which content to search in. /// /// If false, searches for pattern in the command names. /// </param> /// <returns></returns> internal override IEnumerable<HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent) { int countOfHelpInfoObjectsFound = 0; string target = helpRequest.Target; string pattern = target; // this will be used only when searchOnlyContent == true WildcardPattern wildCardPattern = null; bool decoratedSearch = !WildcardPattern.ContainsWildcardCharacters(target); if (!searchOnlyContent) { if (decoratedSearch) { pattern += "*"; } } else { string searchTarget = helpRequest.Target; if (decoratedSearch) { searchTarget = "*" + helpRequest.Target + "*"; } wildCardPattern = WildcardPattern.Get(searchTarget, WildcardOptions.Compiled | WildcardOptions.IgnoreCase); // search in all providers pattern = "*"; } PSSnapinQualifiedName snapinQualifiedNameForPattern = PSSnapinQualifiedName.GetInstance(pattern); if (null == snapinQualifiedNameForPattern) { yield break; } foreach (ProviderInfo providerInfo in _sessionState.Provider.GetAll()) { if (providerInfo.IsMatch(pattern)) { try { LoadHelpFile(providerInfo); } catch (IOException ioException) { if (!decoratedSearch) { ReportHelpFileError(ioException, providerInfo.Name, providerInfo.HelpFile); } } catch (System.Security.SecurityException securityException) { if (!decoratedSearch) { ReportHelpFileError(securityException, providerInfo.Name, providerInfo.HelpFile); } } catch (XmlException xmlException) { if (!decoratedSearch) { ReportHelpFileError(xmlException, providerInfo.Name, providerInfo.HelpFile); } } HelpInfo helpInfo = GetCache(providerInfo.PSSnapInName + "\\" + providerInfo.Name); if (helpInfo != null) { if (searchOnlyContent) { // ignore help objects that do not have pattern in its help // content. if (!helpInfo.MatchPatternInContent(wildCardPattern)) { continue; } } countOfHelpInfoObjectsFound++; yield return helpInfo; if (countOfHelpInfoObjectsFound >= helpRequest.MaxResults && helpRequest.MaxResults > 0) yield break; } } } } internal override IEnumerable<HelpInfo> ProcessForwardedHelp(HelpInfo helpInfo, HelpRequest helpRequest) { ProviderCommandHelpInfo providerCommandHelpInfo = new ProviderCommandHelpInfo( helpInfo, helpRequest.ProviderContext); yield return providerCommandHelpInfo; } #if V2 /// <summary> /// Process a helpInfo forwarded from other providers (normally commandHelpProvider) /// </summary> /// <remarks> /// For command help info, this will /// 1. check whether provider-specific commandlet help exists. /// 2. merge found provider-specific help with commandlet help provided. /// </remarks> /// <param name="helpInfo">helpInfo forwarded in</param> /// <param name="helpRequest">help request object</param> /// <returns>The help info object after processing</returns> override internal HelpInfo ProcessForwardedHelp(HelpInfo helpInfo, HelpRequest helpRequest) { if (helpInfo == null) return null; if (helpInfo.HelpCategory != HelpCategory.Command) { return helpInfo; } string providerName = helpRequest.Provider; if (String.IsNullOrEmpty(providerName)) { providerName = this._sessionState.Path.CurrentLocation.Provider.Name; } HelpRequest providerHelpRequest = helpRequest.Clone(); providerHelpRequest.Target = providerName; ProviderHelpInfo providerHelpInfo = (ProviderHelpInfo)this.ExactMatchHelp(providerHelpRequest); if (providerHelpInfo == null) return null; CommandHelpInfo commandHelpInfo = (CommandHelpInfo)helpInfo; CommandHelpInfo result = commandHelpInfo.MergeProviderSpecificHelp(providerHelpInfo.GetCmdletHelp(commandHelpInfo.Name), providerHelpInfo.GetDynamicParameterHelp(helpRequest.DynamicParameters)); // Reset ForwardHelpCategory for the helpinfo to be returned so that it will not be forwarded back again. result.ForwardHelpCategory = HelpCategory.None; return result; } #endif /// <summary> /// This will reset the help cache. Normally this corresponds to a /// help culture change. /// </summary> internal override void Reset() { base.Reset(); _helpFiles.Clear(); } #endregion } }