context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using HelloWebAPI.Areas.HelpPage.Models; namespace HelloWebAPI.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// 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 // // 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 GgpGrpc.Cloud; using GgpGrpc.Models; using Google.VisualStudioFake.API; using Google.VisualStudioFake.Internal; using Google.VisualStudioFake.Util; using Microsoft.VisualStudio.Debugger.Interop; using Microsoft.VisualStudio.Threading; using NUnit.Framework; using System.Collections.Generic; using System.IO; using System.Linq; using TestsCommon.TestSupport; using YetiCommon; using YetiVSI.ProjectSystem.Abstractions; using YetiVSI.Test.MediumTestsSupport; using YetiVSI.Util; using YetiVSITestsCommon; namespace YetiVSI.Test.GameLaunch { public class LaunchApiMediumTests { static LaunchApiMediumTests() { if (!Microsoft.Build.Locator.MSBuildLocator.IsRegistered) { Microsoft.Build.Locator.MSBuildLocator.RegisterDefaults(); } } static readonly string _sampleDir = Path.Combine(YetiConstants.RootDir, @"TestData\"); const string _sampleName = "StubTestSample"; NLogSpy _nLogSpy; MediumTestDebugEngineFactoryCompRoot _compRoot; FakeMainThreadContext _threadContext; JoinableTaskContext _taskContext; VSFakeCompRoot _vsFakeCompRoot; const string _instanceLocation = "location-east-4/instance-1"; const string _applicationName = "Yeti Development Application"; [SetUp] public void SetUp() { _nLogSpy = NLogSpy.CreateUnique(nameof(LaunchApiMediumTests)); _nLogSpy.Attach(); _threadContext = new FakeMainThreadContext(); _taskContext = _threadContext.JoinableTaskContext; } [TearDown] public void TearDown() { _threadContext.Dispose(); } [Test] public void LaunchRequestIsSentOnLaunchSuspended() { var launches = new List<LaunchGameRequest>(); var gameletClientFactory = new GameletClientStub.Factory().WithSampleInstance() .WithLaunchRequestsTracker(launches); IVSFake vsFake = CreateVsFakeAndLoadProject(gameletClientFactory); _taskContext.RunOnMainThread(() => vsFake.LaunchSuspended()); Assert.That(launches.Count, Is.EqualTo(1)); Assert.That(launches[0].GameletName, Is.EqualTo(_instanceLocation)); Assert.That(launches[0].ApplicationName, Is.EqualTo(_applicationName)); Assert.That(launches[0].ExecutablePath, Does.Contain(_sampleName)); } [Test] public void EnvironmentVariablesArePropagatedToLaunchRequest() { var launches = new List<LaunchGameRequest>(); var gameletClientFactory = new GameletClientStub.Factory().WithSampleInstance() .WithLaunchRequestsTracker(launches); IVSFake vsFake = CreateVsFakeAndLoadProject(gameletClientFactory); (vsFake.ProjectAdapter as ProjectAdapter)?.SetGameletEnvironmentVariables( "v1=1;v2=stringValue"); _taskContext.RunOnMainThread(() => vsFake.LaunchSuspended()); Assert.That(launches.Count, Is.EqualTo(1)); Assert.That(launches[0].EnvironmentVariablePairs, Is.EqualTo(new Dictionary<string, string> { { "v1", "1" }, { "v2", "stringValue" } })); } [Test] public void EnvironmentVariablesArePropagatedWhenSpecifiedViaQueryParams() { var launches = new List<LaunchGameRequest>(); var gameletClientFactory = new GameletClientStub.Factory().WithSampleInstance() .WithLaunchRequestsTracker(launches); IVSFake vsFake = CreateVsFakeAndLoadProject(gameletClientFactory); (vsFake.ProjectAdapter as ProjectAdapter)?.SetQueryParams( "stream_profile_preset=HIGH_VISUAL_QUALITY&streamer_fixed_fps=120"); _taskContext.RunOnMainThread(() => vsFake.LaunchSuspended()); Assert.That(launches.Count, Is.EqualTo(1)); Assert.That(launches[0].StreamQualityPreset, Is.EqualTo(StreamQualityPreset.HighVisualQuality)); Assert.That(launches[0].StreamerFixedFps, Is.EqualTo(120)); } [Test] public void RenderDocPropertyIsPropagatedToLaunchRequest() { var launches = new List<LaunchGameRequest>(); var gameletClientFactory = new GameletClientStub.Factory().WithSampleInstance() .WithLaunchRequestsTracker(launches); IVSFake vsFake = CreateVsFakeAndLoadProject(gameletClientFactory); (vsFake.ProjectAdapter as ProjectAdapter)?.SetLaunchRenderDoc(true); _taskContext.RunOnMainThread(() => vsFake.LaunchSuspended()); Assert.That(launches.Count, Is.EqualTo(1)); Assert.That(launches[0].EnvironmentVariablePairs, Is.EqualTo( new Dictionary<string, string> { { "ENABLE_VULKAN_RENDERDOC_CAPTURE", "1" }, { "RENDERDOC_TEMP", "/mnt/developer/ggp" }, { "RENDERDOC_DEBUG_LOG_FILE", "/var/game/RDDebug.log" } })); } [Test] public void SurfaceEnforcementPropertyIsPropagatedToLaunchRequest() { var launches = new List<LaunchGameRequest>(); var gameletClientFactory = new GameletClientStub.Factory().WithSampleInstance() .WithLaunchRequestsTracker(launches); IVSFake vsFake = CreateVsFakeAndLoadProject(gameletClientFactory); (vsFake.ProjectAdapter as ProjectAdapter)?.SetSurfaceEnforcement( SurfaceEnforcementSetting.Block); _taskContext.RunOnMainThread(() => vsFake.LaunchSuspended()); Assert.That(launches.Count, Is.EqualTo(1)); Assert.That(launches[0].SurfaceEnforcementMode, Is.EqualTo(SurfaceEnforcementSetting.Block)); } [Test] public void VulkanDriverVariantIsPropagatedToLaunchRequest() { var launches = new List<LaunchGameRequest>(); var gameletClientFactory = new GameletClientStub.Factory().WithSampleInstance() .WithLaunchRequestsTracker(launches); IVSFake vsFake = CreateVsFakeAndLoadProject(gameletClientFactory); (vsFake.ProjectAdapter as ProjectAdapter)?.SetVulkanDriverVariant( "vulkan-driver-variant"); _taskContext.RunOnMainThread(() => vsFake.LaunchSuspended()); Assert.That(launches[0].EnvironmentVariablePairs, Is.EqualTo( new Dictionary<string, string> { { "GGP_DEV_VK_DRIVER_VARIANT", "vulkan-driver-variant" } })); } [Test] public void LaunchRgpIsPropagatedToLaunchRequest() { var launches = new List<LaunchGameRequest>(); var gameletClientFactory = new GameletClientStub.Factory().WithSampleInstance() .WithLaunchRequestsTracker(launches); IVSFake vsFake = CreateVsFakeAndLoadProject(gameletClientFactory); (vsFake.ProjectAdapter as ProjectAdapter)?.SetLaunchRgp(true); _taskContext.RunOnMainThread(() => vsFake.LaunchSuspended()); Assert.That(launches.Count, Is.EqualTo(1)); Assert.That(launches[0].EnvironmentVariablePairs, Is.EqualTo( new Dictionary<string, string> { { "GGP_INTERNAL_LOAD_RGP", "1" }, { "RGP_DEBUG_LOG_FILE", "/var/game/RGPDebug.log" }, { "LD_PRELOAD", "librgpserver.so" } })); } [Test] public void LaunchDiveIsPropagatedToLaunchRequest() { var launches = new List<LaunchGameRequest>(); var gameletClientFactory = new GameletClientStub.Factory().WithSampleInstance().WithLaunchRequestsTracker( launches); IVSFake vsFake = CreateVsFakeAndLoadProject(gameletClientFactory); (vsFake.ProjectAdapter as ProjectAdapter)?.SetLaunchDive(true); _taskContext.RunOnMainThread(() => vsFake.LaunchSuspended()); Assert.That(launches.Count, Is.EqualTo(1)); Assert.That( launches[0].EnvironmentVariablePairs, Is.EqualTo( new Dictionary<string, string> { { "GGP_INTERNAL_LOAD_RGP", "1" }, { "RGP_DEBUG_LOG_FILE", "/var/game/RGPDebug.log" }, { "VK_INSTANCE_LAYERS", "VK_LAYER_dive_capture" }, { "LD_PRELOAD", "librgpserver.so" } })); } [Test] public void LaunchOrbitIsPropagatedToLaunchRequest() { var launches = new List<LaunchGameRequest>(); var gameletClientFactory = new GameletClientStub.Factory().WithSampleInstance().WithLaunchRequestsTracker( launches); IVSFake vsFake = CreateVsFakeAndLoadProject(gameletClientFactory); (vsFake.ProjectAdapter as ProjectAdapter)?.SetLaunchOrbit(true); _taskContext.RunOnMainThread(() => vsFake.LaunchSuspended()); Assert.That(launches.Count, Is.EqualTo(1)); Assert.That(launches[0].EnvironmentVariablePairs, Is.EqualTo(new Dictionary<string, string> { { "ENABLE_ORBIT_VULKAN_LAYER", "1" } })); } [Test] public void TestAccountIsPropagatedToLaunchRequest() { var launches = new List<LaunchGameRequest>(); var gameletClientFactory = new GameletClientStub.Factory().WithSampleInstance() .WithLaunchRequestsTracker(launches); IVSFake vsFake = CreateVsFakeAndLoadProject(gameletClientFactory); (vsFake.ProjectAdapter as ProjectAdapter)?.SetTestAccount("gamer#1234"); _taskContext.RunOnMainThread(() => vsFake.LaunchSuspended()); Assert.That(launches.Count, Is.EqualTo(1)); Assert.That(launches[0].Parent, Does.Contain("testAccounts/gamer#1234")); } [Test] public void ErrorIsShownWhenPropertiesParsingFailed() { var gameletClientFactory = new GameletClientStub.Factory().WithSampleInstance(); IVSFake vsFake = CreateVsFakeAndLoadProject(gameletClientFactory); (vsFake.ProjectAdapter as ProjectAdapter)?.SetQueryParams("cmd=wrongBinaryName"); Assert.Throws<DialogUtilFake.DialogException>( () => _taskContext.RunOnMainThread(() => vsFake.LaunchSuspended())); DialogUtilFake.Message errorMessage = (_compRoot.GetDialogUtil() as DialogUtilFake)?.Messages.Last(); Assert.That(errorMessage?.Text, Does.Contain("invalid binary name: 'wrongBinaryName'")); } IVSFake CreateVsFakeAndLoadProject(IGameletClientFactory gameletClientFactory) { IVSFake vsFake = CreateVsFake(gameletClientFactory); // For this test we don't need to launch / build binaries. The test assets contain // fake binaries in StubTestSample/GGP/Debug. vsFake.ProjectAdapter.Load(_sampleName); (vsFake.ProjectAdapter as ProjectAdapter)?.SetDeployOnLaunch( DeployOnLaunchSetting.FALSE); return vsFake; } IVSFake CreateVsFake(IGameletClientFactory gameletClientFactory) { var serviceManager = new MediumTestServiceManager(_taskContext, CreateVsiOptions()); _compRoot = new MediumTestDebugEngineFactoryCompRoot( serviceManager, _taskContext, gameletClientFactory, TestDummyGenerator.Create<IWindowsRegistry>()); IDebugEngine2 CreateDebugEngine() => _compRoot.CreateDebugEngineFactory().Create(null); InitVsFakeCompRoot(serviceManager, gameletClientFactory); return _vsFakeCompRoot.Create(CreateDebugEngine); } void InitVsFakeCompRoot(ServiceManager serviceManager, IGameletClientFactory gameletClientFactory) { var config = new VSFakeCompRoot.Config { SamplesRoot = _sampleDir }; var dialogUtil = new DialogUtilFake(); var debugTargetCompRoot = new MediumTestGgpDebugQueryTargetCompRoot(serviceManager, dialogUtil, gameletClientFactory); _taskContext.RunOnMainThread(() => { var debugTargetWrapperFactory = new GgpDebugQueryTargetWrapperFactory( debugTargetCompRoot.Create(), _taskContext, new ManagedProcess.Factory()); _vsFakeCompRoot = new VSFakeCompRoot(config, debugTargetWrapperFactory, _taskContext, _nLogSpy.GetLogger()); }); } OptionPageGrid CreateVsiOptions() { var vsiOptions = OptionPageGrid.CreateForTesting(); return vsiOptions; } } }
#if !NOSOCKET using NBitcoin.Crypto; using NBitcoin.Protocol.Behaviors; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using NBitcoin.Logging; namespace NBitcoin.Protocol { /// <summary> /// The AddressManager, keep a set of peers discovered on the network in cache can update their actual states. /// Replicate AddressManager of Bitcoin Core, the Buckets and BucketPosition are not guaranteed to be coherent with Bitcoin Core /// </summary> public class AddressManager : IBitcoinSerializable { // Serialization versions. private const byte V0_HISTORICAL = 0; // historic format, before bitcoin core commit e6b343d88 private const byte V1_DETERMINISTIC = 1; // for pre-asmap files private const byte V2_ASMAP = 2; // for files including asmap version private const byte V3_BIP155 = 3; // same as V2_ASMAP plus addresses are in BIP155 format public IDnsResolver DnsResolver { get; set; } /// <summary> /// Will properly convert a endpoint to IPEndpoint /// If endpoint is a DNSEndpoint, a DNS resolution will be made and all addresses added /// If endpoint is a DNSEndpoint for onion, it will be converted into onioncat address /// If endpoint is an IPEndpoint it is added to AddressManager /// </summary> /// <param name="endpoint">The endpoint to add to the address manager</param> /// <param name="source">The source which advertized this endpoint (default: IPAddress.Loopback)</param> /// <returns></returns> public Task AddAsync(EndPoint endpoint, IPAddress source = null) { return AddAsync(endpoint, source, default); } /// <summary> /// Will properly convert a endpoint to IPEndpoint /// If endpoint is a DNSEndpoint, a DNS resolution will be made and all addresses added /// If endpoint is a DNSEndpoint for onion, it will be converted into onioncat address /// If endpoint is an IPEndpoint it is added to AddressManager /// </summary> /// <param name="endpoint">The endpoint to add to the address manager</param> /// <param name="source">The source which advertized this endpoint (default: IPAddress.Loopback)</param> /// <param name="cancellationToken">The cancellationToken</param> /// <returns></returns> public async Task AddAsync(EndPoint endpoint, IPAddress source, CancellationToken cancellationToken) { if (endpoint == null) throw new ArgumentNullException(nameof(endpoint)); if (source == null) source = IPAddress.Loopback; if (endpoint is DnsEndPoint && !endpoint.IsI2P() && !endpoint.IsTor()) { foreach (var ip in (await endpoint.ResolveToIPEndpointsAsync(DnsResolver, cancellationToken).ConfigureAwait(false))) { Add(new NetworkAddress(ip), source); } } else { Add(new NetworkAddress(endpoint), source); } } internal class AddressInfo : IBitcoinSerializable { #region IBitcoinSerializable Members public void ReadWrite(BitcoinStream stream) { stream.ReadWrite(ref _Address); stream.ReadWrite(ref source); stream.ReadWrite(ref nLastSuccess); stream.ReadWrite(ref nAttempts); } internal int nAttempts; internal long nLastSuccess; byte[] source = new byte[16]; public DateTimeOffset LastSuccess { get { return Utils.UnixTimeToDateTime((uint)nLastSuccess); } set { nLastSuccess = Utils.DateTimeToUnixTime(value); } } public IPAddress Source { get { return new IPAddress(source); } set { var ipBytes = value.GetAddressBytes(); if (ipBytes.Length == 16) { source = ipBytes; } else if (ipBytes.Length == 4) { //Convert to ipv4 mapped to ipv6 //In these addresses, the first 80 bits are zero, the next 16 bits are one, and the remaining 32 bits are the IPv4 address source = new byte[16]; Array.Copy(ipBytes, 0, source, 12, 4); Array.Copy(new byte[] { 0xFF, 0xFF }, 0, source, 10, 2); } else throw new NotSupportedException("Invalid IP address type"); } } NetworkAddress _Address; public int nRandomPos = -1; public int nRefCount; public bool fInTried; internal long nLastTry; internal DateTimeOffset nTime { get { return Address.Time; } set { Address.Time = value; } } public AddressInfo() { } public AddressInfo(NetworkAddress addr, IPAddress addrSource) { Address = addr; Source = addrSource; } public bool IsTerrible { get { return _IsTerrible(DateTimeOffset.UtcNow); } } internal DateTimeOffset LastTry { get { return Utils.UnixTimeToDateTime((uint)nLastSuccess); } set { nLastTry = Utils.DateTimeToUnixTime(value); } } public NetworkAddress Address { get { return _Address; } set { _Address = value; } } #endregion internal int GetNewBucket(uint256 nKey) { return GetNewBucket(nKey, Source); } internal int GetNewBucket(uint256 nKey, IPAddress src) { byte[] vchSourceGroupKey = src.GetGroup(); UInt64 hash1 = Cheap(Hashes.DoubleSHA256( nKey.ToBytes(true) .Concat(Address.Endpoint.GetGroup()) .Concat(vchSourceGroupKey) .ToArray())); UInt64 hash2 = Cheap(Hashes.DoubleSHA256( nKey.ToBytes(true) .Concat(vchSourceGroupKey) .Concat(Utils.ToBytes(hash1 % AddressManager.ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP, true)) .ToArray())); return (int)(hash2 % ADDRMAN_NEW_BUCKET_COUNT); } private ulong Cheap(uint256 v) { return Utils.ToUInt64(v.ToBytes(), true); } internal int GetBucketPosition(uint256 nKey, bool fNew, int nBucket) { UInt64 hash1 = Cheap( Hashes.DoubleSHA256( nKey.ToBytes() .Concat(new byte[] { (fNew ? (byte)'N' : (byte)'K') }) .Concat(Utils.ToBytes((uint)nBucket, false)) .Concat(Address.GetKey()) .ToArray())); return (int)(hash1 % ADDRMAN_BUCKET_SIZE); } internal int GetTriedBucket(uint256 nKey) { UInt64 hash1 = Cheap(Hashes.DoubleSHA256(nKey.ToBytes().Concat(Address.GetKey()).ToArray())); UInt64 hash2 = Cheap(Hashes.DoubleSHA256(nKey.ToBytes().Concat(Address.Endpoint.GetGroup()).Concat(Utils.ToBytes(hash1 % AddressManager.ADDRMAN_TRIED_BUCKETS_PER_GROUP, true)).ToArray())); return (int)(hash2 % ADDRMAN_TRIED_BUCKET_COUNT); } internal bool _IsTerrible(DateTimeOffset now) { if (nLastTry != 0 && LastTry >= now - TimeSpan.FromSeconds(60)) // never remove things tried in the last minute return false; if (Address.Time > now + TimeSpan.FromSeconds(10 * 60)) // came in a flying DeLorean return true; if (Address.nTime == 0 || now - Address.Time > TimeSpan.FromSeconds(ADDRMAN_HORIZON_DAYS * 24 * 60 * 60)) // not seen in recent history return true; if (nLastSuccess == 0 && nAttempts >= AddressManager.ADDRMAN_RETRIES) // tried N times and never a success return true; if (now - LastSuccess > TimeSpan.FromSeconds(ADDRMAN_MIN_FAIL_DAYS * 24 * 60 * 60) && nAttempts >= AddressManager.ADDRMAN_MAX_FAILURES) // N successive failures in the last week return true; return false; } internal bool Match(NetworkAddress addr) { return Address.Endpoint.IsEqualTo(addr.Endpoint); } internal double Chance { get { return GetChance(DateTimeOffset.UtcNow); } } //! Calculate the relative chance this entry should be given when selecting nodes to connect to internal double GetChance(DateTimeOffset nNow) { double fChance = 1.0; var nSinceLastSeen = nNow - nTime; var nSinceLastTry = nNow - LastTry; if (nSinceLastSeen < TimeSpan.Zero) nSinceLastSeen = TimeSpan.Zero; if (nSinceLastTry < TimeSpan.Zero) nSinceLastTry = TimeSpan.Zero; // deprioritize very recent attempts away if (nSinceLastTry < TimeSpan.FromSeconds(60 * 10)) fChance *= 0.01; // deprioritize 66% after each failed attempt, but at most 1/28th to avoid the search taking forever or overly penalizing outages. fChance *= Math.Pow(0.66, Math.Min(nAttempts, 8)); return fChance; } } //! total number of buckets for tried addresses internal const int ADDRMAN_TRIED_BUCKET_COUNT = 256; //! total number of buckets for new addresses internal const int ADDRMAN_NEW_BUCKET_COUNT = 1024; //! maximum allowed number of entries in buckets for new and tried addresses internal const int ADDRMAN_BUCKET_SIZE = 64; //! over how many buckets entries with tried addresses from a single group (/16 for IPv4) are spread internal const int ADDRMAN_TRIED_BUCKETS_PER_GROUP = 8; //! over how many buckets entries with new addresses originating from a single group are spread internal const int ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP = 64; //! in how many buckets for entries with new addresses a single address may occur const int ADDRMAN_NEW_BUCKETS_PER_ADDRESS = 8; //! how old addresses can maximally be internal const int ADDRMAN_HORIZON_DAYS = 30; //! after how many failed attempts we give up on a new node internal const int ADDRMAN_RETRIES = 3; //! how many successive failures are allowed ... internal const int ADDRMAN_MAX_FAILURES = 10; //! ... in at least this many days internal const int ADDRMAN_MIN_FAIL_DAYS = 7; //! the maximum percentage of nodes to return in a getaddr call const int ADDRMAN_GETADDR_MAX_PCT = 23; //! the maximum number of nodes to return in a getaddr call const int ADDRMAN_GETADDR_MAX = 2500; #if !NOFILEIO public static AddressManager LoadPeerFile(string filePath, Network expectedNetwork = null) { var addrman = new AddressManager(); byte[] data, hash; using (var fs = File.Open(filePath, FileMode.Open, FileAccess.Read)) { data = new byte[fs.Length - 32]; fs.Read(data, 0, data.Length); hash = new byte[32]; fs.Read(hash, 0, 32); } var actual = Hashes.DoubleSHA256(data); var expected = new uint256(hash); if (expected != actual) throw new FormatException("Invalid address manager file"); BitcoinStream stream = new BitcoinStream(data); stream.Type = SerializationType.Disk; uint magic = 0; stream.ReadWrite(ref magic); if (expectedNetwork != null && expectedNetwork.Magic != magic) { throw new FormatException("This file is not for the expected network"); } addrman.ReadWrite(stream); return addrman; } public void SavePeerFile(string filePath, Network network) { if (network == null) throw new ArgumentNullException(nameof(network)); if (filePath == null) throw new ArgumentNullException(nameof(filePath)); MemoryStream ms = new MemoryStream(); BitcoinStream stream = new BitcoinStream(ms, true); stream.Type = SerializationType.Disk; stream.ReadWrite(network.Magic); stream.ReadWrite(this); var hash = Hashes.DoubleSHA256(ms.ToArray()); stream.ReadWrite(hash.AsBitcoinSerializable()); string dirPath = Path.GetDirectoryName(filePath); if (!string.IsNullOrWhiteSpace(dirPath)) { Directory.CreateDirectory(dirPath); } File.WriteAllBytes(filePath, ms.ToArray()); } #endif AddressInfo Find(NetworkAddress addr) { int unused; return Find(addr, out unused); } AddressInfo Find(NetworkAddress addr, out int pnId) { if (!mapAddr.TryGetValue(addr.ToAddressString(), out pnId)) return null; return mapInfo.TryGet(pnId); } public AddressManager() { Clear(); } private void Clear() { vRandom = new List<int>(); nKey = new uint256(RandomUtils.GetBytes(32)); vvNew = new int[ADDRMAN_NEW_BUCKET_COUNT, ADDRMAN_BUCKET_SIZE]; for (int i = 0; i < ADDRMAN_NEW_BUCKET_COUNT; i++) for (int j = 0; j < ADDRMAN_BUCKET_SIZE; j++) vvNew[i, j] = -1; vvTried = new int[ADDRMAN_TRIED_BUCKET_COUNT, ADDRMAN_BUCKET_SIZE]; for (int i = 0; i < ADDRMAN_TRIED_BUCKET_COUNT; i++) for (int j = 0; j < ADDRMAN_BUCKET_SIZE; j++) vvTried[i, j] = -1; nIdCount = 0; nTried = 0; nNew = 0; } byte nVersion = V3_BIP155; byte nKeySize = 32; internal uint256 nKey; internal int nNew; internal int nTried; List<int> vRandom; int[,] vvNew; int[,] vvTried; public int DiscoveredPeers => _DiscoveredPeers; int _DiscoveredPeers; // no auto-property because used as ref parameter below public int NeededPeers { get; private set; } Dictionary<int, AddressInfo> mapInfo = new Dictionary<int, AddressInfo>(); Dictionary<string, int> mapAddr = new Dictionary<string, int>(); private int nIdCount; #region IBitcoinSerializable Members public void ReadWrite(BitcoinStream stream) { lock (cs) { Check(); if (!stream.Serializing) Clear(); stream.ReadWrite(ref nVersion); if (nVersion >= V3_BIP155) stream.ProtocolVersion = (stream.ProtocolVersion ?? 0) | NetworkAddress.AddrV2Format; stream.ReadWrite(ref nKeySize); if (!stream.Serializing && nKeySize != 32) throw new FormatException("Incorrect keysize in addrman deserialization"); stream.ReadWrite(ref nKey); stream.ReadWrite(ref nNew); stream.ReadWrite(ref nTried); int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30); stream.ReadWrite(ref nUBuckets); if (nVersion > V0_HISTORICAL) { nUBuckets ^= (1 << 30); } if (!stream.Serializing) { // Deserialize entries from the new table. for (int n = 0; n < nNew; n++) { AddressInfo info = new AddressInfo(); info.ReadWrite(stream); mapInfo.Add(n, info); mapAddr[info.Address.ToAddressString()] = n; info.nRandomPos = vRandom.Count; vRandom.Add(n); if (nVersion == V0_HISTORICAL || nUBuckets != ADDRMAN_NEW_BUCKET_COUNT) { // In case the new table data cannot be used (nVersion unknown/historical, or bucket count wrong), // immediately try to give them a reference based on their primary source address. int nUBucket = info.GetNewBucket(nKey); int nUBucketPos = info.GetBucketPosition(nKey, true, nUBucket); if (vvNew[nUBucket, nUBucketPos] == -1) { vvNew[nUBucket, nUBucketPos] = n; info.nRefCount++; } } } nIdCount = nNew; // Deserialize entries from the tried table. int nLost = 0; for (int n = 0; n < nTried; n++) { AddressInfo info = new AddressInfo(); info.ReadWrite(stream); int nKBucket = info.GetTriedBucket(nKey); int nKBucketPos = info.GetBucketPosition(nKey, false, nKBucket); if (vvTried[nKBucket, nKBucketPos] == -1) { info.nRandomPos = vRandom.Count; info.fInTried = true; vRandom.Add(nIdCount); mapInfo[nIdCount] = info; mapAddr[info.Address.ToAddressString()] = nIdCount; vvTried[nKBucket, nKBucketPos] = nIdCount; nIdCount++; } else { nLost++; } } nTried -= nLost; // Deserialize positions in the new table (if possible). for (int bucket = 0; bucket < nUBuckets; bucket++) { int nSize = 0; stream.ReadWrite(ref nSize); for (int n = 0; n < nSize; n++) { int nIndex = 0; stream.ReadWrite(ref nIndex); if (nIndex >= 0 && nIndex < nNew) { AddressInfo info = mapInfo[nIndex]; int nUBucketPos = info.GetBucketPosition(nKey, true, bucket); if (nVersion >= V1_DETERMINISTIC && nUBuckets == ADDRMAN_NEW_BUCKET_COUNT && vvNew[bucket, nUBucketPos] == -1 && info.nRefCount < ADDRMAN_NEW_BUCKETS_PER_ADDRESS) { info.nRefCount++; vvNew[bucket, nUBucketPos] = nIndex; } } } } // Prune new entries with refcount 0 (as a result of collisions). int nLostUnk = 0; foreach (var kv in mapInfo.ToList()) { if (kv.Value.fInTried == false && kv.Value.nRefCount == 0) { Delete(kv.Key); nLostUnk++; } } } else { Dictionary<int, int> mapUnkIds = new Dictionary<int, int>(); int nIds = 0; foreach (var kv in mapInfo) { mapUnkIds[kv.Key] = nIds; AddressInfo info = kv.Value; if (info.nRefCount != 0) { assert(nIds != nNew); // this means nNew was wrong, oh ow info.ReadWrite(stream); nIds++; } } nIds = 0; foreach (var kv in mapInfo) { AddressInfo info = kv.Value; if (info.fInTried) { assert(nIds != nTried); // this means nTried was wrong, oh ow info.ReadWrite(stream); nIds++; } } for (int bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++) { int nSize = 0; for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) { if (vvNew[bucket, i] != -1) nSize++; } stream.ReadWrite(ref nSize); for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) { if (vvNew[bucket, i] != -1) { int nIndex = mapUnkIds[vvNew[bucket, i]]; stream.ReadWrite(ref nIndex); } } } } Check(); } } #endregion //! Add a single address. public bool Add(NetworkAddress addr, IPAddress source) { return Add(addr, source, TimeSpan.Zero); } object cs = new object(); public bool Add(NetworkAddress addr) { return Add(addr, IPAddress.Loopback); } public bool Add(NetworkAddress addr, IPAddress source, TimeSpan nTimePenalty) { bool fRet = false; lock (cs) { Check(); fRet |= Add_(addr, source, nTimePenalty); Check(); } return fRet; } public bool Add(IEnumerable<NetworkAddress> vAddr, IPAddress source) { return Add(vAddr, source, TimeSpan.FromSeconds(0)); } public bool Add(IEnumerable<NetworkAddress> vAddr, IPAddress source, TimeSpan nTimePenalty) { int nAdd = 0; lock (cs) { Check(); foreach (var addr in vAddr) nAdd += Add_(addr, source, nTimePenalty) ? 1 : 0; Check(); } return nAdd > 0; } private bool Add_(NetworkAddress addr, IPAddress source, TimeSpan nTimePenalty) { if (!addr.Endpoint.IsRoutable(true)) return false; bool fNew = false; int nId; AddressInfo pinfo = Find(addr, out nId); if (pinfo != null) { // periodically update nTime bool fCurrentlyOnline = (DateTimeOffset.UtcNow - addr.Time < TimeSpan.FromSeconds(24 * 60 * 60)); var nUpdateInterval = TimeSpan.FromSeconds(fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60); if (addr.nTime != 0 && (pinfo.Address.nTime == 0 || pinfo.Address.Time < addr.Time - nUpdateInterval - nTimePenalty)) pinfo.Address.nTime = (uint)Math.Max(0L, (long)Utils.DateTimeToUnixTime(addr.Time - nTimePenalty)); // add services pinfo.Address.Services |= addr.Services; // do not update if no new information is present if (addr.nTime == 0 || (pinfo.Address.nTime != 0 && addr.Time <= pinfo.Address.Time)) return false; // do not update if the entry was already in the "tried" table if (pinfo.fInTried) return false; // do not update if the max reference count is reached if (pinfo.nRefCount == ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return false; // stochastic test: previous nRefCount == N: 2^N times harder to increase it int nFactor = 1; for (int n = 0; n < pinfo.nRefCount; n++) nFactor *= 2; if (nFactor > 1 && (GetRandInt(nFactor) != 0)) return false; } else { pinfo = Create(addr, source, out nId); pinfo.Address.nTime = (uint)Math.Max((long)0, (long)Utils.DateTimeToUnixTime(pinfo.Address.Time - nTimePenalty)); nNew++; fNew = true; } int nUBucket = pinfo.GetNewBucket(nKey, source); int nUBucketPos = pinfo.GetBucketPosition(nKey, true, nUBucket); if (vvNew[nUBucket, nUBucketPos] != nId) { bool fInsert = vvNew[nUBucket, nUBucketPos] == -1; if (!fInsert) { AddressInfo infoExisting = mapInfo[vvNew[nUBucket, nUBucketPos]]; if (infoExisting.IsTerrible || (infoExisting.nRefCount > 1 && pinfo.nRefCount == 0)) { // Overwrite the existing new table entry. fInsert = true; } } if (fInsert) { ClearNew(nUBucket, nUBucketPos); pinfo.nRefCount++; vvNew[nUBucket, nUBucketPos] = nId; } else { if (pinfo.nRefCount == 0) { Delete(nId); } } } return fNew; } private void ClearNew(int nUBucket, int nUBucketPos) { // if there is an entry in the specified bucket, delete it. if (vvNew[nUBucket, nUBucketPos] != -1) { int nIdDelete = vvNew[nUBucket, nUBucketPos]; AddressInfo infoDelete = mapInfo[nIdDelete]; assert(infoDelete.nRefCount > 0); infoDelete.nRefCount--; infoDelete.nRefCount = Math.Max(0, infoDelete.nRefCount); vvNew[nUBucket, nUBucketPos] = -1; if (infoDelete.nRefCount == 0) { Delete(nIdDelete); } } } private void Delete(int nId) { assert(mapInfo.ContainsKey(nId)); AddressInfo info = mapInfo[nId]; assert(!info.fInTried); assert(info.nRefCount == 0); SwapRandom(info.nRandomPos, vRandom.Count - 1); vRandom.RemoveAt(vRandom.Count - 1); mapAddr.Remove(info.Address.ToAddressString()); mapInfo.Remove(nId); nNew--; } private void SwapRandom(int nRndPos1, int nRndPos2) { if (nRndPos1 == nRndPos2) return; assert(nRndPos1 < vRandom.Count && nRndPos2 < vRandom.Count); int nId1 = vRandom[nRndPos1]; int nId2 = vRandom[nRndPos2]; assert(mapInfo.ContainsKey(nId1)); assert(mapInfo.ContainsKey(nId2)); mapInfo[nId1].nRandomPos = nRndPos2; mapInfo[nId2].nRandomPos = nRndPos1; vRandom[nRndPos1] = nId2; vRandom[nRndPos2] = nId1; } private AddressInfo Create(NetworkAddress addr, IPAddress addrSource, out int pnId) { int nId = nIdCount++; mapInfo[nId] = new AddressInfo(addr, addrSource); mapAddr[addr.ToAddressString()] = nId; mapInfo[nId].nRandomPos = vRandom.Count; vRandom.Add(nId); pnId = nId; return mapInfo[nId]; } internal bool DebugMode { get; set; } internal void Check() { if (!DebugMode) return; lock (cs) { assert(Check_() == 0); } } private int Check_() { List<int> setTried = new List<int>(); Dictionary<int, int> mapNew = new Dictionary<int, int>(); if (vRandom.Count != nTried + nNew) return -7; foreach (var kv in mapInfo) { int n = kv.Key; AddressInfo info = kv.Value; if (info.fInTried) { if (info.nLastSuccess == 0) return -1; if (info.nRefCount != 0) return -2; setTried.Add(n); } else { if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return -3; if (info.nRefCount == 0) return -4; mapNew[n] = info.nRefCount; } if (mapAddr[info.Address.ToAddressString()] != n) return -5; if (info.nRandomPos < 0 || info.nRandomPos >= vRandom.Count || vRandom[info.nRandomPos] != n) return -14; if (info.nLastTry < 0) return -6; if (info.nLastSuccess < 0) return -8; } if (setTried.Count != nTried) return -9; if (mapNew.Count != nNew) return -10; for (int n = 0; n < ADDRMAN_TRIED_BUCKET_COUNT; n++) { for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) { if (vvTried[n, i] != -1) { if (!setTried.Contains(vvTried[n, i])) return -11; if (mapInfo[vvTried[n, i]].GetTriedBucket(nKey) != n) return -17; if (mapInfo[vvTried[n, i]].GetBucketPosition(nKey, false, n) != i) return -18; setTried.Remove(vvTried[n, i]); } } } for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) { for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) { if (vvNew[n, i] != -1) { if (!mapNew.ContainsKey(vvNew[n, i])) return -12; if (mapInfo[vvNew[n, i]].GetBucketPosition(nKey, true, n) != i) return -19; if (--mapNew[vvNew[n, i]] == 0) mapNew.Remove(vvNew[n, i]); } } } if (setTried.Count != 0) return -13; if (mapNew.Count != 0) return -15; if (nKey == null || nKey == uint256.Zero) return -16; return 0; } public void Good(NetworkAddress addr) { Good(addr, DateTimeOffset.UtcNow); } public void Good(NetworkAddress addr, DateTimeOffset nTime) { lock (cs) { Check(); Good_(addr, nTime); Check(); } } private void Good_(NetworkAddress addr, DateTimeOffset nTime) { int nId; AddressInfo pinfo = Find(addr, out nId); // if not found, bail out if (pinfo == null) return; AddressInfo info = pinfo; // check whether we are talking about the exact same CService (including same port) if (!info.Match(addr)) return; // update info info.LastSuccess = nTime; info.LastTry = nTime; info.nAttempts = 0; // nTime is not updated here, to avoid leaking information about // currently-connected peers. // if it is already in the tried set, don't do anything else if (info.fInTried) return; // find a bucket it is in now int nRnd = GetRandInt(ADDRMAN_NEW_BUCKET_COUNT); int nUBucket = -1; for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) { int nB = (n + nRnd) % ADDRMAN_NEW_BUCKET_COUNT; int nBpos = info.GetBucketPosition(nKey, true, nB); if (vvNew[nB, nBpos] == nId) { nUBucket = nB; break; } } // if no bucket is found, something bad happened; // TODO: maybe re-add the node, but for now, just bail out if (nUBucket == -1) return; // move nId to the tried tables MakeTried(info, nId); } private void MakeTried(AddressInfo info, int nId) { // remove the entry from all new buckets for (int bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++) { int pos = info.GetBucketPosition(nKey, true, bucket); if (vvNew[bucket, pos] == nId) { vvNew[bucket, pos] = -1; info.nRefCount--; } } nNew--; assert(info.nRefCount == 0); // which tried bucket to move the entry to int nKBucket = info.GetTriedBucket(nKey); int nKBucketPos = info.GetBucketPosition(nKey, false, nKBucket); // first make space to add it (the existing tried entry there is moved to new, deleting whatever is there). if (vvTried[nKBucket, nKBucketPos] != -1) { // find an item to evict int nIdEvict = vvTried[nKBucket, nKBucketPos]; assert(mapInfo.ContainsKey(nIdEvict)); AddressInfo infoOld = mapInfo[nIdEvict]; // Remove the to-be-evicted item from the tried set. infoOld.fInTried = false; vvTried[nKBucket, nKBucketPos] = -1; nTried--; // find which new bucket it belongs to int nUBucket = infoOld.GetNewBucket(nKey); int nUBucketPos = infoOld.GetBucketPosition(nKey, true, nUBucket); ClearNew(nUBucket, nUBucketPos); assert(vvNew[nUBucket, nUBucketPos] == -1); // Enter it into the new set again. infoOld.nRefCount = 1; vvNew[nUBucket, nUBucketPos] = nIdEvict; nNew++; } assert(vvTried[nKBucket, nKBucketPos] == -1); vvTried[nKBucket, nKBucketPos] = nId; nTried++; info.fInTried = true; } private static void assert(bool value) { if (!value) throw new InvalidOperationException("Bug in AddressManager, should never happen, contact NBitcoin developers if you see this exception"); } //! Mark an entry as connection attempted to. public void Attempt(NetworkAddress addr) { Attempt(addr, DateTimeOffset.UtcNow); } //! Mark an entry as connection attempted to. public void Attempt(NetworkAddress addr, DateTimeOffset nTime) { lock (cs) { Check(); Attempt_(addr, nTime); Check(); } } private void Attempt_(NetworkAddress addr, DateTimeOffset nTime) { AddressInfo pinfo = Find(addr); // if not found, bail out if (pinfo == null) return; AddressInfo info = pinfo; // check whether we are talking about the exact same CService (including same port) if (!info.Match(addr)) return; // update info info.LastTry = nTime; info.nAttempts++; } //! Mark an entry as currently-connected-to. public void Connected(NetworkAddress addr) { Connected(addr, DateTimeOffset.UtcNow); } //! Mark an entry as currently-connected-to. public void Connected(NetworkAddress addr, DateTimeOffset nTime) { lock (cs) { Check(); Connected_(addr, nTime); Check(); } } void Connected_(NetworkAddress addr, DateTimeOffset nTime) { int unused; AddressInfo pinfo = Find(addr, out unused); // if not found, bail out if (pinfo == null) return; AddressInfo info = pinfo; // check whether we are talking about the exact same CService (including same port) if (!info.Match(addr)) return; // update info var nUpdateInterval = TimeSpan.FromSeconds(20 * 60); if (nTime - info.nTime > nUpdateInterval) info.nTime = nTime; } /// <summary> /// Choose an address to connect to. /// </summary> /// <returns>The network address of a peer, or null if none are found</returns> public NetworkAddress Select() { AddressInfo addrRet = null; lock (cs) { Check(); addrRet = Select_(); Check(); } return addrRet == null ? null : addrRet.Address; } private AddressInfo Select_() { if (vRandom.Count == 0) return null; var rnd = new Random(); // Use a 50% chance for choosing between tried and new table entries. if (nTried > 0 && (nNew == 0 || GetRandInt(2) == 0)) { // use a tried node double fChanceFactor = 1.0; while (true) { int nKBucket = GetRandInt(ADDRMAN_TRIED_BUCKET_COUNT); int nKBucketPos = GetRandInt(ADDRMAN_BUCKET_SIZE); while (vvTried[nKBucket, nKBucketPos] == -1) { nKBucket = (nKBucket + rnd.Next(ADDRMAN_TRIED_BUCKET_COUNT)) % ADDRMAN_TRIED_BUCKET_COUNT; nKBucketPos = (nKBucketPos + rnd.Next(ADDRMAN_BUCKET_SIZE)) % ADDRMAN_BUCKET_SIZE; } int nId = vvTried[nKBucket, nKBucketPos]; assert(mapInfo.ContainsKey(nId)); AddressInfo info = mapInfo[nId]; if (GetRandInt(1 << 30) < fChanceFactor * info.Chance * (1 << 30)) return info; fChanceFactor *= 1.2; } } else { // use a new node double fChanceFactor = 1.0; while (true) { int nUBucket = GetRandInt(ADDRMAN_NEW_BUCKET_COUNT); int nUBucketPos = GetRandInt(ADDRMAN_BUCKET_SIZE); while (vvNew[nUBucket, nUBucketPos] == -1) { nUBucket = (nUBucket + rnd.Next(ADDRMAN_NEW_BUCKET_COUNT)) % ADDRMAN_NEW_BUCKET_COUNT; nUBucketPos = (nUBucketPos + rnd.Next(ADDRMAN_BUCKET_SIZE)) % ADDRMAN_BUCKET_SIZE; } int nId = vvNew[nUBucket, nUBucketPos]; assert(mapInfo.ContainsKey(nId)); AddressInfo info = mapInfo[nId]; if (GetRandInt(1 << 30) < fChanceFactor * info.Chance * (1 << 30)) return info; fChanceFactor *= 1.2; } } } private static int GetRandInt(int max) { return (int)(RandomUtils.GetUInt32() % (uint)max); } /// <summary> /// Return a bunch of addresses, selected at random. /// </summary> /// <returns></returns> public NetworkAddress[] GetAddr() { NetworkAddress[] result = null; lock (cs) { Check(); result = GetAddr_().ToArray(); Check(); } return result; } IEnumerable<NetworkAddress> GetAddr_() { List<NetworkAddress> vAddr = new List<NetworkAddress>(); int nNodes = ADDRMAN_GETADDR_MAX_PCT * vRandom.Count / 100; if (nNodes > ADDRMAN_GETADDR_MAX) nNodes = ADDRMAN_GETADDR_MAX; // gather a list of random nodes, skipping those of low quality for (int n = 0; n < vRandom.Count; n++) { if (vAddr.Count >= nNodes) break; int nRndPos = GetRandInt(vRandom.Count - n) + n; SwapRandom(n, nRndPos); assert(mapInfo.ContainsKey(vRandom[n])); AddressInfo ai = mapInfo[vRandom[n]]; if (!ai.IsTerrible) vAddr.Add(ai.Address); } return vAddr; } public int Count { get { return vRandom.Count; } } internal void DiscoverPeers(Network network, NodeConnectionParameters parameters, int peerToFind) { TimeSpan backoff = TimeSpan.Zero; Logs.NodeServer.LogTrace("Discovering nodes"); _DiscoveredPeers = 0; NeededPeers = peerToFind; { while (_DiscoveredPeers < peerToFind) { Thread.Sleep(backoff); backoff = backoff == TimeSpan.Zero ? TimeSpan.FromSeconds(1.0) : TimeSpan.FromSeconds(backoff.TotalSeconds * 2); if (backoff > TimeSpan.FromSeconds(10.0)) backoff = TimeSpan.FromSeconds(10.0); parameters.ConnectCancellation.ThrowIfCancellationRequested(); Logs.NodeServer.LogTrace("Remaining peer to get {remainingPeerCount}", (-_DiscoveredPeers + peerToFind)); List<NetworkAddress> peers = new List<NetworkAddress>(); peers.AddRange(this.GetAddr()); if (peers.Count == 0) { PopulateTableWithDNSNodes(network, peers, parameters.ConnectCancellation).GetAwaiter().GetResult(); PopulateTableWithHardNodes(network, peers); peers = new List<NetworkAddress>(peers.OrderBy(a => RandomUtils.GetInt32())); if (peers.Count == 0) return; } CancellationTokenSource peerTableFull = new CancellationTokenSource(); CancellationToken loopCancel = CancellationTokenSource.CreateLinkedTokenSource(peerTableFull.Token, parameters.ConnectCancellation).Token; try { Parallel.ForEach(peers, new ParallelOptions() { MaxDegreeOfParallelism = 5, CancellationToken = loopCancel, }, p => { using (CancellationTokenSource timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5))) using (var cancelConnection = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, loopCancel)) { Node n = null; try { var param2 = parameters.Clone(); param2.ConnectCancellation = cancelConnection.Token; var addrman = param2.TemplateBehaviors.Find<AddressManagerBehavior>(); var socks = param2.TemplateBehaviors.Find<SocksSettingsBehavior>(); param2.TemplateBehaviors.Clear(); param2.TemplateBehaviors.Add(addrman); if (socks != null) param2.TemplateBehaviors.Add(socks); n = Node.Connect(network, p, param2); n.VersionHandshake(cancelConnection.Token); n.MessageReceived += (s, a) => { var addr = (a.Message.Payload as AddrPayload); if (addr != null) { Interlocked.Add(ref _DiscoveredPeers, addr.Addresses.Length); backoff = TimeSpan.FromSeconds(0); try { cancelConnection.Cancel(); } catch { } if (_DiscoveredPeers >= peerToFind) peerTableFull.Cancel(); } }; n.SendMessageAsync(new GetAddrPayload()); cancelConnection.Token.WaitHandle.WaitOne(2000); } catch { } finally { if (n != null) n.DisconnectAsync(); } } if (_DiscoveredPeers >= peerToFind) peerTableFull.Cancel(); else Logs.NodeServer.LogInformation("Need {neededPeerCount} more peers", (-_DiscoveredPeers + peerToFind)); }); } catch (OperationCanceledException) { if (parameters.ConnectCancellation.IsCancellationRequested) throw; } } } } private async Task PopulateTableWithDNSNodes(Network network, List<NetworkAddress> peers, CancellationToken cancellationToken) { var result = await Task.WhenAll(network.DNSSeeds .Select(async dns => { try { return (await dns.GetAddressNodesAsync(network.DefaultPort, DnsResolver, cancellationToken).ConfigureAwait(false)).Select(o => new NetworkAddress(o)).ToArray(); } catch { return new NetworkAddress[0]; } }) .ToArray()).ConfigureAwait(false); peers.AddRange(result.SelectMany(x => x)); } private static void PopulateTableWithHardNodes(Network network, List<NetworkAddress> peers) { peers.AddRange(network.SeedNodes); } } } #endif
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using CookComputing.XmlRpc; namespace XenAPI { /// <summary> /// A long-running asynchronous task /// First published in XenServer 4.0. /// </summary> public partial class Task : XenObject<Task> { public Task() { } public Task(string uuid, string name_label, string name_description, List<task_allowed_operations> allowed_operations, Dictionary<string, task_allowed_operations> current_operations, DateTime created, DateTime finished, task_status_type status, XenRef<Host> resident_on, double progress, string type, string result, string[] error_info, Dictionary<string, string> other_config, XenRef<Task> subtask_of, List<XenRef<Task>> subtasks, string backtrace) { this.uuid = uuid; this.name_label = name_label; this.name_description = name_description; this.allowed_operations = allowed_operations; this.current_operations = current_operations; this.created = created; this.finished = finished; this.status = status; this.resident_on = resident_on; this.progress = progress; this.type = type; this.result = result; this.error_info = error_info; this.other_config = other_config; this.subtask_of = subtask_of; this.subtasks = subtasks; this.backtrace = backtrace; } /// <summary> /// Creates a new Task from a Proxy_Task. /// </summary> /// <param name="proxy"></param> public Task(Proxy_Task proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(Task update) { uuid = update.uuid; name_label = update.name_label; name_description = update.name_description; allowed_operations = update.allowed_operations; current_operations = update.current_operations; created = update.created; finished = update.finished; status = update.status; resident_on = update.resident_on; progress = update.progress; type = update.type; result = update.result; error_info = update.error_info; other_config = update.other_config; subtask_of = update.subtask_of; subtasks = update.subtasks; backtrace = update.backtrace; } internal void UpdateFromProxy(Proxy_Task proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; name_label = proxy.name_label == null ? null : (string)proxy.name_label; name_description = proxy.name_description == null ? null : (string)proxy.name_description; allowed_operations = proxy.allowed_operations == null ? null : Helper.StringArrayToEnumList<task_allowed_operations>(proxy.allowed_operations); current_operations = proxy.current_operations == null ? null : Maps.convert_from_proxy_string_task_allowed_operations(proxy.current_operations); created = proxy.created; finished = proxy.finished; status = proxy.status == null ? (task_status_type) 0 : (task_status_type)Helper.EnumParseDefault(typeof(task_status_type), (string)proxy.status); resident_on = proxy.resident_on == null ? null : XenRef<Host>.Create(proxy.resident_on); progress = Convert.ToDouble(proxy.progress); type = proxy.type == null ? null : (string)proxy.type; result = proxy.result == null ? null : (string)proxy.result; error_info = proxy.error_info == null ? new string[] {} : (string [])proxy.error_info; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); subtask_of = proxy.subtask_of == null ? null : XenRef<Task>.Create(proxy.subtask_of); subtasks = proxy.subtasks == null ? null : XenRef<Task>.Create(proxy.subtasks); backtrace = proxy.backtrace == null ? null : (string)proxy.backtrace; } public Proxy_Task ToProxy() { Proxy_Task result_ = new Proxy_Task(); result_.uuid = (uuid != null) ? uuid : ""; result_.name_label = (name_label != null) ? name_label : ""; result_.name_description = (name_description != null) ? name_description : ""; result_.allowed_operations = (allowed_operations != null) ? Helper.ObjectListToStringArray(allowed_operations) : new string[] {}; result_.current_operations = Maps.convert_to_proxy_string_task_allowed_operations(current_operations); result_.created = created; result_.finished = finished; result_.status = task_status_type_helper.ToString(status); result_.resident_on = (resident_on != null) ? resident_on : ""; result_.progress = progress; result_.type = (type != null) ? type : ""; result_.result = (result != null) ? result : ""; result_.error_info = error_info; result_.other_config = Maps.convert_to_proxy_string_string(other_config); result_.subtask_of = (subtask_of != null) ? subtask_of : ""; result_.subtasks = (subtasks != null) ? Helper.RefListToStringArray(subtasks) : new string[] {}; result_.backtrace = (backtrace != null) ? backtrace : ""; return result_; } /// <summary> /// Creates a new Task from a Hashtable. /// </summary> /// <param name="table"></param> public Task(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); name_label = Marshalling.ParseString(table, "name_label"); name_description = Marshalling.ParseString(table, "name_description"); allowed_operations = Helper.StringArrayToEnumList<task_allowed_operations>(Marshalling.ParseStringArray(table, "allowed_operations")); current_operations = Maps.convert_from_proxy_string_task_allowed_operations(Marshalling.ParseHashTable(table, "current_operations")); created = Marshalling.ParseDateTime(table, "created"); finished = Marshalling.ParseDateTime(table, "finished"); status = (task_status_type)Helper.EnumParseDefault(typeof(task_status_type), Marshalling.ParseString(table, "status")); resident_on = Marshalling.ParseRef<Host>(table, "resident_on"); progress = Marshalling.ParseDouble(table, "progress"); type = Marshalling.ParseString(table, "type"); result = Marshalling.ParseString(table, "result"); error_info = Marshalling.ParseStringArray(table, "error_info"); other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); subtask_of = Marshalling.ParseRef<Task>(table, "subtask_of"); subtasks = Marshalling.ParseSetRef<Task>(table, "subtasks"); backtrace = Marshalling.ParseString(table, "backtrace"); } public bool DeepEquals(Task other, bool ignoreCurrentOperations) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) return false; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._name_label, other._name_label) && Helper.AreEqual2(this._name_description, other._name_description) && Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && Helper.AreEqual2(this._created, other._created) && Helper.AreEqual2(this._finished, other._finished) && Helper.AreEqual2(this._status, other._status) && Helper.AreEqual2(this._resident_on, other._resident_on) && Helper.AreEqual2(this._progress, other._progress) && Helper.AreEqual2(this._type, other._type) && Helper.AreEqual2(this._result, other._result) && Helper.AreEqual2(this._error_info, other._error_info) && Helper.AreEqual2(this._other_config, other._other_config) && Helper.AreEqual2(this._subtask_of, other._subtask_of) && Helper.AreEqual2(this._subtasks, other._subtasks) && Helper.AreEqual2(this._backtrace, other._backtrace); } public override string SaveChanges(Session session, string opaqueRef, Task server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { Task.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given task. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static Task get_record(Session session, string _task) { return new Task((Proxy_Task)session.proxy.task_get_record(session.uuid, (_task != null) ? _task : "").parse()); } /// <summary> /// Get a reference to the task instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<Task> get_by_uuid(Session session, string _uuid) { return XenRef<Task>.Create(session.proxy.task_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse()); } /// <summary> /// Get all the task instances with the given label. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_label">label of object to return</param> public static List<XenRef<Task>> get_by_name_label(Session session, string _label) { return XenRef<Task>.Create(session.proxy.task_get_by_name_label(session.uuid, (_label != null) ? _label : "").parse()); } /// <summary> /// Get the uuid field of the given task. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static string get_uuid(Session session, string _task) { return (string)session.proxy.task_get_uuid(session.uuid, (_task != null) ? _task : "").parse(); } /// <summary> /// Get the name/label field of the given task. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static string get_name_label(Session session, string _task) { return (string)session.proxy.task_get_name_label(session.uuid, (_task != null) ? _task : "").parse(); } /// <summary> /// Get the name/description field of the given task. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static string get_name_description(Session session, string _task) { return (string)session.proxy.task_get_name_description(session.uuid, (_task != null) ? _task : "").parse(); } /// <summary> /// Get the allowed_operations field of the given task. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static List<task_allowed_operations> get_allowed_operations(Session session, string _task) { return Helper.StringArrayToEnumList<task_allowed_operations>(session.proxy.task_get_allowed_operations(session.uuid, (_task != null) ? _task : "").parse()); } /// <summary> /// Get the current_operations field of the given task. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static Dictionary<string, task_allowed_operations> get_current_operations(Session session, string _task) { return Maps.convert_from_proxy_string_task_allowed_operations(session.proxy.task_get_current_operations(session.uuid, (_task != null) ? _task : "").parse()); } /// <summary> /// Get the created field of the given task. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static DateTime get_created(Session session, string _task) { return session.proxy.task_get_created(session.uuid, (_task != null) ? _task : "").parse(); } /// <summary> /// Get the finished field of the given task. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static DateTime get_finished(Session session, string _task) { return session.proxy.task_get_finished(session.uuid, (_task != null) ? _task : "").parse(); } /// <summary> /// Get the status field of the given task. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static task_status_type get_status(Session session, string _task) { return (task_status_type)Helper.EnumParseDefault(typeof(task_status_type), (string)session.proxy.task_get_status(session.uuid, (_task != null) ? _task : "").parse()); } /// <summary> /// Get the resident_on field of the given task. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static XenRef<Host> get_resident_on(Session session, string _task) { return XenRef<Host>.Create(session.proxy.task_get_resident_on(session.uuid, (_task != null) ? _task : "").parse()); } /// <summary> /// Get the progress field of the given task. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static double get_progress(Session session, string _task) { return Convert.ToDouble(session.proxy.task_get_progress(session.uuid, (_task != null) ? _task : "").parse()); } /// <summary> /// Get the type field of the given task. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static string get_type(Session session, string _task) { return (string)session.proxy.task_get_type(session.uuid, (_task != null) ? _task : "").parse(); } /// <summary> /// Get the result field of the given task. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static string get_result(Session session, string _task) { return (string)session.proxy.task_get_result(session.uuid, (_task != null) ? _task : "").parse(); } /// <summary> /// Get the error_info field of the given task. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static string[] get_error_info(Session session, string _task) { return (string [])session.proxy.task_get_error_info(session.uuid, (_task != null) ? _task : "").parse(); } /// <summary> /// Get the other_config field of the given task. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static Dictionary<string, string> get_other_config(Session session, string _task) { return Maps.convert_from_proxy_string_string(session.proxy.task_get_other_config(session.uuid, (_task != null) ? _task : "").parse()); } /// <summary> /// Get the subtask_of field of the given task. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static XenRef<Task> get_subtask_of(Session session, string _task) { return XenRef<Task>.Create(session.proxy.task_get_subtask_of(session.uuid, (_task != null) ? _task : "").parse()); } /// <summary> /// Get the subtasks field of the given task. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static List<XenRef<Task>> get_subtasks(Session session, string _task) { return XenRef<Task>.Create(session.proxy.task_get_subtasks(session.uuid, (_task != null) ? _task : "").parse()); } /// <summary> /// Get the backtrace field of the given task. /// First published in XenServer 7.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static string get_backtrace(Session session, string _task) { return (string)session.proxy.task_get_backtrace(session.uuid, (_task != null) ? _task : "").parse(); } /// <summary> /// Set the other_config field of the given task. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _task, Dictionary<string, string> _other_config) { session.proxy.task_set_other_config(session.uuid, (_task != null) ? _task : "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given task. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _task, string _key, string _value) { session.proxy.task_add_to_other_config(session.uuid, (_task != null) ? _task : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given task. If the key is not in that Map, then do nothing. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _task, string _key) { session.proxy.task_remove_from_other_config(session.uuid, (_task != null) ? _task : "", (_key != null) ? _key : "").parse(); } /// <summary> /// Create a new task object which must be manually destroyed. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_label">short label for the new task</param> /// <param name="_description">longer description for the new task</param> public static XenRef<Task> create(Session session, string _label, string _description) { return XenRef<Task>.Create(session.proxy.task_create(session.uuid, (_label != null) ? _label : "", (_description != null) ? _description : "").parse()); } /// <summary> /// Destroy the task object /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static void destroy(Session session, string _task) { session.proxy.task_destroy(session.uuid, (_task != null) ? _task : "").parse(); } /// <summary> /// Request that a task be cancelled. Note that a task may fail to be cancelled and may complete or fail normally and note that, even when a task does cancel, it might take an arbitrary amount of time. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static void cancel(Session session, string _task) { session.proxy.task_cancel(session.uuid, (_task != null) ? _task : "").parse(); } /// <summary> /// Request that a task be cancelled. Note that a task may fail to be cancelled and may complete or fail normally and note that, even when a task does cancel, it might take an arbitrary amount of time. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> public static XenRef<Task> async_cancel(Session session, string _task) { return XenRef<Task>.Create(session.proxy.async_task_cancel(session.uuid, (_task != null) ? _task : "").parse()); } /// <summary> /// Set the task status /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_task">The opaque_ref of the given task</param> /// <param name="_value">task status value to be set</param> public static void set_status(Session session, string _task, task_status_type _value) { session.proxy.task_set_status(session.uuid, (_task != null) ? _task : "", task_status_type_helper.ToString(_value)).parse(); } /// <summary> /// Return a list of all the tasks known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<Task>> get_all(Session session) { return XenRef<Task>.Create(session.proxy.task_get_all(session.uuid).parse()); } /// <summary> /// Get all the task Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Task>, Task> get_all_records(Session session) { return XenRef<Task>.Create<Proxy_Task>(session.proxy.task_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// a human-readable name /// </summary> public virtual string name_label { get { return _name_label; } set { if (!Helper.AreEqual(value, _name_label)) { _name_label = value; Changed = true; NotifyPropertyChanged("name_label"); } } } private string _name_label; /// <summary> /// a notes field containing human-readable description /// </summary> public virtual string name_description { get { return _name_description; } set { if (!Helper.AreEqual(value, _name_description)) { _name_description = value; Changed = true; NotifyPropertyChanged("name_description"); } } } private string _name_description; /// <summary> /// list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client. /// </summary> public virtual List<task_allowed_operations> allowed_operations { get { return _allowed_operations; } set { if (!Helper.AreEqual(value, _allowed_operations)) { _allowed_operations = value; Changed = true; NotifyPropertyChanged("allowed_operations"); } } } private List<task_allowed_operations> _allowed_operations; /// <summary> /// links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task. /// </summary> public virtual Dictionary<string, task_allowed_operations> current_operations { get { return _current_operations; } set { if (!Helper.AreEqual(value, _current_operations)) { _current_operations = value; Changed = true; NotifyPropertyChanged("current_operations"); } } } private Dictionary<string, task_allowed_operations> _current_operations; /// <summary> /// Time task was created /// </summary> public virtual DateTime created { get { return _created; } set { if (!Helper.AreEqual(value, _created)) { _created = value; Changed = true; NotifyPropertyChanged("created"); } } } private DateTime _created; /// <summary> /// Time task finished (i.e. succeeded or failed). If task-status is pending, then the value of this field has no meaning /// </summary> public virtual DateTime finished { get { return _finished; } set { if (!Helper.AreEqual(value, _finished)) { _finished = value; Changed = true; NotifyPropertyChanged("finished"); } } } private DateTime _finished; /// <summary> /// current status of the task /// </summary> public virtual task_status_type status { get { return _status; } set { if (!Helper.AreEqual(value, _status)) { _status = value; Changed = true; NotifyPropertyChanged("status"); } } } private task_status_type _status; /// <summary> /// the host on which the task is running /// </summary> public virtual XenRef<Host> resident_on { get { return _resident_on; } set { if (!Helper.AreEqual(value, _resident_on)) { _resident_on = value; Changed = true; NotifyPropertyChanged("resident_on"); } } } private XenRef<Host> _resident_on; /// <summary> /// This field contains the estimated fraction of the task which is complete. This field should not be used to determine whether the task is complete - for this the status field of the task should be used. /// </summary> public virtual double progress { get { return _progress; } set { if (!Helper.AreEqual(value, _progress)) { _progress = value; Changed = true; NotifyPropertyChanged("progress"); } } } private double _progress; /// <summary> /// if the task has completed successfully, this field contains the type of the encoded result (i.e. name of the class whose reference is in the result field). Undefined otherwise. /// </summary> public virtual string type { get { return _type; } set { if (!Helper.AreEqual(value, _type)) { _type = value; Changed = true; NotifyPropertyChanged("type"); } } } private string _type; /// <summary> /// if the task has completed successfully, this field contains the result value (either Void or an object reference). Undefined otherwise. /// </summary> public virtual string result { get { return _result; } set { if (!Helper.AreEqual(value, _result)) { _result = value; Changed = true; NotifyPropertyChanged("result"); } } } private string _result; /// <summary> /// if the task has failed, this field contains the set of associated error strings. Undefined otherwise. /// </summary> public virtual string[] error_info { get { return _error_info; } set { if (!Helper.AreEqual(value, _error_info)) { _error_info = value; Changed = true; NotifyPropertyChanged("error_info"); } } } private string[] _error_info; /// <summary> /// additional configuration /// First published in XenServer 4.1. /// </summary> public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config; /// <summary> /// Ref pointing to the task this is a substask of. /// First published in XenServer 5.0. /// </summary> public virtual XenRef<Task> subtask_of { get { return _subtask_of; } set { if (!Helper.AreEqual(value, _subtask_of)) { _subtask_of = value; Changed = true; NotifyPropertyChanged("subtask_of"); } } } private XenRef<Task> _subtask_of; /// <summary> /// List pointing to all the substasks. /// First published in XenServer 5.0. /// </summary> public virtual List<XenRef<Task>> subtasks { get { return _subtasks; } set { if (!Helper.AreEqual(value, _subtasks)) { _subtasks = value; Changed = true; NotifyPropertyChanged("subtasks"); } } } private List<XenRef<Task>> _subtasks; /// <summary> /// Function call trace for debugging. /// First published in XenServer 7.0. /// </summary> public virtual string backtrace { get { return _backtrace; } set { if (!Helper.AreEqual(value, _backtrace)) { _backtrace = value; Changed = true; NotifyPropertyChanged("backtrace"); } } } private string _backtrace; } }
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.38.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Library Agent API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://cloud.google.com/docs/quota'>Library Agent API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20190205 (1496) * <tr><th>API Docs * <td><a href='https://cloud.google.com/docs/quota'> * https://cloud.google.com/docs/quota</a> * <tr><th>Discovery Name<td>libraryagent * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Library Agent API can be found at * <a href='https://cloud.google.com/docs/quota'>https://cloud.google.com/docs/quota</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Libraryagent.v1 { /// <summary>The Libraryagent Service.</summary> public class LibraryagentService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public LibraryagentService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public LibraryagentService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { shelves = new ShelvesResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "libraryagent"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://libraryagent.googleapis.com/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return ""; } } #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri { get { return "https://libraryagent.googleapis.com/batch"; } } /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath { get { return "batch"; } } #endif /// <summary>Available OAuth 2.0 scopes for use with the Library Agent API.</summary> public class Scope { /// <summary>View and manage your data across Google Cloud Platform services</summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Available OAuth 2.0 scope constants for use with the Library Agent API.</summary> public static class ScopeConstants { /// <summary>View and manage your data across Google Cloud Platform services</summary> public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } private readonly ShelvesResource shelves; /// <summary>Gets the Shelves resource.</summary> public virtual ShelvesResource Shelves { get { return shelves; } } } ///<summary>A base abstract class for Libraryagent requests.</summary> public abstract class LibraryagentBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new LibraryagentBaseServiceRequest instance.</summary> protected LibraryagentBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes Libraryagent parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "shelves" collection of methods.</summary> public class ShelvesResource { private const string Resource = "shelves"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ShelvesResource(Google.Apis.Services.IClientService service) { this.service = service; books = new BooksResource(service); } private readonly BooksResource books; /// <summary>Gets the Books resource.</summary> public virtual BooksResource Books { get { return books; } } /// <summary>The "books" collection of methods.</summary> public class BooksResource { private const string Resource = "books"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public BooksResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Borrow a book from the library. Returns the book if it is borrowed successfully. Returns /// NOT_FOUND if the book does not exist in the library. Returns quota exceeded error if the amount of books /// borrowed exceeds allocation quota in any dimensions.</summary> /// <param name="name">The name of the book to borrow.</param> public virtual BorrowRequest Borrow(string name) { return new BorrowRequest(service, name); } /// <summary>Borrow a book from the library. Returns the book if it is borrowed successfully. Returns /// NOT_FOUND if the book does not exist in the library. Returns quota exceeded error if the amount of books /// borrowed exceeds allocation quota in any dimensions.</summary> public class BorrowRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1Book> { /// <summary>Constructs a new Borrow request.</summary> public BorrowRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The name of the book to borrow.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "borrow"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}:borrow"; } } /// <summary>Initializes Borrow parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^shelves/[^/]+/books/[^/]+$", }); } } /// <summary>Gets a book. Returns NOT_FOUND if the book does not exist.</summary> /// <param name="name">The name of the book to retrieve.</param> public virtual GetRequest Get(string name) { return new GetRequest(service, name); } /// <summary>Gets a book. Returns NOT_FOUND if the book does not exist.</summary> public class GetRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1Book> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The name of the book to retrieve.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^shelves/[^/]+/books/[^/]+$", }); } } /// <summary>Lists books in a shelf. The order is unspecified but deterministic. Newly created books will /// not necessarily be added to the end of this list. Returns NOT_FOUND if the shelf does not /// exist.</summary> /// <param name="parent">The name of the shelf whose books we'd like to list.</param> public virtual ListRequest List(string parent) { return new ListRequest(service, parent); } /// <summary>Lists books in a shelf. The order is unspecified but deterministic. Newly created books will /// not necessarily be added to the end of this list. Returns NOT_FOUND if the shelf does not /// exist.</summary> public class ListRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1ListBooksResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service) { Parent = parent; InitParameters(); } /// <summary>The name of the shelf whose books we'd like to list.</summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary>A token identifying a page of results the server should return. Typically, this is the /// value of ListBooksResponse.next_page_token. returned from the previous call to `ListBooks` /// method.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Requested page size. Server may return fewer books than requested. If unspecified, server /// will pick an appropriate default.</summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+parent}/books"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^shelves/[^/]+$", }); RequestParameters.Add( "pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Return a book to the library. Returns the book if it is returned to the library successfully. /// Returns error if the book does not belong to the library or the users didn't borrow before.</summary> /// <param name="name">The name of the book to return.</param> public virtual LibraryagentReturnRequest LibraryagentReturn(string name) { return new LibraryagentReturnRequest(service, name); } /// <summary>Return a book to the library. Returns the book if it is returned to the library successfully. /// Returns error if the book does not belong to the library or the users didn't borrow before.</summary> public class LibraryagentReturnRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1Book> { /// <summary>Constructs a new LibraryagentReturn request.</summary> public LibraryagentReturnRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The name of the book to return.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "return"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}:return"; } } /// <summary>Initializes LibraryagentReturn parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^shelves/[^/]+/books/[^/]+$", }); } } } /// <summary>Gets a shelf. Returns NOT_FOUND if the shelf does not exist.</summary> /// <param name="name">The name of the shelf to retrieve.</param> public virtual GetRequest Get(string name) { return new GetRequest(service, name); } /// <summary>Gets a shelf. Returns NOT_FOUND if the shelf does not exist.</summary> public class GetRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1Shelf> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The name of the shelf to retrieve.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^shelves/[^/]+$", }); } } /// <summary>Lists shelves. The order is unspecified but deterministic. Newly created shelves will not /// necessarily be added to the end of this list.</summary> public virtual ListRequest List() { return new ListRequest(service); } /// <summary>Lists shelves. The order is unspecified but deterministic. Newly created shelves will not /// necessarily be added to the end of this list.</summary> public class ListRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1ListShelvesResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>A token identifying a page of results the server should return. Typically, this is the value of /// ListShelvesResponse.next_page_token returned from the previous call to `ListShelves` method.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Requested page size. Server may return fewer shelves than requested. If unspecified, server /// will pick an appropriate default.</summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/shelves"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Libraryagent.v1.Data { /// <summary>A single book in the library.</summary> public class GoogleExampleLibraryagentV1Book : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The name of the book author.</summary> [Newtonsoft.Json.JsonPropertyAttribute("author")] public virtual string Author { get; set; } /// <summary>The resource name of the book. Book names have the form `shelves/{shelf_id}/books/{book_id}`. The /// name is ignored when creating a book.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>Value indicating whether the book has been read.</summary> [Newtonsoft.Json.JsonPropertyAttribute("read")] public virtual System.Nullable<bool> Read { get; set; } /// <summary>The title of the book.</summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for LibraryAgent.ListBooks.</summary> public class GoogleExampleLibraryagentV1ListBooksResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The list of books.</summary> [Newtonsoft.Json.JsonPropertyAttribute("books")] public virtual System.Collections.Generic.IList<GoogleExampleLibraryagentV1Book> Books { get; set; } /// <summary>A token to retrieve next page of results. Pass this value in the ListBooksRequest.page_token field /// in the subsequent call to `ListBooks` method to retrieve the next page of results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for LibraryAgent.ListShelves.</summary> public class GoogleExampleLibraryagentV1ListShelvesResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>A token to retrieve next page of results. Pass this value in the ListShelvesRequest.page_token /// field in the subsequent call to `ListShelves` method to retrieve the next page of results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The list of shelves.</summary> [Newtonsoft.Json.JsonPropertyAttribute("shelves")] public virtual System.Collections.Generic.IList<GoogleExampleLibraryagentV1Shelf> Shelves { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A Shelf contains a collection of books with a theme.</summary> public class GoogleExampleLibraryagentV1Shelf : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Output only. The resource name of the shelf. Shelf names have the form `shelves/{shelf_id}`. The /// name is ignored when creating a shelf.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The theme of the shelf</summary> [Newtonsoft.Json.JsonPropertyAttribute("theme")] public virtual string Theme { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
// LzmaDecoder.cs using System; namespace SevenZip.Compression.LZMA { using RangeCoder; public class Decoder : ICoder, ISetDecoderProperties // ,System.IO.Stream { class LenDecoder { BitDecoder m_Choice = new BitDecoder(); BitDecoder m_Choice2 = new BitDecoder(); BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; BitTreeDecoder m_HighCoder = new BitTreeDecoder(Base.kNumHighLenBits); uint m_NumPosStates = 0; public void Create(uint numPosStates) { for (uint posState = m_NumPosStates; posState < numPosStates; posState++) { m_LowCoder[posState] = new BitTreeDecoder(Base.kNumLowLenBits); m_MidCoder[posState] = new BitTreeDecoder(Base.kNumMidLenBits); } m_NumPosStates = numPosStates; } public void Init() { m_Choice.Init(); for (uint posState = 0; posState < m_NumPosStates; posState++) { m_LowCoder[posState].Init(); m_MidCoder[posState].Init(); } m_Choice2.Init(); m_HighCoder.Init(); } public uint Decode(RangeCoder.Decoder rangeDecoder, uint posState) { if (m_Choice.Decode(rangeDecoder) == 0) return m_LowCoder[posState].Decode(rangeDecoder); else { uint symbol = Base.kNumLowLenSymbols; if (m_Choice2.Decode(rangeDecoder) == 0) symbol += m_MidCoder[posState].Decode(rangeDecoder); else { symbol += Base.kNumMidLenSymbols; symbol += m_HighCoder.Decode(rangeDecoder); } return symbol; } } } class LiteralDecoder { struct Decoder2 { BitDecoder[] m_Decoders; public void Create() { m_Decoders = new BitDecoder[0x300]; } public void Init() { for (int i = 0; i < 0x300; i++) m_Decoders[i].Init(); } public byte DecodeNormal(RangeCoder.Decoder rangeDecoder) { uint symbol = 1; do symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); while (symbol < 0x100); return (byte)symbol; } public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, byte matchByte) { uint symbol = 1; do { uint matchBit = (uint)(matchByte >> 7) & 1; matchByte <<= 1; uint bit = m_Decoders[((1 + matchBit) << 8) + symbol].Decode(rangeDecoder); symbol = (symbol << 1) | bit; if (matchBit != bit) { while (symbol < 0x100) symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); break; } } while (symbol < 0x100); return (byte)symbol; } } Decoder2[] m_Coders; int m_NumPrevBits; int m_NumPosBits; uint m_PosMask; public void Create(int numPosBits, int numPrevBits) { if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits) return; m_NumPosBits = numPosBits; m_PosMask = ((uint)1 << numPosBits) - 1; m_NumPrevBits = numPrevBits; uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); m_Coders = new Decoder2[numStates]; for (uint i = 0; i < numStates; i++) m_Coders[i].Create(); } public void Init() { uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); for (uint i = 0; i < numStates; i++) m_Coders[i].Init(); } uint GetState(uint pos, byte prevByte) { return ((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits)); } public byte DecodeNormal(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte) { return m_Coders[GetState(pos, prevByte)].DecodeNormal(rangeDecoder); } public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte, byte matchByte) { return m_Coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte); } }; LZ.OutWindow m_OutWindow = new LZ.OutWindow(); RangeCoder.Decoder m_RangeDecoder = new RangeCoder.Decoder(); BitDecoder[] m_IsMatchDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; BitDecoder[] m_IsRepDecoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRepG0Decoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRepG1Decoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRepG2Decoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates]; BitDecoder[] m_PosDecoders = new BitDecoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(Base.kNumAlignBits); LenDecoder m_LenDecoder = new LenDecoder(); LenDecoder m_RepLenDecoder = new LenDecoder(); LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); uint m_DictionarySize; uint m_DictionarySizeCheck; uint m_PosStateMask; public Decoder() { m_DictionarySize = 0xFFFFFFFF; for (int i = 0; i < Base.kNumLenToPosStates; i++) m_PosSlotDecoder[i] = new BitTreeDecoder(Base.kNumPosSlotBits); } void SetDictionarySize(uint dictionarySize) { if (m_DictionarySize != dictionarySize) { m_DictionarySize = dictionarySize; m_DictionarySizeCheck = Math.Max(m_DictionarySize, 1); uint blockSize = Math.Max(m_DictionarySizeCheck, (1 << 12)); m_OutWindow.Create(blockSize); } } void SetLiteralProperties(int lp, int lc) { if (lp > 8) throw new InvalidParamException(); if (lc > 8) throw new InvalidParamException(); m_LiteralDecoder.Create(lp, lc); } void SetPosBitsProperties(int pb) { if (pb > Base.kNumPosStatesBitsMax) throw new InvalidParamException(); uint numPosStates = (uint)1 << pb; m_LenDecoder.Create(numPosStates); m_RepLenDecoder.Create(numPosStates); m_PosStateMask = numPosStates - 1; } bool _solid = false; void Init(System.IO.Stream inStream, System.IO.Stream outStream) { m_RangeDecoder.Init(inStream); m_OutWindow.Init(outStream, _solid); uint i; for (i = 0; i < Base.kNumStates; i++) { for (uint j = 0; j <= m_PosStateMask; j++) { uint index = (i << Base.kNumPosStatesBitsMax) + j; m_IsMatchDecoders[index].Init(); m_IsRep0LongDecoders[index].Init(); } m_IsRepDecoders[i].Init(); m_IsRepG0Decoders[i].Init(); m_IsRepG1Decoders[i].Init(); m_IsRepG2Decoders[i].Init(); } m_LiteralDecoder.Init(); for (i = 0; i < Base.kNumLenToPosStates; i++) m_PosSlotDecoder[i].Init(); // m_PosSpecDecoder.Init(); for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++) m_PosDecoders[i].Init(); m_LenDecoder.Init(); m_RepLenDecoder.Init(); m_PosAlignDecoder.Init(); } public void Code(System.IO.Stream inStream, System.IO.Stream outStream, Int64 inSize, Int64 outSize, ICodeProgress progress) { Init(inStream, outStream); Base.State state = new Base.State(); state.Init(); uint rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0; UInt64 nowPos64 = 0; UInt64 outSize64 = (UInt64)outSize; if (nowPos64 < outSize64) { if (m_IsMatchDecoders[state.Index << Base.kNumPosStatesBitsMax].Decode(m_RangeDecoder) != 0) throw new DataErrorException(); state.UpdateChar(); byte b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, 0, 0); m_OutWindow.PutByte(b); nowPos64++; } while (nowPos64 < outSize64) { // UInt64 next = Math.Min(nowPos64 + (1 << 18), outSize64); // while(nowPos64 < next) { uint posState = (uint)nowPos64 & m_PosStateMask; if (m_IsMatchDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0) { byte b; byte prevByte = m_OutWindow.GetByte(0); if (!state.IsCharState()) b = m_LiteralDecoder.DecodeWithMatchByte(m_RangeDecoder, (uint)nowPos64, prevByte, m_OutWindow.GetByte(rep0)); else b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, (uint)nowPos64, prevByte); m_OutWindow.PutByte(b); state.UpdateChar(); nowPos64++; } else { uint len; if (m_IsRepDecoders[state.Index].Decode(m_RangeDecoder) == 1) { if (m_IsRepG0Decoders[state.Index].Decode(m_RangeDecoder) == 0) { if (m_IsRep0LongDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0) { state.UpdateShortRep(); m_OutWindow.PutByte(m_OutWindow.GetByte(rep0)); nowPos64++; continue; } } else { UInt32 distance; if (m_IsRepG1Decoders[state.Index].Decode(m_RangeDecoder) == 0) { distance = rep1; } else { if (m_IsRepG2Decoders[state.Index].Decode(m_RangeDecoder) == 0) distance = rep2; else { distance = rep3; rep3 = rep2; } rep2 = rep1; } rep1 = rep0; rep0 = distance; } len = m_RepLenDecoder.Decode(m_RangeDecoder, posState) + Base.kMatchMinLen; state.UpdateRep(); } else { rep3 = rep2; rep2 = rep1; rep1 = rep0; len = Base.kMatchMinLen + m_LenDecoder.Decode(m_RangeDecoder, posState); state.UpdateMatch(); uint posSlot = m_PosSlotDecoder[Base.GetLenToPosState(len)].Decode(m_RangeDecoder); if (posSlot >= Base.kStartPosModelIndex) { int numDirectBits = (int)((posSlot >> 1) - 1); rep0 = ((2 | (posSlot & 1)) << numDirectBits); if (posSlot < Base.kEndPosModelIndex) rep0 += BitTreeDecoder.ReverseDecode(m_PosDecoders, rep0 - posSlot - 1, m_RangeDecoder, numDirectBits); else { rep0 += (m_RangeDecoder.DecodeDirectBits( numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits); rep0 += m_PosAlignDecoder.ReverseDecode(m_RangeDecoder); } } else rep0 = posSlot; } if (rep0 >= m_OutWindow.TrainSize + nowPos64 || rep0 >= m_DictionarySizeCheck) { if (rep0 == 0xFFFFFFFF) break; throw new DataErrorException(); } m_OutWindow.CopyBlock(rep0, len); nowPos64 += len; } } } m_OutWindow.Flush(); m_OutWindow.ReleaseStream(); m_RangeDecoder.ReleaseStream(); } public void SetDecoderProperties(byte[] properties) { if (properties.Length < 5) throw new InvalidParamException(); int lc = properties[0] % 9; int remainder = properties[0] / 9; int lp = remainder % 5; int pb = remainder / 5; if (pb > Base.kNumPosStatesBitsMax) throw new InvalidParamException(); UInt32 dictionarySize = 0; for (int i = 0; i < 4; i++) dictionarySize += ((UInt32)(properties[1 + i])) << (i * 8); SetDictionarySize(dictionarySize); SetLiteralProperties(lp, lc); SetPosBitsProperties(pb); } public bool Train(System.IO.Stream stream) { _solid = true; return m_OutWindow.Train(stream); } /* public override bool CanRead { get { return true; }} public override bool CanWrite { get { return true; }} public override bool CanSeek { get { return true; }} public override long Length { get { return 0; }} public override long Position { get { return 0; } set { } } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { return 0; } public override void Write(byte[] buffer, int offset, int count) { } public override long Seek(long offset, System.IO.SeekOrigin origin) { return 0; } public override void SetLength(long value) {} */ } }
using System; using System.Collections; using System.Reflection; using LuaInterface; namespace Voyage.LuaNetInterface { /// <summary> /// A class for providing an interface to a Lua virtual machine. /// </summary> public class LuaVirtualMachine { #region Data Members private Lua _lua = null; // Lua virtual machine private Hashtable _functions = null; // Registered functions in the Lua virtual machine private Hashtable _packages = null; // Registered packages in the Lua virtual machine #endregion #region Properties /// <summary> /// Gets the Lua virtual machine. /// </summary> public Lua Lua { get { return _lua; } } /// <summary> /// Gets the table of Lua-registered functions. /// </summary> public Hashtable Functions { get { return _functions; } } /// <summary> /// Gets the table of Lua-registered packages. /// </summary> public Hashtable Packages { get { return _packages; } } #endregion #region Methods /// <summary> /// Creates an object for interfacing with the Lua virtual machine. /// </summary> /// <param name="register">Whether to register the built-in functions.</param> public LuaVirtualMachine( bool register ) { _lua = new Lua(); _functions = new Hashtable(); _packages = new Hashtable(); // Register the built-in Lua functions if ( register ) RegisterLuaFunctions( this ); } /// <summary> /// Registers the Lua-attributed functions in the target object. /// </summary> /// <param name="target">The target to load Lua-attributed functions from.</param> public void RegisterLuaFunctions( object target ) { RegisterLuaFunctions( target, null, null ); } /// <summary> /// Registers the Lua-attributed functions in the target object. /// </summary> /// <param name="target">The target to load Lua-attributed functions from.</param> /// <param name="package">The package to register the functions under.</param> /// <param name="packageDocumentation">The documentation for the package.</param> public void RegisterLuaFunctions( object target, string package, string packageDocumentation ) { // Sanity checks if ( target == null || _lua == null || _functions == null || _packages == null ) return; try { LuaPackageDescriptor pPackage = null; Console.WriteLine("Loading Lua library: " + target.ToString()); if ( package != null ) { // Check if the package already exists if ( !_packages.ContainsKey( "package" ) ) { // Create a new package _lua.DoString( package + " = {}" ); pPackage = new LuaPackageDescriptor( package, packageDocumentation ); } else // Access the old package pPackage = (LuaPackageDescriptor) _packages["package"]; } // Get the target type Type targetType = target.GetType(); // ... and simply iterate through all its methods foreach ( MethodInfo info in targetType.GetMethods() ) { // ... then through all this method's attributes foreach ( Attribute attr in Attribute.GetCustomAttributes( info ) ) { // ... and if they happen to be one of our LuaFunctionAttribute attributes if ( attr.GetType() == typeof( LuaFunctionAttribute ) ) { LuaFunctionAttribute luaAttr = (LuaFunctionAttribute) attr; ArrayList paramList = new ArrayList(); ArrayList paramDocs = new ArrayList(); // Get the desired function name and doc string, along with parameter info string fName = luaAttr.FunctionName; string fDoc = luaAttr.FunctionDocumentation; string[] pDocs = luaAttr.FunctionParameters; // Now get the expected parameters from the MethodInfo object ParameterInfo[] pInfo = info.GetParameters(); // If they don't match, someone forgot to add some documentation to the // attribute, complain and go to the next method if ( pDocs != null && ( pInfo.Length != pDocs.Length ) ) { Console.WriteLine( "Function " + info.Name + " (exported as " + fName + ") argument number mismatch. Declared " + pDocs.Length + " but requires " + pInfo.Length + "." ); break; } // Build a parameter <-> parameter doc hashtable for ( int i = 0; i < pInfo.Length; i++ ) { paramList.Add( pInfo[i].Name ); paramDocs.Add( pDocs[i] ); } // Get a new function descriptor from this information LuaFunctionDescriptor func = new LuaFunctionDescriptor( fName, fDoc, paramList, paramDocs ); if ( pPackage != null ) { // Check if the package already contains the function if ( !pPackage.Functions.ContainsKey( fName ) ) { // Add the new package function pPackage.AddFunction( func ); _lua.RegisterFunction( package + fName, target, info ); _lua.DoString( package + "." + fName + " = " + package + fName ); _lua.DoString( package + fName + " = nil" ); } } else { // Check if the function has already been loaded if ( !_functions.ContainsKey( fName ) ) { // Add it to the global hashtable _functions.Add( fName, func ); // And tell the VM to register it _lua.RegisterFunction( fName, target, info ); } } } } } if ( pPackage != null && !_packages.ContainsKey( package ) ) _packages.Add( package, pPackage ); } catch ( Exception e ) { } finally { } } #endregion #region LuaMethods /// <summary> /// Displays available commands to the console. /// </summary> [LuaFunctionAttribute( "help", "List available commands." )] public void Help() { string[] results; int counter; // Display stand-alone commands if ( _functions.Count > 0 ) { results = new string[_functions.Count]; counter = 0; Console.WriteLine( "Available commands:" ); Console.WriteLine(); IDictionaryEnumerator funcs = _functions.GetEnumerator(); while ( funcs.MoveNext() ) { results[counter] = ( (LuaFunctionDescriptor) funcs.Value ).FunctionHeader; counter++; } Array.Sort( results ); for ( int i = 0; i < counter; i++ ) Console.WriteLine( results[i] ); } // Display packages if ( _packages.Count > 0 ) { results = new string[_packages.Count]; counter = 0; Console.WriteLine(); Console.WriteLine( "Available packages:" ); IDictionaryEnumerator pkgs = _packages.GetEnumerator(); while ( pkgs.MoveNext() ) { results[counter] += pkgs.Key.ToString(); counter++; } Array.Sort( results ); for ( int i = 0; i < counter; i++ ) Console.WriteLine( results[i] ); } } /// <summary> /// Displays information about the specified command to the console. /// </summary> /// <param name="command">The command to display information for.</param> [LuaFunctionAttribute( "helpcmd", "Show help for a given command.", "Command to get help of (put in quotes)." )] public void Help( string command ) { if ( _functions.Contains( command ) ) { LuaFunctionDescriptor func = (LuaFunctionDescriptor) _functions[command]; Console.WriteLine( func.FunctionFullDocumentation ); return; } if ( command.IndexOf( "." ) == -1 ) { if ( _packages.ContainsKey( command ) ) { LuaPackageDescriptor pkg = (LuaPackageDescriptor) _packages[command]; Console.WriteLine( pkg.WriteHelp( command ) ); return; } else { Console.WriteLine( "No such function or package: " + command ); return; } } string[] parts = command.Split( '.' ); if ( !_packages.ContainsKey( parts[0] ) ) { Console.WriteLine( "No such function or package: " + command ); return; } LuaPackageDescriptor desc = (LuaPackageDescriptor) _packages[ parts[0] ]; if ( !desc.HasFunction( parts[1] ) ) { Console.WriteLine( "Package " + parts[0] + " doesn't have a " + parts[1] + " function." ); return; } Console.WriteLine( desc.WriteHelp( parts[1] ) ); } #endregion } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Redshift.Model { /// <summary> /// Container for the parameters to the CreateCluster operation. /// Creates a new cluster. To create the cluster in virtual private cloud (VPC), you /// must provide cluster subnet group name. If you don't provide a cluster subnet group /// name or the cluster security group parameter, Amazon Redshift creates a non-VPC cluster, /// it associates the default cluster security group with the cluster. For more information /// about managing clusters, go to <a href="http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html">Amazon /// Redshift Clusters</a> in the <i>Amazon Redshift Cluster Management Guide</i> . /// </summary> public partial class CreateClusterRequest : AmazonRedshiftRequest { private bool? _allowVersionUpgrade; private int? _automatedSnapshotRetentionPeriod; private string _availabilityZone; private string _clusterIdentifier; private string _clusterParameterGroupName; private List<string> _clusterSecurityGroups = new List<string>(); private string _clusterSubnetGroupName; private string _clusterType; private string _clusterVersion; private string _dbName; private string _elasticIp; private bool? _encrypted; private string _hsmClientCertificateIdentifier; private string _hsmConfigurationIdentifier; private string _kmsKeyId; private string _masterUsername; private string _masterUserPassword; private string _nodeType; private int? _numberOfNodes; private int? _port; private string _preferredMaintenanceWindow; private bool? _publiclyAccessible; private List<Tag> _tags = new List<Tag>(); private List<string> _vpcSecurityGroupIds = new List<string>(); /// <summary> /// Gets and sets the property AllowVersionUpgrade. /// <para> /// If <code>true</code>, major version upgrades can be applied during the maintenance /// window to the Amazon Redshift engine that is running on the cluster. /// </para> /// /// <para> /// When a new major version of the Amazon Redshift engine is released, you can request /// that the service automatically apply upgrades during the maintenance window to the /// Amazon Redshift engine that is running on your cluster. /// </para> /// /// <para> /// Default: <code>true</code> /// </para> /// </summary> public bool AllowVersionUpgrade { get { return this._allowVersionUpgrade.GetValueOrDefault(); } set { this._allowVersionUpgrade = value; } } // Check to see if AllowVersionUpgrade property is set internal bool IsSetAllowVersionUpgrade() { return this._allowVersionUpgrade.HasValue; } /// <summary> /// Gets and sets the property AutomatedSnapshotRetentionPeriod. /// <para> /// The number of days that automated snapshots are retained. If the value is 0, automated /// snapshots are disabled. Even if automated snapshots are disabled, you can still create /// manual snapshots when you want with <a>CreateClusterSnapshot</a>. /// </para> /// /// <para> /// Default: <code>1</code> /// </para> /// /// <para> /// Constraints: Must be a value from 0 to 35. /// </para> /// </summary> public int AutomatedSnapshotRetentionPeriod { get { return this._automatedSnapshotRetentionPeriod.GetValueOrDefault(); } set { this._automatedSnapshotRetentionPeriod = value; } } // Check to see if AutomatedSnapshotRetentionPeriod property is set internal bool IsSetAutomatedSnapshotRetentionPeriod() { return this._automatedSnapshotRetentionPeriod.HasValue; } /// <summary> /// Gets and sets the property AvailabilityZone. /// <para> /// The EC2 Availability Zone (AZ) in which you want Amazon Redshift to provision the /// cluster. For example, if you have several EC2 instances running in a specific Availability /// Zone, then you might want the cluster to be provisioned in the same zone in order /// to decrease network latency. /// </para> /// /// <para> /// Default: A random, system-chosen Availability Zone in the region that is specified /// by the endpoint. /// </para> /// /// <para> /// Example: <code>us-east-1d</code> /// </para> /// /// <para> /// Constraint: The specified Availability Zone must be in the same region as the current /// endpoint. /// </para> /// </summary> public string AvailabilityZone { get { return this._availabilityZone; } set { this._availabilityZone = value; } } // Check to see if AvailabilityZone property is set internal bool IsSetAvailabilityZone() { return this._availabilityZone != null; } /// <summary> /// Gets and sets the property ClusterIdentifier. /// <para> /// A unique identifier for the cluster. You use this identifier to refer to the cluster /// for any subsequent cluster operations such as deleting or modifying. The identifier /// also appears in the Amazon Redshift console. /// </para> /// /// <para> /// Constraints: /// </para> /// <ul> <li>Must contain from 1 to 63 alphanumeric characters or hyphens.</li> <li>Alphabetic /// characters must be lowercase.</li> <li>First character must be a letter.</li> <li>Cannot /// end with a hyphen or contain two consecutive hyphens.</li> <li>Must be unique for /// all clusters within an AWS account.</li> </ul> /// <para> /// Example: <code>myexamplecluster</code> /// </para> /// </summary> public string ClusterIdentifier { get { return this._clusterIdentifier; } set { this._clusterIdentifier = value; } } // Check to see if ClusterIdentifier property is set internal bool IsSetClusterIdentifier() { return this._clusterIdentifier != null; } /// <summary> /// Gets and sets the property ClusterParameterGroupName. /// <para> /// The name of the parameter group to be associated with this cluster. /// </para> /// /// <para> /// Default: The default Amazon Redshift cluster parameter group. For information about /// the default parameter group, go to <a href="http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-parameter-groups.html">Working /// with Amazon Redshift Parameter Groups</a> /// </para> /// /// <para> /// Constraints: /// </para> /// <ul> <li>Must be 1 to 255 alphanumeric characters or hyphens.</li> <li>First character /// must be a letter.</li> <li>Cannot end with a hyphen or contain two consecutive hyphens.</li> /// </ul> /// </summary> public string ClusterParameterGroupName { get { return this._clusterParameterGroupName; } set { this._clusterParameterGroupName = value; } } // Check to see if ClusterParameterGroupName property is set internal bool IsSetClusterParameterGroupName() { return this._clusterParameterGroupName != null; } /// <summary> /// Gets and sets the property ClusterSecurityGroups. /// <para> /// A list of security groups to be associated with this cluster. /// </para> /// /// <para> /// Default: The default cluster security group for Amazon Redshift. /// </para> /// </summary> public List<string> ClusterSecurityGroups { get { return this._clusterSecurityGroups; } set { this._clusterSecurityGroups = value; } } // Check to see if ClusterSecurityGroups property is set internal bool IsSetClusterSecurityGroups() { return this._clusterSecurityGroups != null && this._clusterSecurityGroups.Count > 0; } /// <summary> /// Gets and sets the property ClusterSubnetGroupName. /// <para> /// The name of a cluster subnet group to be associated with this cluster. /// </para> /// /// <para> /// If this parameter is not provided the resulting cluster will be deployed outside /// virtual private cloud (VPC). /// </para> /// </summary> public string ClusterSubnetGroupName { get { return this._clusterSubnetGroupName; } set { this._clusterSubnetGroupName = value; } } // Check to see if ClusterSubnetGroupName property is set internal bool IsSetClusterSubnetGroupName() { return this._clusterSubnetGroupName != null; } /// <summary> /// Gets and sets the property ClusterType. /// <para> /// The type of the cluster. When cluster type is specified as <ul> <li> <code>single-node</code>, /// the <b>NumberOfNodes</b> parameter is not required.</li> <li> <code>multi-node</code>, /// the <b>NumberOfNodes</b> parameter is required.</li> </ul> /// </para> /// /// <para> /// Valid Values: <code>multi-node</code> | <code>single-node</code> /// </para> /// /// <para> /// Default: <code>multi-node</code> /// </para> /// </summary> public string ClusterType { get { return this._clusterType; } set { this._clusterType = value; } } // Check to see if ClusterType property is set internal bool IsSetClusterType() { return this._clusterType != null; } /// <summary> /// Gets and sets the property ClusterVersion. /// <para> /// The version of the Amazon Redshift engine software that you want to deploy on the /// cluster. /// </para> /// /// <para> /// The version selected runs on all the nodes in the cluster. /// </para> /// /// <para> /// Constraints: Only version 1.0 is currently available. /// </para> /// /// <para> /// Example: <code>1.0</code> /// </para> /// </summary> public string ClusterVersion { get { return this._clusterVersion; } set { this._clusterVersion = value; } } // Check to see if ClusterVersion property is set internal bool IsSetClusterVersion() { return this._clusterVersion != null; } /// <summary> /// Gets and sets the property DBName. /// <para> /// The name of the first database to be created when the cluster is created. /// </para> /// /// <para> /// To create additional databases after the cluster is created, connect to the cluster /// with a SQL client and use SQL commands to create a database. For more information, /// go to <a href="http://docs.aws.amazon.com/redshift/latest/dg/t_creating_database.html">Create /// a Database</a> in the Amazon Redshift Database Developer Guide. /// </para> /// /// <para> /// Default: <code>dev</code> /// </para> /// /// <para> /// Constraints: /// </para> /// <ul> <li>Must contain 1 to 64 alphanumeric characters.</li> <li>Must contain only /// lowercase letters.</li> <li>Cannot be a word that is reserved by the service. A list /// of reserved words can be found in <a href="http://docs.aws.amazon.com/redshift/latest/dg/r_pg_keywords.html">Reserved /// Words</a> in the Amazon Redshift Database Developer Guide. </li> </ul> /// </summary> public string DBName { get { return this._dbName; } set { this._dbName = value; } } // Check to see if DBName property is set internal bool IsSetDBName() { return this._dbName != null; } /// <summary> /// Gets and sets the property ElasticIp. /// <para> /// The Elastic IP (EIP) address for the cluster. /// </para> /// /// <para> /// Constraints: The cluster must be provisioned in EC2-VPC and publicly-accessible through /// an Internet gateway. For more information about provisioning clusters in EC2-VPC, /// go to <a href="http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#cluster-platforms">Supported /// Platforms to Launch Your Cluster</a> in the Amazon Redshift Cluster Management Guide. /// </para> /// </summary> public string ElasticIp { get { return this._elasticIp; } set { this._elasticIp = value; } } // Check to see if ElasticIp property is set internal bool IsSetElasticIp() { return this._elasticIp != null; } /// <summary> /// Gets and sets the property Encrypted. /// <para> /// If <code>true</code>, the data in the cluster is encrypted at rest. /// </para> /// /// <para> /// Default: false /// </para> /// </summary> public bool Encrypted { get { return this._encrypted.GetValueOrDefault(); } set { this._encrypted = value; } } // Check to see if Encrypted property is set internal bool IsSetEncrypted() { return this._encrypted.HasValue; } /// <summary> /// Gets and sets the property HsmClientCertificateIdentifier. /// <para> /// Specifies the name of the HSM client certificate the Amazon Redshift cluster uses /// to retrieve the data encryption keys stored in an HSM. /// </para> /// </summary> public string HsmClientCertificateIdentifier { get { return this._hsmClientCertificateIdentifier; } set { this._hsmClientCertificateIdentifier = value; } } // Check to see if HsmClientCertificateIdentifier property is set internal bool IsSetHsmClientCertificateIdentifier() { return this._hsmClientCertificateIdentifier != null; } /// <summary> /// Gets and sets the property HsmConfigurationIdentifier. /// <para> /// Specifies the name of the HSM configuration that contains the information the Amazon /// Redshift cluster can use to retrieve and store keys in an HSM. /// </para> /// </summary> public string HsmConfigurationIdentifier { get { return this._hsmConfigurationIdentifier; } set { this._hsmConfigurationIdentifier = value; } } // Check to see if HsmConfigurationIdentifier property is set internal bool IsSetHsmConfigurationIdentifier() { return this._hsmConfigurationIdentifier != null; } /// <summary> /// Gets and sets the property KmsKeyId. /// <para> /// The AWS Key Management Service (KMS) key ID of the encryption key that you want to /// use to encrypt data in the cluster. /// </para> /// </summary> public string KmsKeyId { get { return this._kmsKeyId; } set { this._kmsKeyId = value; } } // Check to see if KmsKeyId property is set internal bool IsSetKmsKeyId() { return this._kmsKeyId != null; } /// <summary> /// Gets and sets the property MasterUsername. /// <para> /// The user name associated with the master user account for the cluster that is being /// created. /// </para> /// /// <para> /// Constraints: /// </para> /// <ul> <li>Must be 1 - 128 alphanumeric characters.</li> <li>First character must be /// a letter.</li> <li>Cannot be a reserved word. A list of reserved words can be found /// in <a href="http://docs.aws.amazon.com/redshift/latest/dg/r_pg_keywords.html">Reserved /// Words</a> in the Amazon Redshift Database Developer Guide. </li> </ul> /// </summary> public string MasterUsername { get { return this._masterUsername; } set { this._masterUsername = value; } } // Check to see if MasterUsername property is set internal bool IsSetMasterUsername() { return this._masterUsername != null; } /// <summary> /// Gets and sets the property MasterUserPassword. /// <para> /// The password associated with the master user account for the cluster that is being /// created. /// </para> /// /// <para> /// Constraints: /// </para> /// <ul> <li>Must be between 8 and 64 characters in length.</li> <li>Must contain at /// least one uppercase letter.</li> <li>Must contain at least one lowercase letter.</li> /// <li>Must contain one number.</li> <li>Can be any printable ASCII character (ASCII /// code 33 to 126) except ' (single quote), " (double quote), \, /, @, or space.</li> /// </ul> /// </summary> public string MasterUserPassword { get { return this._masterUserPassword; } set { this._masterUserPassword = value; } } // Check to see if MasterUserPassword property is set internal bool IsSetMasterUserPassword() { return this._masterUserPassword != null; } /// <summary> /// Gets and sets the property NodeType. /// <para> /// The node type to be provisioned for the cluster. For information about node types, /// go to <a href="http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#how-many-nodes"> /// Working with Clusters</a> in the <i>Amazon Redshift Cluster Management Guide</i>. /// /// </para> /// /// <para> /// Valid Values: <code>ds1.xlarge</code> | <code>ds1.8xlarge</code> | <code>ds2.xlarge</code> /// | <code>ds2.8xlarge</code> | <code>dc1.large</code> | <code>dc1.8xlarge</code>. /// </para> /// </summary> public string NodeType { get { return this._nodeType; } set { this._nodeType = value; } } // Check to see if NodeType property is set internal bool IsSetNodeType() { return this._nodeType != null; } /// <summary> /// Gets and sets the property NumberOfNodes. /// <para> /// The number of compute nodes in the cluster. This parameter is required when the <b>ClusterType</b> /// parameter is specified as <code>multi-node</code>. /// </para> /// /// <para> /// For information about determining how many nodes you need, go to <a href="http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#how-many-nodes"> /// Working with Clusters</a> in the <i>Amazon Redshift Cluster Management Guide</i>. /// /// </para> /// /// <para> /// If you don't specify this parameter, you get a single-node cluster. When requesting /// a multi-node cluster, you must specify the number of nodes that you want in the cluster. /// </para> /// /// <para> /// Default: <code>1</code> /// </para> /// /// <para> /// Constraints: Value must be at least 1 and no more than 100. /// </para> /// </summary> public int NumberOfNodes { get { return this._numberOfNodes.GetValueOrDefault(); } set { this._numberOfNodes = value; } } // Check to see if NumberOfNodes property is set internal bool IsSetNumberOfNodes() { return this._numberOfNodes.HasValue; } /// <summary> /// Gets and sets the property Port. /// <para> /// The port number on which the cluster accepts incoming connections. /// </para> /// /// <para> /// The cluster is accessible only via the JDBC and ODBC connection strings. Part of the /// connection string requires the port on which the cluster will listen for incoming /// connections. /// </para> /// /// <para> /// Default: <code>5439</code> /// </para> /// /// <para> /// Valid Values: <code>1150-65535</code> /// </para> /// </summary> public int Port { get { return this._port.GetValueOrDefault(); } set { this._port = value; } } // Check to see if Port property is set internal bool IsSetPort() { return this._port.HasValue; } /// <summary> /// Gets and sets the property PreferredMaintenanceWindow. /// <para> /// The weekly time range (in UTC) during which automated cluster maintenance can occur. /// /// </para> /// /// <para> /// Format: <code>ddd:hh24:mi-ddd:hh24:mi</code> /// </para> /// /// <para> /// Default: A 30-minute window selected at random from an 8-hour block of time per region, /// occurring on a random day of the week. For more information about the time blocks /// for each region, see <a href="http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#rs-maintenance-windows">Maintenance /// Windows</a> in Amazon Redshift Cluster Management Guide. /// </para> /// /// <para> /// Valid Days: Mon | Tue | Wed | Thu | Fri | Sat | Sun /// </para> /// /// <para> /// Constraints: Minimum 30-minute window. /// </para> /// </summary> public string PreferredMaintenanceWindow { get { return this._preferredMaintenanceWindow; } set { this._preferredMaintenanceWindow = value; } } // Check to see if PreferredMaintenanceWindow property is set internal bool IsSetPreferredMaintenanceWindow() { return this._preferredMaintenanceWindow != null; } /// <summary> /// Gets and sets the property PubliclyAccessible. /// <para> /// If <code>true</code>, the cluster can be accessed from a public network. /// </para> /// </summary> public bool PubliclyAccessible { get { return this._publiclyAccessible.GetValueOrDefault(); } set { this._publiclyAccessible = value; } } // Check to see if PubliclyAccessible property is set internal bool IsSetPubliclyAccessible() { return this._publiclyAccessible.HasValue; } /// <summary> /// Gets and sets the property Tags. /// <para> /// A list of tag instances. /// </para> /// </summary> public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } /// <summary> /// Gets and sets the property VpcSecurityGroupIds. /// <para> /// A list of Virtual Private Cloud (VPC) security groups to be associated with the cluster. /// </para> /// /// <para> /// Default: The default VPC security group is associated with the cluster. /// </para> /// </summary> public List<string> VpcSecurityGroupIds { get { return this._vpcSecurityGroupIds; } set { this._vpcSecurityGroupIds = value; } } // Check to see if VpcSecurityGroupIds property is set internal bool IsSetVpcSecurityGroupIds() { return this._vpcSecurityGroupIds != null && this._vpcSecurityGroupIds.Count > 0; } } }
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <author name="Daniel Grunwald"/> // <version>$Revision: 5762 $</version> // </file> using System; using System.ComponentModel; using System.Diagnostics; using ICSharpCode.AvalonEdit.Utils; namespace ICSharpCode.AvalonEdit.Document { /// <summary> /// Undo stack implementation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] public sealed class UndoStack : INotifyPropertyChanged { /// undo stack is listening for changes internal const int StateListen = 0; /// undo stack is reverting/repeating a set of changes internal const int StatePlayback = 1; // undo stack is reverting/repeating a set of changes and modifies the document to do this internal const int StatePlaybackModifyDocument = 2; /// state is used for checking that noone but the UndoStack performs changes /// during Undo events internal int state = StateListen; Deque<IUndoableOperation> undostack = new Deque<IUndoableOperation>(); Deque<IUndoableOperation> redostack = new Deque<IUndoableOperation>(); int sizeLimit = int.MaxValue; int undoGroupDepth; int actionCountInUndoGroup; int optionalActionCount; object lastGroupDescriptor; bool allowContinue; #region IsOriginalFile implementation // implements feature request SD2-784 - File still considered dirty after undoing all changes /// <summary> /// Number of times undo must be executed until the original state is reached. /// Negative: number of times redo must be executed until the original state is reached. /// Special case: int.MinValue == original state is unreachable /// </summary> int elementsOnUndoUntilOriginalFile; bool isOriginalFile = true; /// <summary> /// Gets whether the document is currently in its original state (no modifications). /// </summary> public bool IsOriginalFile { get { return isOriginalFile; } } void RecalcIsOriginalFile() { bool newIsOriginalFile = (elementsOnUndoUntilOriginalFile == 0); if (newIsOriginalFile != isOriginalFile) { isOriginalFile = newIsOriginalFile; NotifyPropertyChanged("IsOriginalFile"); } } /// <summary> /// Marks the current state as original. Discards any previous "original" markers. /// </summary> public void MarkAsOriginalFile() { elementsOnUndoUntilOriginalFile = 0; RecalcIsOriginalFile(); } /// <summary> /// Discards the current "original" marker. /// </summary> public void DiscardOriginalFileMarker() { elementsOnUndoUntilOriginalFile = int.MinValue; RecalcIsOriginalFile(); } void FileModified(int newElementsOnUndoStack) { if (elementsOnUndoUntilOriginalFile == int.MinValue) return; elementsOnUndoUntilOriginalFile += newElementsOnUndoStack; if (elementsOnUndoUntilOriginalFile > undostack.Count) elementsOnUndoUntilOriginalFile = int.MinValue; // don't call RecalcIsOriginalFile(): wait until end of undo group } #endregion /// <summary> /// Gets if the undo stack currently accepts changes. /// Is false while an undo action is running. /// </summary> public bool AcceptChanges { get { return state == StateListen; } } /// <summary> /// Gets if there are actions on the undo stack. /// Use the PropertyChanged event to listen to changes of this property. /// </summary> public bool CanUndo { get { return undostack.Count > 0; } } /// <summary> /// Gets if there are actions on the redo stack. /// Use the PropertyChanged event to listen to changes of this property. /// </summary> public bool CanRedo { get { return redostack.Count > 0; } } /// <summary> /// Gets/Sets the limit on the number of items on the undo stack. /// </summary> /// <remarks>The size limit is enforced only on the number of stored top-level undo groups. /// Elements within undo groups do not count towards the size limit.</remarks> public int SizeLimit { get { return sizeLimit; } set { if (value < 0) ThrowUtil.CheckNotNegative(value, "value"); if (sizeLimit != value) { sizeLimit = value; NotifyPropertyChanged("SizeLimit"); if (undoGroupDepth == 0) EnforceSizeLimit(); } } } void EnforceSizeLimit() { Debug.Assert(undoGroupDepth == 0); while (undostack.Count > sizeLimit) undostack.PopFront(); while (redostack.Count > sizeLimit) redostack.PopFront(); } /// <summary> /// If an undo group is open, gets the group descriptor of the current top-level /// undo group. /// If no undo group is open, gets the group descriptor from the previous undo group. /// </summary> /// <remarks>The group descriptor can be used to join adjacent undo groups: /// use a group descriptor to mark your changes, and on the second action, /// compare LastGroupDescriptor and use <see cref="StartContinuedUndoGroup"/> if you /// want to join the undo groups.</remarks> public object LastGroupDescriptor { get { return lastGroupDescriptor; } } /// <summary> /// Starts grouping changes. /// Maintains a counter so that nested calls are possible. /// </summary> public void StartUndoGroup() { StartUndoGroup(null); } /// <summary> /// Starts grouping changes. /// Maintains a counter so that nested calls are possible. /// </summary> /// <param name="groupDescriptor">An object that is stored with the undo group. /// If this is not a top-level undo group, the parameter is ignored.</param> public void StartUndoGroup(object groupDescriptor) { if (undoGroupDepth == 0) { actionCountInUndoGroup = 0; optionalActionCount = 0; lastGroupDescriptor = groupDescriptor; } undoGroupDepth++; //Util.LoggingService.Debug("Open undo group (new depth=" + undoGroupDepth + ")"); } /// <summary> /// Starts grouping changes, continuing with the previously closed undo group if possible. /// Maintains a counter so that nested calls are possible. /// If the call to StartContinuedUndoGroup is a nested call, it behaves exactly /// as <see cref="StartUndoGroup()"/>, only top-level calls can continue existing undo groups. /// </summary> /// <param name="groupDescriptor">An object that is stored with the undo group. /// If this is not a top-level undo group, the parameter is ignored.</param> public void StartContinuedUndoGroup(object groupDescriptor) { if (undoGroupDepth == 0) { actionCountInUndoGroup = (allowContinue && undostack.Count > 0) ? 1 : 0; optionalActionCount = 0; lastGroupDescriptor = groupDescriptor; } undoGroupDepth++; //Util.LoggingService.Debug("Continue undo group (new depth=" + undoGroupDepth + ")"); } /// <summary> /// Stops grouping changes. /// </summary> public void EndUndoGroup() { if (undoGroupDepth == 0) throw new InvalidOperationException("There are no open undo groups"); undoGroupDepth--; //Util.LoggingService.Debug("Close undo group (new depth=" + undoGroupDepth + ")"); if (undoGroupDepth == 0) { if (actionCountInUndoGroup == optionalActionCount) { // only optional actions: don't store them for (int i = 0; i < optionalActionCount; i++) { undostack.PopBack(); } } else if (actionCountInUndoGroup > 1) { // combine all actions within the group into a single grouped action undostack.PushBack(new UndoOperationGroup(undostack, actionCountInUndoGroup)); FileModified(-actionCountInUndoGroup + 1 + optionalActionCount); } EnforceSizeLimit(); allowContinue = true; RecalcIsOriginalFile(); // can raise event } } /// <summary> /// Throws an InvalidOperationException if an undo group is current open. /// </summary> void ThrowIfUndoGroupOpen() { if (undoGroupDepth != 0) { undoGroupDepth = 0; throw new InvalidOperationException("No undo group should be open at this point"); } if (state != StateListen) { throw new InvalidOperationException("This method cannot be called while an undo operation is being performed"); } } /// <summary> /// Call this method to undo the last operation on the stack /// </summary> public void Undo() { ThrowIfUndoGroupOpen(); if (undostack.Count > 0) { // disallow continuing undo groups after undo operation lastGroupDescriptor = null; allowContinue = false; // fetch operation to undo and move it to redo stack IUndoableOperation uedit = undostack.PopBack(); redostack.PushBack(uedit); state = StatePlayback; try { RunUndo(uedit); } finally { state = StateListen; } FileModified(-1); RecalcIsOriginalFile(); if (undostack.Count == 0) NotifyPropertyChanged("CanUndo"); if (redostack.Count == 1) NotifyPropertyChanged("CanRedo"); } } internal void RunUndo(IUndoableOperation op) { IUndoableOperationWithContext opWithCtx = op as IUndoableOperationWithContext; if (opWithCtx != null) opWithCtx.Undo(this); else op.Undo(); } /// <summary> /// Call this method to redo the last undone operation /// </summary> public void Redo() { ThrowIfUndoGroupOpen(); if (redostack.Count > 0) { lastGroupDescriptor = null; allowContinue = false; IUndoableOperation uedit = redostack.PopBack(); undostack.PushBack(uedit); state = StatePlayback; try { RunRedo(uedit); } finally { state = StateListen; } FileModified(1); RecalcIsOriginalFile(); if (redostack.Count == 0) NotifyPropertyChanged("CanRedo"); if (undostack.Count == 1) NotifyPropertyChanged("CanUndo"); } } internal void RunRedo(IUndoableOperation op) { IUndoableOperationWithContext opWithCtx = op as IUndoableOperationWithContext; if (opWithCtx != null) opWithCtx.Redo(this); else op.Redo(); } /// <summary> /// Call this method to push an UndoableOperation on the undostack. /// The redostack will be cleared if you use this method. /// </summary> public void Push(IUndoableOperation operation) { Push(operation, false); } /// <summary> /// Call this method to push an UndoableOperation on the undostack. /// However, the operation will be only stored if the undo group contains a /// non-optional operation. /// Use this method to store the caret position/selection on the undo stack to /// prevent having only actions that affect only the caret and not the document. /// </summary> public void PushOptional(IUndoableOperation operation) { if (undoGroupDepth == 0) throw new InvalidOperationException("Cannot use PushOptional outside of undo group"); Push(operation, true); } void Push(IUndoableOperation operation, bool isOptional) { if (operation == null) { throw new ArgumentNullException("operation"); } if (state == StateListen && sizeLimit > 0) { bool wasEmpty = undostack.Count == 0; StartUndoGroup(); undostack.PushBack(operation); actionCountInUndoGroup++; if (isOptional) optionalActionCount++; else FileModified(1); EndUndoGroup(); if (wasEmpty) NotifyPropertyChanged("CanUndo"); ClearRedoStack(); } } /// <summary> /// Call this method, if you want to clear the redo stack /// </summary> public void ClearRedoStack() { if (redostack.Count != 0) { redostack.Clear(); NotifyPropertyChanged("CanRedo"); // if the "orginal file" marker is on the redo stack: remove it if (elementsOnUndoUntilOriginalFile < 0) elementsOnUndoUntilOriginalFile = int.MinValue; } } /// <summary> /// Clears both the undo and redo stack. /// </summary> public void ClearAll() { ThrowIfUndoGroupOpen(); actionCountInUndoGroup = 0; optionalActionCount = 0; if (undostack.Count != 0) { lastGroupDescriptor = null; allowContinue = false; undostack.Clear(); NotifyPropertyChanged("CanUndo"); } ClearRedoStack(); } internal void AttachToDocument(TextDocument document) { document.UpdateStarted += document_UpdateStarted; document.UpdateFinished += document_UpdateFinished; document.Changing += document_Changing; } void document_UpdateStarted(object sender, EventArgs e) { StartUndoGroup(); } void document_UpdateFinished(object sender, EventArgs e) { EndUndoGroup(); } void document_Changing(object sender, DocumentChangeEventArgs e) { if (state == StatePlayback) throw new InvalidOperationException("Document changes during undo/redo operations are not allowed."); TextDocument document = (TextDocument)sender; Push(new DocumentChangeOperation(document, e)); } /// <summary> /// Is raised when a property (CanUndo, CanRedo) changed. /// </summary> public event PropertyChangedEventHandler PropertyChanged; void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading.Tasks; using Orleans.Runtime.Configuration; namespace Orleans.Runtime.Scheduler { [DebuggerDisplay("WorkItemGroup Name={Name} State={state}")] internal class WorkItemGroup : IWorkItem { private enum WorkGroupStatus { Waiting = 0, Runnable = 1, Running = 2, Shutdown = 3 } private static readonly Logger appLogger = LogManager.GetLogger("Scheduler.WorkItemGroup", LoggerType.Runtime); private readonly Logger log; private readonly OrleansTaskScheduler masterScheduler; private WorkGroupStatus state; private readonly Object lockable; private readonly Queue<Task> workItems; private long totalItemsEnQueued; // equals total items queued, + 1 private long totalItemsProcessed; private readonly QueueTrackingStatistic queueTracking; private TimeSpan totalQueuingDelay; private readonly long quantumExpirations; private readonly int workItemGroupStatisticsNumber; internal ActivationTaskScheduler TaskRunner { get; private set; } public DateTime TimeQueued { get; set; } public TimeSpan TimeSinceQueued { get { return Utils.Since(TimeQueued); } } public ISchedulingContext SchedulingContext { get; set; } public bool IsSystemPriority { get { return SchedulingUtils.IsSystemPriorityContext(SchedulingContext); } } internal bool IsSystemGroup { get { return SchedulingUtils.IsSystemContext(SchedulingContext); } } public string Name { get { return SchedulingContext == null ? "unknown" : SchedulingContext.Name; } } internal int ExternalWorkItemCount { get { lock (lockable) { return WorkItemCount; } } } private int WorkItemCount { get { return workItems.Count; } } internal float AverageQueueLenght { get { #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectShedulerQueuesStats) { return queueTracking.AverageQueueLength; } #endif return 0; } } internal float NumEnqueuedRequests { get { #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectShedulerQueuesStats) { return queueTracking.NumEnqueuedRequests; } #endif return 0; } } internal float ArrivalRate { get { #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectShedulerQueuesStats) { return queueTracking.ArrivalRate; } #endif return 0; } } private bool IsActive { get { return WorkItemCount != 0; } } // This is the maximum number of work items to be processed in an activation turn. // If this is set to zero or a negative number, then the full work queue is drained (MaxTimePerTurn allowing). private const int MaxWorkItemsPerTurn = 0; // Unlimited // This is a soft time limit on the duration of activation macro-turn (a number of micro-turns). // If a activation was running its micro-turns longer than this, we will give up the thread. // If this is set to zero or a negative number, then the full work queue is drained (MaxWorkItemsPerTurn allowing). public static TimeSpan ActivationSchedulingQuantum { get; set; } // This is the maximum number of waiting threads (blocked in WaitForResponse) allowed // per ActivationWorker. An attempt to wait when there are already too many threads waiting // will result in a TooManyWaitersException being thrown. //private static readonly int MaxWaitingThreads = 500; internal WorkItemGroup(OrleansTaskScheduler sched, ISchedulingContext schedulingContext) { masterScheduler = sched; SchedulingContext = schedulingContext; state = WorkGroupStatus.Waiting; workItems = new Queue<Task>(); lockable = new Object(); totalItemsEnQueued = 0; totalItemsProcessed = 0; totalQueuingDelay = TimeSpan.Zero; quantumExpirations = 0; TaskRunner = new ActivationTaskScheduler(this); log = IsSystemPriority ? LogManager.GetLogger("Scheduler." + Name + ".WorkItemGroup", LoggerType.Runtime) : appLogger; if (StatisticsCollector.CollectShedulerQueuesStats) { queueTracking = new QueueTrackingStatistic("Scheduler." + SchedulingContext.Name); queueTracking.OnStartExecution(); } if (StatisticsCollector.CollectPerWorkItemStats) { workItemGroupStatisticsNumber = SchedulerStatisticsGroup.RegisterWorkItemGroup(SchedulingContext.Name, SchedulingContext, () => { var sb = new StringBuilder(); lock (lockable) { sb.Append("QueueLength = " + WorkItemCount); sb.Append(String.Format(", State = {0}", state)); if (state == WorkGroupStatus.Runnable) sb.Append(String.Format("; oldest item is {0} old", workItems.Count >= 0 ? workItems.Peek().ToString() : "null")); } return sb.ToString(); }); } } /// <summary> /// Adds a task to this activation. /// If we're adding it to the run list and we used to be waiting, now we're runnable. /// </summary> /// <param name="task">The work item to add.</param> public void EnqueueTask(Task task) { lock (lockable) { #if DEBUG if (log.IsVerbose2) log.Verbose2("EnqueueWorkItem {0} into {1} when TaskScheduler.Current={2}", task, SchedulingContext, TaskScheduler.Current); #endif if (state == WorkGroupStatus.Shutdown) { ReportWorkGroupProblem( String.Format("Enqueuing task {0} to a stopped work item group. Going to ignore and not execute it. " + "The likely reason is that the task is not being 'awaited' properly.", task), ErrorCode.SchedulerNotEnqueuWorkWhenShutdown); task.Ignore(); // Ignore this Task, so in case it is faulted it will not cause UnobservedException. return; } long thisSequenceNumber = totalItemsEnQueued++; int count = WorkItemCount; #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectShedulerQueuesStats) queueTracking.OnEnQueueRequest(1, count); if (StatisticsCollector.CollectGlobalShedulerStats) SchedulerStatisticsGroup.OnWorkItemEnqueue(); #endif workItems.Enqueue(task); int maxPendingItemsLimit = masterScheduler.MaxPendingItemsLimit.SoftLimitThreshold; if (maxPendingItemsLimit > 0 && count > maxPendingItemsLimit) { log.Warn(ErrorCode.SchedulerTooManyPendingItems, String.Format("{0} pending work items for group {1}, exceeding the warning threshold of {2}", count, Name, maxPendingItemsLimit)); } if (state != WorkGroupStatus.Waiting) return; state = WorkGroupStatus.Runnable; #if DEBUG if (log.IsVerbose3) log.Verbose3("Add to RunQueue {0}, #{1}, onto {2}", task, thisSequenceNumber, SchedulingContext); #endif masterScheduler.RunQueue.Add(this); } } /// <summary> /// Shuts down this work item group so that it will not process any additional work items, even if they /// have already been queued. /// </summary> internal void Stop() { lock (lockable) { if (IsActive) { ReportWorkGroupProblem( String.Format("WorkItemGroup is being stoped while still active. workItemCount = {0}." + "The likely reason is that the task is not being 'awaited' properly.", WorkItemCount), ErrorCode.SchedulerWorkGroupStopping); } if (state == WorkGroupStatus.Shutdown) { log.Warn(ErrorCode.SchedulerWorkGroupShuttingDown, "WorkItemGroup is already shutting down {0}", this.ToString()); return; } state = WorkGroupStatus.Shutdown; if (StatisticsCollector.CollectPerWorkItemStats) SchedulerStatisticsGroup.UnRegisterWorkItemGroup(workItemGroupStatisticsNumber); if (StatisticsCollector.CollectGlobalShedulerStats) SchedulerStatisticsGroup.OnWorkItemDrop(WorkItemCount); if (StatisticsCollector.CollectShedulerQueuesStats) queueTracking.OnStopExecution(); foreach (Task task in workItems) { // Ignore all queued Tasks, so in case they are faulted they will not cause UnobservedException. task.Ignore(); } workItems.Clear(); } } #region IWorkItem Members public WorkItemType ItemType { get { return WorkItemType.WorkItemGroup; } } // Execute one or more turns for this activation. // This method is always called in a single-threaded environment -- that is, no more than one // thread will be in this method at once -- but other asynch threads may still be queueing tasks, etc. public void Execute() { lock (lockable) { if (state == WorkGroupStatus.Shutdown) { if (!IsActive) return; // Don't mind if no work has been queued to this work group yet. ReportWorkGroupProblemWithBacktrace( "Cannot execute work items in a work item group that is in a shutdown state.", ErrorCode.SchedulerNotExecuteWhenShutdown); // Throws InvalidOperationException return; } state = WorkGroupStatus.Running; } var thread = WorkerPoolThread.CurrentWorkerThread; try { // Process multiple items -- drain the applicationMessageQueue (up to max items) for this physical activation int count = 0; var stopwatch = new Stopwatch(); stopwatch.Start(); do { lock (lockable) { if (state == WorkGroupStatus.Shutdown) { if (WorkItemCount > 0) log.Warn(ErrorCode.SchedulerSkipWorkStopping, "Thread {0} is exiting work loop due to Shutdown state {1} while still having {2} work items in the queue.", thread.ToString(), this.ToString(), WorkItemCount); else if(log.IsVerbose) log.Verbose("Thread {0} is exiting work loop due to Shutdown state {1}. Has {2} work items in the queue.", thread.ToString(), this.ToString(), WorkItemCount); break; } // Check the cancellation token (means that the silo is stopping) if (thread.CancelToken.IsCancellationRequested) { log.Warn(ErrorCode.SchedulerSkipWorkCancelled, "Thread {0} is exiting work loop due to cancellation token. WorkItemGroup: {1}, Have {2} work items in the queue.", thread.ToString(), this.ToString(), WorkItemCount); break; } } // Get the first Work Item on the list Task task; lock (lockable) { if (workItems.Count > 0) task = workItems.Dequeue(); else // If the list is empty, then we're done break; } #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectGlobalShedulerStats) SchedulerStatisticsGroup.OnWorkItemDequeue(); #endif #if DEBUG if (log.IsVerbose2) log.Verbose2("About to execute task {0} in SchedulingContext={1}", task, SchedulingContext); #endif var taskStart = stopwatch.Elapsed; try { thread.CurrentTask = task; #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectTurnsStats) SchedulerStatisticsGroup.OnTurnExecutionStartsByWorkGroup(workItemGroupStatisticsNumber, thread.WorkerThreadStatisticsNumber, SchedulingContext); #endif TaskRunner.RunTask(task); } catch (Exception ex) { log.Error(ErrorCode.SchedulerExceptionFromExecute, String.Format("Worker thread caught an exception thrown from Execute by task {0}", task), ex); throw; } finally { #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectTurnsStats) SchedulerStatisticsGroup.OnTurnExecutionEnd(Utils.Since(thread.CurrentStateStarted)); if (StatisticsCollector.CollectThreadTimeTrackingStats) thread.threadTracking.IncrementNumberOfProcessed(); #endif totalItemsProcessed++; var taskLength = stopwatch.Elapsed - taskStart; if (taskLength > OrleansTaskScheduler.TurnWarningLengthThreshold) { SchedulerStatisticsGroup.NumLongRunningTurns.Increment(); log.Warn(ErrorCode.SchedulerTurnTooLong3, "Task {0} in WorkGroup {1} took elapsed time {2:g} for execution, which is longer than {3}. Running on thread {4}", OrleansTaskExtentions.ToString(task), SchedulingContext.ToString(), taskLength, OrleansTaskScheduler.TurnWarningLengthThreshold, thread.ToString()); } thread.CurrentTask = null; } count++; } while (((MaxWorkItemsPerTurn <= 0) || (count <= MaxWorkItemsPerTurn)) && ((ActivationSchedulingQuantum <= TimeSpan.Zero) || (stopwatch.Elapsed < ActivationSchedulingQuantum))); stopwatch.Stop(); } catch (Exception ex) { log.Error(ErrorCode.Runtime_Error_100032, String.Format("Worker thread {0} caught an exception thrown from IWorkItem.Execute", thread), ex); } finally { // Now we're not Running anymore. // If we left work items on our run list, we're Runnable, and need to go back on the silo run queue; // If our run list is empty, then we're waiting. lock (lockable) { if (state != WorkGroupStatus.Shutdown) { if (WorkItemCount > 0) { state = WorkGroupStatus.Runnable; masterScheduler.RunQueue.Add(this); } else { state = WorkGroupStatus.Waiting; } } } } } #endregion public override string ToString() { return String.Format("{0}WorkItemGroup:Name={1},WorkGroupStatus={2}", IsSystemGroup ? "System*" : "", Name, state); } public string DumpStatus() { lock (lockable) { var sb = new StringBuilder(); sb.Append(this); sb.AppendFormat(". Currently QueuedWorkItems={0}; Total EnQueued={1}; Total processed={2}; Quantum expirations={3}; ", WorkItemCount, totalItemsEnQueued, totalItemsProcessed, quantumExpirations); if (AverageQueueLenght > 0) { sb.AppendFormat("average queue length at enqueue: {0}; ", AverageQueueLenght); if (!totalQueuingDelay.Equals(TimeSpan.Zero) && totalItemsProcessed > 0) { sb.AppendFormat("average queue delay: {0}ms; ", totalQueuingDelay.Divide(totalItemsProcessed).TotalMilliseconds); } } sb.AppendFormat("TaskRunner={0}; ", TaskRunner); if (SchedulingContext != null) { sb.AppendFormat("Detailed SchedulingContext=<{0}>", SchedulingContext.DetailedStatus()); } return sb.ToString(); } } private void ReportWorkGroupProblemWithBacktrace(string what, ErrorCode errorCode) { var st = new StackTrace(); var msg = string.Format("{0} {1}", what, DumpStatus()); log.Warn(errorCode, msg + Environment.NewLine + " Called from " + st); } private void ReportWorkGroupProblem(string what, ErrorCode errorCode) { var msg = string.Format("{0} {1}", what, DumpStatus()); log.Warn(errorCode, msg); } } }
using System; using System.Collections.Generic; namespace Prism.Common { /// <summary> /// A dictionary of lists. /// </summary> /// <typeparam name="TKey">The key to use for lists.</typeparam> /// <typeparam name="TValue">The type of the value held by lists.</typeparam> public sealed class ListDictionary<TKey, TValue> : IDictionary<TKey, IList<TValue>> { Dictionary<TKey, IList<TValue>> innerValues = new Dictionary<TKey, IList<TValue>>(); #region Public Methods /// <summary> /// If a list does not already exist, it will be created automatically. /// </summary> /// <param name="key">The key of the list that will hold the value.</param> public void Add(TKey key) { if (key == null) throw new ArgumentNullException(nameof(key)); CreateNewList(key); } /// <summary> /// Adds a value to a list with the given key. If a list does not already exist, /// it will be created automatically. /// </summary> /// <param name="key">The key of the list that will hold the value.</param> /// <param name="value">The value to add to the list under the given key.</param> public void Add(TKey key, TValue value) { if (key == null) throw new ArgumentNullException(nameof(key)); if (value == null) throw new ArgumentNullException(nameof(value)); if (innerValues.ContainsKey(key)) { innerValues[key].Add(value); } else { List<TValue> values = CreateNewList(key); values.Add(value); } } private List<TValue> CreateNewList(TKey key) { List<TValue> values = new List<TValue>(); innerValues.Add(key, values); return values; } /// <summary> /// Removes all entries in the dictionary. /// </summary> public void Clear() { innerValues.Clear(); } /// <summary> /// Determines whether the dictionary contains the specified value. /// </summary> /// <param name="value">The value to locate.</param> /// <returns>true if the dictionary contains the value in any list; otherwise, false.</returns> public bool ContainsValue(TValue value) { foreach (KeyValuePair<TKey, IList<TValue>> pair in innerValues) { if (pair.Value.Contains(value)) { return true; } } return false; } /// <summary> /// Determines whether the dictionary contains the given key. /// </summary> /// <param name="key">The key to locate.</param> /// <returns>true if the dictionary contains the given key; otherwise, false.</returns> public bool ContainsKey(TKey key) { if (key == null) throw new ArgumentNullException(nameof(key)); return innerValues.ContainsKey(key); } /// <summary> /// Retrieves the all the elements from the list which have a key that matches the condition /// defined by the specified predicate. /// </summary> /// <param name="keyFilter">The filter with the condition to use to filter lists by their key.</param> /// <returns>The elements that have a key that matches the condition defined by the specified predicate.</returns> public IEnumerable<TValue> FindAllValuesByKey(Predicate<TKey> keyFilter) { foreach (KeyValuePair<TKey, IList<TValue>> pair in this) { if (keyFilter(pair.Key)) { foreach (TValue value in pair.Value) { yield return value; } } } } /// <summary> /// Retrieves all the elements that match the condition defined by the specified predicate. /// </summary> /// <param name="valueFilter">The filter with the condition to use to filter values.</param> /// <returns>The elements that match the condition defined by the specified predicate.</returns> public IEnumerable<TValue> FindAllValues(Predicate<TValue> valueFilter) { foreach (KeyValuePair<TKey, IList<TValue>> pair in this) { foreach (TValue value in pair.Value) { if (valueFilter(value)) { yield return value; } } } } /// <summary> /// Removes a list by key. /// </summary> /// <param name="key">The key of the list to remove.</param> /// <returns><see langword="true" /> if the element was removed.</returns> public bool Remove(TKey key) { if (key == null) throw new ArgumentNullException(nameof(key)); return innerValues.Remove(key); } /// <summary> /// Removes a value from the list with the given key. /// </summary> /// <param name="key">The key of the list where the value exists.</param> /// <param name="value">The value to remove.</param> public void RemoveValue(TKey key, TValue value) { if (key == null) throw new ArgumentNullException(nameof(key)); if (value == null) throw new ArgumentNullException(nameof(value)); if (innerValues.ContainsKey(key)) { List<TValue> innerList = (List<TValue>)innerValues[key]; innerList.RemoveAll(delegate (TValue item) { return value.Equals(item); }); } } /// <summary> /// Removes a value from all lists where it may be found. /// </summary> /// <param name="value">The value to remove.</param> public void RemoveValue(TValue value) { foreach (KeyValuePair<TKey, IList<TValue>> pair in innerValues) { RemoveValue(pair.Key, value); } } #endregion #region Properties /// <summary> /// Gets a shallow copy of all values in all lists. /// </summary> /// <value>List of values.</value> public IList<TValue> Values { get { List<TValue> values = new List<TValue>(); foreach (IEnumerable<TValue> list in innerValues.Values) { values.AddRange(list); } return values; } } /// <summary> /// Gets the list of keys in the dictionary. /// </summary> /// <value>Collection of keys.</value> public ICollection<TKey> Keys { get { return innerValues.Keys; } } /// <summary> /// Gets or sets the list associated with the given key. The /// access always succeeds, eventually returning an empty list. /// </summary> /// <param name="key">The key of the list to access.</param> /// <returns>The list associated with the key.</returns> public IList<TValue> this[TKey key] { get { if (innerValues.ContainsKey(key) == false) { innerValues.Add(key, new List<TValue>()); } return innerValues[key]; } set { innerValues[key] = value; } } /// <summary> /// Gets the number of lists in the dictionary. /// </summary> /// <value>Value indicating the values count.</value> public int Count { get { return innerValues.Count; } } #endregion #region IDictionary<TKey,List<TValue>> Members /// <summary> /// See <see cref="IDictionary{TKey,TValue}.Add"/> for more information. /// </summary> void IDictionary<TKey, IList<TValue>>.Add(TKey key, IList<TValue> value) { if (key == null) throw new ArgumentNullException(nameof(key)); if (value == null) throw new ArgumentNullException(nameof(value)); innerValues.Add(key, value); } /// <summary> /// See <see cref="IDictionary{TKey,TValue}.TryGetValue"/> for more information. /// </summary> bool IDictionary<TKey, IList<TValue>>.TryGetValue(TKey key, out IList<TValue> value) { value = this[key]; return true; } /// <summary> /// See <see cref="IDictionary{TKey,TValue}.Values"/> for more information. /// </summary> ICollection<IList<TValue>> IDictionary<TKey, IList<TValue>>.Values { get { return innerValues.Values; } } #endregion #region ICollection<KeyValuePair<TKey,List<TValue>>> Members /// <summary> /// See <see cref="ICollection{TValue}.Add"/> for more information. /// </summary> void ICollection<KeyValuePair<TKey, IList<TValue>>>.Add(KeyValuePair<TKey, IList<TValue>> item) { ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).Add(item); } /// <summary> /// See <see cref="ICollection{TValue}.Contains"/> for more information. /// </summary> bool ICollection<KeyValuePair<TKey, IList<TValue>>>.Contains(KeyValuePair<TKey, IList<TValue>> item) { return ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).Contains(item); } /// <summary> /// See <see cref="ICollection{TValue}.CopyTo"/> for more information. /// </summary> void ICollection<KeyValuePair<TKey, IList<TValue>>>.CopyTo(KeyValuePair<TKey, IList<TValue>>[] array, int arrayIndex) { ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).CopyTo(array, arrayIndex); } /// <summary> /// See <see cref="ICollection{TValue}.IsReadOnly"/> for more information. /// </summary> bool ICollection<KeyValuePair<TKey, IList<TValue>>>.IsReadOnly { get { return ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).IsReadOnly; } } /// <summary> /// See <see cref="ICollection{TValue}.Remove"/> for more information. /// </summary> bool ICollection<KeyValuePair<TKey, IList<TValue>>>.Remove(KeyValuePair<TKey, IList<TValue>> item) { return ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).Remove(item); } #endregion #region IEnumerable<KeyValuePair<TKey,List<TValue>>> Members /// <summary> /// See <see cref="IEnumerable{TValue}.GetEnumerator"/> for more information. /// </summary> IEnumerator<KeyValuePair<TKey, IList<TValue>>> IEnumerable<KeyValuePair<TKey, IList<TValue>>>.GetEnumerator() { return innerValues.GetEnumerator(); } #endregion #region IEnumerable Members /// <summary> /// See <see cref="System.Collections.IEnumerable.GetEnumerator"/> for more information. /// </summary> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return innerValues.GetEnumerator(); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Markup; using Avalon.Internal.Utility; using Avalon.Windows.Converters; namespace Avalon.Windows.Utility { /// <summary> /// Encapsulates methods relating to WPF bindings. /// </summary> public static class BindingHelpers { #region Fields private static readonly List<DependencyProperty> _defaultProperties; #endregion #region Constructor /// <summary> /// Initializes the <see cref="BindingHelpers" /> class. /// </summary> static BindingHelpers() { _defaultProperties = new List<DependencyProperty> { TextBox.TextProperty, Selector.SelectedValueProperty }; EventManager.RegisterClassHandler(typeof(PasswordBox), PasswordBox.PasswordChangedEvent, new RoutedEventHandler(OnPasswordBoxChanged), true); } #endregion #region Methods /// <summary> /// Updates the source according to the default property. /// </summary> /// <param name="o">The source.</param> public static void UpdateSourceDefaultProperty(this DependencyObject o) { ArgumentValidator.NotNull(o, "o"); Type type = o.GetType(); DependencyProperty prop = GetDefaultDependencyProperty(type); BindingExpression exp = BindingOperations.GetBindingExpression(o, prop); if (exp != null) { exp.UpdateSource(); } } /// <summary> /// Updates the source according to the specified property. /// </summary> /// <param name="o">The source.</param> /// <param name="prop">The property.</param> public static void UpdateSourceProperty(this DependencyObject o, DependencyProperty prop) { ArgumentValidator.NotNull(o, "o"); ArgumentValidator.NotNull(prop, "prop"); BindingExpressionBase exp = BindingOperations.GetBindingExpressionBase(o, prop); if (exp != null) { exp.UpdateSource(); } } /// <summary> /// Updates the target of the specified bound property. /// </summary> /// <param name="o">The o.</param> /// <param name="prop">The prop.</param> public static void UpdateTarget(this DependencyObject o, DependencyProperty prop) { ArgumentValidator.NotNull(o, "o"); ArgumentValidator.NotNull(prop, "prop"); BindingExpressionBase exp = BindingOperations.GetBindingExpressionBase(o, prop); if (exp != null) { exp.UpdateTarget(); } } /// <summary> /// Determines whether the specified <see cref="DependencyObject" /> has an error. /// </summary> /// <param name="o">The source.</param> /// <returns> /// <c>true</c> if the specified o has error; otherwise, <c>false</c>. /// </returns> public static bool HasError(this DependencyObject o) { ArgumentValidator.NotNull(o, "o"); Type type = o.GetType(); DependencyProperty prop = GetDefaultDependencyProperty(type); return HasError(o, prop); } /// <summary> /// Determines whether the specified <see cref="DependencyObject" /> has an error /// for the specified <see cref="DependencyProperty" />. /// </summary> /// <param name="o">The source.</param> /// <param name="p">The property.</param> /// <returns> /// <c>true</c> if the specified o has error; otherwise, <c>false</c>. /// </returns> public static bool HasError(this DependencyObject o, DependencyProperty p) { var exp = BindingOperations.GetBindingExpression(o, p); return exp != null && exp.HasError; } /// <summary> /// Gets the all the data validation errors under a given root element. /// </summary> /// <param name="root">The root.</param> /// <param name="markInvalid">If set to <c>true</c> ensures the error template appears.</param> /// <returns></returns> public static ReadOnlyCollection<ValidationError> GetErrors(this DependencyObject root, bool markInvalid) { ArgumentValidator.NotNull(root, "root"); List<ValidationError> errors = new List<ValidationError>(); // this will traverse the entire descendant tree since the predicate always returns false root.FindVisualDescendant(delegate(DependencyObject o) { errors.AddRange(Validation.GetErrors(o)); return false; }); if (markInvalid) { foreach (ValidationError error in errors) { // causes the Validation.ErrorTemplate to appear Validation.MarkInvalid( (BindingExpressionBase)error.BindingInError, error); } } return errors.AsReadOnly(); } /// <summary> /// Gets the default <see cref="DependencyProperty" />. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public static DependencyProperty GetDefaultDependencyProperty(Type type) { ArgumentValidator.NotNull(type, "type"); var prop = _defaultProperties.FirstOrDefault(defaultProp => defaultProp.OwnerType.IsAssignableFrom(type)); if (prop == null) { string propertyName = GetDefaultPropertyName(type); if (propertyName != null) { prop = DependencyHelpers.GetDependencyProperty(type, GetDefaultPropertyName(type)); } } return prop; } /// <summary> /// Gets the default property name. /// </summary> /// <param name="type">The type.</param> /// <returns> /// The property name if it exists; otherwise <c>null</c>. /// </returns> public static string GetDefaultPropertyName(Type type) { ArgumentValidator.NotNull(type, "type"); object[] attrs = type.GetCustomAttributes(false); foreach (object attr in attrs) { ContentPropertyAttribute contentAttribute = attr as ContentPropertyAttribute; if (contentAttribute != null) { return contentAttribute.Name; } DefaultPropertyAttribute defaultAttribute = attr as DefaultPropertyAttribute; if (defaultAttribute != null) { return defaultAttribute.Name; } } return null; } /// <summary> /// Evaluates the property path for the specified object and returns its value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="path">The path.</param> /// <returns></returns> public static T Eval<T>(object source, string path) { ArgumentValidator.NotNull(path, "path"); if (source == null) { return default(T); } var binding = new Binding(path) { Source = source }; return Eval<T>(binding); } /// <summary> /// Evaluates the binding returns a value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="binding">The binding.</param> /// <returns></returns> public static T Eval<T>(this BindingBase binding) { ArgumentValidator.NotNull(binding, "binding"); var helper = new EvalHelper(); BindingOperations.SetBinding(helper, EvalHelper.ValueProperty, binding); T result = (T)helper.GetValue(EvalHelper.ValueProperty); BindingOperations.ClearBinding(helper, EvalHelper.ValueProperty); return result; } #endregion #region Missing Dependency Properties // Use these properties to circumvent places properties that were not defined as Dependency Properties, // and thus are not data-bindable. #region Password (PasswordBox) private static readonly HashSet<DependencyObject> _passwordLocks = new HashSet<DependencyObject>(); /// <summary> /// Gets the password. /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string GetPassword(DependencyObject obj) { return (string)obj.GetValue(PasswordProperty); } /// <summary> /// Sets the password. /// <remarks> /// Using this workaround compromises the security implemented in <see cref="PasswordBox" />. /// </remarks> /// </summary> /// <param name="obj"></param> /// <param name="value"></param> public static void SetPassword(DependencyObject obj, string value) { obj.SetValue(PasswordProperty, value); } /// <summary> /// Identifies the <c>Password</c> attached dependency property. /// </summary> public static readonly DependencyProperty PasswordProperty = DependencyProperty.RegisterAttached("Password", typeof(string), typeof(BindingHelpers), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Journal, OnPasswordChanged)); private static void OnPasswordChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { PasswordBox passwordBox = o as PasswordBox; if (passwordBox != null) { if (_passwordLocks.Contains(passwordBox)) return; _passwordLocks.Add(passwordBox); passwordBox.Password = (string)e.NewValue; _passwordLocks.Remove(passwordBox); } } private static void OnPasswordBoxChanged(object sender, RoutedEventArgs e) { PasswordBox passwordBox = sender as PasswordBox; if (passwordBox != null) { if (_passwordLocks.Contains(passwordBox)) return; _passwordLocks.Add(passwordBox); SetPassword(passwordBox, passwordBox.Password); _passwordLocks.Remove(passwordBox); } } #endregion #region Inlines (TextBlock) /// <summary> /// Gets the inlines. /// <remarks> /// Important: if the inlines in the TextBlock are changed after this property is set, /// the get will not reflect these changes. /// </remarks> /// </summary> /// <param name="obj"></param> /// <returns></returns> [TypeConverter(typeof(FormattedTextTypeConverter))] public static IEnumerable<Inline> GetInlines(DependencyObject obj) { return (IEnumerable<Inline>)obj.GetValue(InlinesProperty); } /// <summary> /// Sets the inlines. /// </summary> /// <param name="obj"></param> /// <param name="value"></param> [TypeConverter(typeof(FormattedTextTypeConverter))] public static void SetInlines(DependencyObject obj, IEnumerable<Inline> value) { obj.SetValue(InlinesProperty, value); } /// <summary> /// Identifies the <c>Inlines</c> attached dependency property. /// </summary> public static readonly DependencyProperty InlinesProperty = DependencyProperty.RegisterAttached("Inlines", typeof(IEnumerable<Inline>), typeof(BindingHelpers), new FrameworkPropertyMetadata(OnInlinesChanged)); private static void OnInlinesChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { if (e.NewValue != null) { TextBlock textBlock = o as TextBlock; if (textBlock != null) { textBlock.Inlines.AddRange((IEnumerable<Inline>)e.NewValue); } } } #endregion #region WindowStartupLocation (Window) /// <summary> /// Identifies the <c>WindowStartupLocation</c> attached dependency property. /// </summary> public static readonly DependencyProperty WindowStartupLocationProperty = DependencyProperty.RegisterAttached( "WindowStartupLocation", typeof(WindowStartupLocation), typeof(BindingHelpers), new FrameworkPropertyMetadata(OnWindowStartupLocationChanged)); private static void OnWindowStartupLocationChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((Window)d).WindowStartupLocation = (WindowStartupLocation)e.NewValue; } /// <summary> /// Sets the window startup location. /// </summary> /// <param name="window">The window.</param> /// <param name="value">The value.</param> public static void SetWindowStartupLocation(Window window, WindowStartupLocation value) { window.SetValue(WindowStartupLocationProperty, value); } /// <summary> /// Gets the window startup location. /// </summary> /// <param name="window">The window.</param> /// <returns></returns> public static WindowStartupLocation GetWindowStartupLocation(Window window) { return (WindowStartupLocation)window.GetValue(WindowStartupLocationProperty); } #endregion #endregion #region EvalHelper Class /// <summary> /// Used internally in the Eval method. /// </summary> private class EvalHelper : DependencyObject { public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(object), typeof(EvalHelper)); } #endregion } }
using System; using System.Collections.Generic; using Jsonics; using NUnit.Framework; namespace JsonicsTests.ToJsonTests { [TestFixture] public class ListTests { [Test] public void ToJson_IntList_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<int>>(); //act string json = converter.ToJson(new List<int>{1,2,3,4,5}); //assert Assert.That(json, Is.EqualTo("[1,2,3,4,5]")); } [Test] public void ToJson_StringList_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<string>>(); //act string json = converter.ToJson(new List<string>{"1","2","3","4","5"}); //assert Assert.That(json, Is.EqualTo("[\"1\",\"2\",\"3\",\"4\",\"5\"]")); } public class IntListObject { public List<int> IntListProperty { get; set; } } [Test] public void ToJson_ListTestObjectNullProperty_PropertyNotIncludedInJson() { //arrange var jsonConverter = JsonFactory.Compile<IntListObject>(); var testObject = new IntListObject(); //act var json = jsonConverter.ToJson(testObject); //assert Assert.That(json, Is.EqualTo("{\"IntListProperty\":null}")); } [Test] public void ToJson_ListTestObject_CorrectJson() { //arrange var jsonConverter = JsonFactory.Compile<IntListObject>(); var testObject = new IntListObject() { IntListProperty = new List<int>(){1,2,3,4,5} }; //act var json = jsonConverter.ToJson(testObject); //assert Assert.That(json, Is.EqualTo("{\"IntListProperty\":[1,2,3,4,5]}")); } public class StringListObject { public List<string> StringListProperty { get; set; } } [Test] public void ToJson_StringListObjectNullProperty_PropertyNotIncludedInJson() { //arrange var jsonConverter = JsonFactory.Compile<StringListObject>(); var testObject = new StringListObject(); //act var json = jsonConverter.ToJson(testObject); //assert Assert.That(json, Is.EqualTo("{\"StringListProperty\":null}")); } [Test] public void ToJson_StringListProperty_CorrectJson() { //arrange var jsonConverter = JsonFactory.Compile<StringListObject>(); var testObject = new StringListObject() { StringListProperty = new List<string>{"1","2","3","4","5"} }; //act var json = jsonConverter.ToJson(testObject); //assert Assert.That(json, Is.EqualTo("{\"StringListProperty\":[\"1\",\"2\",\"3\",\"4\",\"5\"]}")); } [Test] public void ToJson_StringListPropertyNeedsEscaping_CorrectJson() { //arrange var jsonConverter = JsonFactory.Compile<StringListObject>(); var testObject = new StringListObject() { StringListProperty = new List<string>{"1","2","3\"","4","5"} }; //act var json = jsonConverter.ToJson(testObject); //assert Assert.That(json, Is.EqualTo("{\"StringListProperty\":[\"1\",\"2\",\"3\\\"\",\"4\",\"5\"]}")); } [Test] public void ToJson_StringListPropertyEmtpy_CorrectJson() { //arrange var jsonConverter = JsonFactory.Compile<StringListObject>(); var testObject = new StringListObject() { StringListProperty = new List<string>{} }; //act var json = jsonConverter.ToJson(testObject); //assert Assert.That(json, Is.EqualTo("{\"StringListProperty\":[]}")); } [Test] public void ToJson_ListNullableInt_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<int?>>(); //act string json = converter.ToJson(new List<int?>{1,-2,3,null,4,5}); //assert Assert.That(json, Is.EqualTo("[1,-2,3,null,4,5]")); } [Test] public void ToJson_ListNullableUInt_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<uint?>>(); //act string json = converter.ToJson(new List<uint?>(){1,2,3,null,4,5}); //assert Assert.That(json, Is.EqualTo("[1,2,3,null,4,5]")); } [Test] public void ToJson_ListUInt_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<uint>>(); //act string json = converter.ToJson(new List<uint>{1,2,3,4,5}); //assert Assert.That(json, Is.EqualTo("[1,2,3,4,5]")); } [Test] public void ToJson_ListNullableShort_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<short?>>(); //act string json = converter.ToJson(new List<short?>{-11,2,3,null,4,5}); //assert Assert.That(json, Is.EqualTo("[-11,2,3,null,4,5]")); } [Test] public void ToJson_ListShort_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<short>>(); //act string json = converter.ToJson(new List<short>{-11,2,3,4,5}); //assert Assert.That(json, Is.EqualTo("[-11,2,3,4,5]")); } [Test] public void ToJson_ListNullableUShort_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<ushort?>>(); //act string json = converter.ToJson(new List<ushort?>(){1,2,3,null,4,5}); //assert Assert.That(json, Is.EqualTo("[1,2,3,null,4,5]")); } [Test] public void ToJson_ListUShort_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<ushort>>(); //act string json = converter.ToJson(new List<ushort>{1,2,3,4,5}); //assert Assert.That(json, Is.EqualTo("[1,2,3,4,5]")); } [Test] public void ToJson_ListNullableFloat_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<float?>>(); //act string json = converter.ToJson(new List<float?>{-11,2.2f,3,null,4,5}); //assert Assert.That(json, Is.EqualTo("[-11,2.2,3,null,4,5]")); } [Test] public void ToJson_ListFloat_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<float>>(); //act string json = converter.ToJson(new List<float>{-11.12f,2.2f,3,4,5.5f}); //assert Assert.That(json, Is.EqualTo("[-11.12,2.2,3,4,5.5]")); } [Test] public void ToJson_ListNullableDouble_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<double?>>(); //act string json = converter.ToJson(new List<double?>{-11,2.3d,3,null,4,5}); //assert Assert.That(json, Is.EqualTo("[-11,2.3,3,null,4,5]")); } [Test] public void ToJson_ListDouble_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<double>>(); //act string json = converter.ToJson(new List<double>{-11.12d,2.4d,3,4,5.5f}); //assert Assert.That(json, Is.EqualTo("[-11.12,2.4,3,4,5.5]")); } [Test] public void ToJson_ListNullableByte_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<byte?>>(); //act string json = converter.ToJson(new List<byte?>{255,0,1,null,3,4}); //assert Assert.That(json, Is.EqualTo("[255,0,1,null,3,4]")); } [Test] public void ToJson_ListByte_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<byte>>(); //act string json = converter.ToJson(new List<byte>{255,0,1,3,4}); //assert Assert.That(json, Is.EqualTo("[255,0,1,3,4]")); } [Test] public void ToJson_ListNullableSByte_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<sbyte?>>(); //act string json = converter.ToJson(new List<sbyte?>{127,-128,1,null,3,4}); //assert Assert.That(json, Is.EqualTo("[127,-128,1,null,3,4]")); } [Test] public void ToJson_ListSByte_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<sbyte>>(); //act string json = converter.ToJson(new List<sbyte>{127,-128,1,3,4}); //assert Assert.That(json, Is.EqualTo("[127,-128,1,3,4]")); } [Test] public void ToJson_ListNullableChar_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<char?>>(); //act string json = converter.ToJson(new List<char?>{'a','b','c',null,'d','e'}); //assert Assert.That(json, Is.EqualTo("[\"a\",\"b\",\"c\",null,\"d\",\"e\"]")); } [Test] public void ToJson_ListChar_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<char>>(); //act string json = converter.ToJson(new List<char>{'a','b','c','d','e'}); //assert Assert.That(json, Is.EqualTo("[\"a\",\"b\",\"c\",\"d\",\"e\"]")); } [Test] public void ToJson_ListNullableBool_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<bool?>>(); //act string json = converter.ToJson(new List<bool?>{true, null, false}); //assert Assert.That(json, Is.EqualTo("[true,null,false]")); } [Test] public void ToJson_ListBool_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<bool>>(); //act string json = converter.ToJson(new List<bool>{true, false}); //assert Assert.That(json, Is.EqualTo("[true,false]")); } [Test] public void ToJson_ListNullableGuid_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<Guid?>>(); //act string json = converter.ToJson(new List<Guid?>{new Guid(1,2,3,4,5,6,7,8,9,10,11), null, new Guid(2,3,4,5,6,7,8,9,10,11,12)}); //assert Assert.That(json, Is.EqualTo("[\"00000001-0002-0003-0405-060708090a0b\",null,\"00000002-0003-0004-0506-0708090a0b0c\"]")); } [Test] public void ToJson_ListGuid_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<Guid>>(); //act string json = converter.ToJson(new List<Guid>{new Guid(1,2,3,4,5,6,7,8,9,10,11), new Guid(2,3,4,5,6,7,8,9,10,11,12)}); //assert Assert.That(json, Is.EqualTo("[\"00000001-0002-0003-0405-060708090a0b\",\"00000002-0003-0004-0506-0708090a0b0c\"]")); } [Test] public void ToJson_ListNullableDateTime_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<DateTime?>>(); //act string json = converter.ToJson(new List<DateTime?>{new DateTime(2018,04,08, 1,2,3, DateTimeKind.Utc), null, new DateTime(2017,03,07, 23,59,42, DateTimeKind.Utc)}); //assert Assert.That(json, Is.EqualTo("[\"2018-04-08T01:02:03Z\",null,\"2017-03-07T23:59:42Z\"]")); } [Test] public void ToJson_ListDateTime_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<DateTime>>(); //act string json = converter.ToJson(new List<DateTime>{new DateTime(2018,04,08, 1,2,3, DateTimeKind.Utc), new DateTime(2017,03,07, 23,59,42, DateTimeKind.Utc)}); //assert Assert.That(json, Is.EqualTo("[\"2018-04-08T01:02:03Z\",\"2017-03-07T23:59:42Z\"]")); } [Test] public void ToJson_ListDecimal_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<decimal>>(); //act string json = converter.ToJson(new List<decimal>{-11.12M,2.4M,3M,4M,5.5M}); //assert Assert.That(json, Is.EqualTo("[-11.12,2.4,3,4,5.5]")); } [Test] public void ToJson_ListNullableDecimal_CorrectJson() { //arrange var converter = JsonFactory.Compile<List<decimal?>>(); //act string json = converter.ToJson(new List<decimal?>{-11.12M,2.4M,null,3M,4M,5.5M}); //assert Assert.That(json, Is.EqualTo("[-11.12,2.4,null,3,4,5.5]")); } } }
#region Using Directives using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using UnityEngine; #endregion namespace PlanetShine { [KSPAddon(KSPAddon.Startup.Instantly, false)] public class Logger : MonoBehaviour { #region Constants private static readonly string fileName; private static readonly AssemblyName assemblyName; #endregion #region Fields private static readonly List<string[]> messages = new List<string[]>(); #endregion #region Initialisation static Logger() { assemblyName = Assembly.GetExecutingAssembly().GetName(); fileName = Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, "log"); File.Delete(fileName); lock (messages) { messages.Add(new[] { "Executing: " + assemblyName.Name + " - " + assemblyName.Version }); messages.Add(new[] { "Assembly: " + Assembly.GetExecutingAssembly().Location }); } Blank(); } private void Awake() { DontDestroyOnLoad(this); } #endregion #region Printing public static void Blank() { lock (messages) { messages.Add(new string[] { }); } } public static void Log(object obj) { lock (messages) { try { if (obj is IEnumerable) { messages.Add(new[] { "Log " + DateTime.Now.TimeOfDay, obj.ToString() }); foreach (var o in obj as IEnumerable) { messages.Add(new[] { "\t", o.ToString() }); } } else { messages.Add(new[] { "Log " + DateTime.Now.TimeOfDay, obj.ToString() }); } } catch (Exception ex) { Exception(ex); } } } public static void Log(string name, object obj) { lock (messages) { try { if (obj is IEnumerable) { messages.Add(new[] { "Log " + DateTime.Now.TimeOfDay, name }); foreach (var o in obj as IEnumerable) { messages.Add(new[] { "\t", o.ToString() }); } } else { messages.Add(new[] { "Log " + DateTime.Now.TimeOfDay, obj.ToString() }); } } catch (Exception ex) { Exception(ex); } } } public static void Log(string message) { lock (messages) { messages.Add(new[] { "Log " + DateTime.Now.TimeOfDay, message }); } } [System.Diagnostics.Conditional("DEBUG")] [System.Diagnostics.DebuggerStepThrough] public static void Debug(string message) { lock (messages) { messages.Add(new[] { "Debug " + DateTime.Now.TimeOfDay, message }); } } public static void Warning(string message) { lock (messages) { messages.Add(new[] { "Warning " + DateTime.Now.TimeOfDay, message }); } } public static void Error(string message) { lock (messages) { messages.Add(new[] { "Error " + DateTime.Now.TimeOfDay, message }); } } public static void Exception(Exception ex) { lock (messages) { messages.Add(new[] { "Exception " + DateTime.Now.TimeOfDay, ex.Message }); messages.Add(new[] { string.Empty, ex.StackTrace }); Blank(); } } public static void Exception(Exception ex, string location) { lock (messages) { messages.Add(new[] { "Exception " + DateTime.Now.TimeOfDay, location + " // " + ex.Message }); messages.Add(new[] { string.Empty, ex.StackTrace }); Blank(); } } #endregion #region Flushing public static void Flush() { lock (messages) { if (messages.Count > 0) { using (var file = File.AppendText(fileName)) { foreach (var message in messages) { file.WriteLine(message.Length > 0 ? message.Length > 1 ? "[" + message[0] + "]: " + message[1] : message[0] : string.Empty); if (message.Length > 0) { print(message.Length > 1 ? assemblyName.Name + " -> " + message[1] : assemblyName.Name + " -> " + message[0]); } } } messages.Clear(); } } } private void LateUpdate() { Flush(); } #endregion #region Destruction private void OnDestroy() { Flush(); } ~Logger() { Flush(); } #endregion } }
using System; using System.Collections.Generic; using System.Text; using Data.EDM; namespace Analysis.EDM { // Note that all FWHM based gates have been disabled to remove SharedCode's dependence on the // NI analysis libraries. /// <summary> /// This is a bit confusing looking, but it's pretty simple to use. Instances of this class /// tell the BlockDemodulator how to extract the data. The class also provides a standard /// library of configurations, accessed through the static member GetStandardDemodulationConfig. /// This is usually the way you'll want to use the class, although you are of course free to build /// your own configurations on the fly. /// /// I have a nagging feeling that there might be a simpler way to do this, but I can't see it at /// the minute. /// </summary> [Serializable] public class DemodulationConfig { public Dictionary<string, GatedDetectorExtractSpec> GatedDetectorExtractSpecs = new Dictionary<string, GatedDetectorExtractSpec>(); public List<string> PointDetectorChannels = new List<string>(); public String AnalysisTag = ""; // static members for making standard configs private static Dictionary<string, DemodulationConfigBuilder> standardConfigs = new Dictionary<string, DemodulationConfigBuilder>(); private static double kDetectorDistanceRatio = 3.842; public static DemodulationConfig GetStandardDemodulationConfig(string name, Block b) { return (standardConfigs[name])(b); } static DemodulationConfig() { // here we stock the class' static library of configs up with some standard configs // a wide gate - integrate everything DemodulationConfigBuilder wide = delegate(Block b) { DemodulationConfig dc; GatedDetectorExtractSpec dg0, dg1, dg2, dg3, dg4, dg5, dg6, dg7; dc = new DemodulationConfig(); dc.AnalysisTag = "wide"; dg0 = GatedDetectorExtractSpec.MakeWideGate(0); dg0.Name = "top"; dg1 = GatedDetectorExtractSpec.MakeWideGate(1); dg1.Name = "norm"; dg2 = GatedDetectorExtractSpec.MakeWideGate(2); dg2.Name = "magnetometer"; dg2.Integrate = false; dg3 = GatedDetectorExtractSpec.MakeWideGate(3); dg3.Name = "gnd"; dg3.Integrate = false; dg4 = GatedDetectorExtractSpec.MakeWideGate(4); dg4.Name = "battery"; dg5 = GatedDetectorExtractSpec.MakeWideGate(5); dg5.Name = "rfCurrent"; dg5.Integrate = false; dg6 = GatedDetectorExtractSpec.MakeWideGate(6); dg6.Name = "reflectedrf1Amplitude"; dg7 = GatedDetectorExtractSpec.MakeWideGate(7); dg7.Name = "reflectedrf2Amplitude"; dc.GatedDetectorExtractSpecs.Add(dg0.Name, dg0); dc.GatedDetectorExtractSpecs.Add(dg1.Name, dg1); dc.GatedDetectorExtractSpecs.Add(dg2.Name, dg2); dc.GatedDetectorExtractSpecs.Add(dg3.Name, dg3); dc.GatedDetectorExtractSpecs.Add(dg4.Name, dg4); dc.GatedDetectorExtractSpecs.Add(dg5.Name, dg5); dc.GatedDetectorExtractSpecs.Add(dg6.Name, dg6); dc.GatedDetectorExtractSpecs.Add(dg7.Name, dg7); dc.PointDetectorChannels.Add("MiniFlux1"); dc.PointDetectorChannels.Add("MiniFlux2"); dc.PointDetectorChannels.Add("MiniFlux3"); dc.PointDetectorChannels.Add("NorthCurrent"); dc.PointDetectorChannels.Add("SouthCurrent"); dc.PointDetectorChannels.Add("PumpPD"); dc.PointDetectorChannels.Add("ProbePD"); return dc; }; standardConfigs.Add("wide", wide); //// fwhm of the tof pulse for top and norm, wide gates for everything else. //AddSliceConfig("fwhm", 0, 1); //// narrower than fwhm, takes only the center hwhm //AddSliceConfig("hwhm", 0, 0.5); //// only the fast half of the fwhm (NOT TRUE - 01Jul08 JH) //AddSliceConfig("fast", -0.5, 0.5); //// the slow half of the fwhm (NOT TRUE - 01Jul08 JH) //AddSliceConfig("slow", 0.5, 0.5); //// the fastest and slowest molecules, used for estimating any tof related systematic. //// these gates don't overlap with the usual centred analysis gates (fwhm and cgate11). //AddSliceConfig("vfast", -0.85, 0.5); //AddSliceConfig("vslow", 0.85, 0.5); // for testing out different centred-gate widths for (int i = 1; i < 10; i++) AddFixedSliceConfig("wgate" + i, 2190, i * 20); for (int i = 1; i < 30; i++) AddFixedSliceConfig("pgate" + i, 2090 + i*10, 10); //// testing different gate centres. "slide0" is centred at -0.7 fwhm, "slide14" //// is centred and +0.7 fwhm. //for (int i = 0; i < 15; i++) // AddSliceConfig("slide" + i, (((double)i) / 10.0) - 0.7, 1); //// now some finer slices //double d = -1.4; //for (int i = 0; i < 15; i++) //{ // AddSliceConfig("slice" + i, d, 0.2); // d += 0.2; //} //// optimised gates for spring 2009 run //AddSliceConfig("optimum1", 0.3, 1.1); //AddSliceConfig("optimum2", 0.2, 1.1); // "background" gate DemodulationConfigBuilder background = delegate(Block b) { DemodulationConfig dc; GatedDetectorExtractSpec dg0, dg1; dc = new DemodulationConfig(); dc.AnalysisTag = "background"; dg0 = GatedDetectorExtractSpec.MakeWideGate(0); dg0.GateLow = 2550; dg0.GateHigh = 2600; dg0.Name = "top"; dg1 = GatedDetectorExtractSpec.MakeWideGate(1); dg1.Name = "norm"; dg1.GateLow = 750; dg1.GateHigh = 800; dc.GatedDetectorExtractSpecs.Add(dg0.Name, dg0); dc.GatedDetectorExtractSpecs.Add(dg1.Name, dg1); return dc; }; standardConfigs.Add("background", background); // add some fixed gate slices - the first three are the 1.1 sigma centre portion and two // non-overlapping portions either side. AddFixedSliceConfig("cgate11Fixed", 2156, 90); // This is normally ("cgate11Fixed", 2156, 90) AddFixedSliceConfig("vfastFixed", 2025, 41); AddFixedSliceConfig("vslowFixed", 2286, 41); // these "nudge" gates are chosen to, hopefully, tweak the 09_10 dataset so that the // RF1F channel, DB-normed in the non-linear way, is reduced to near zero AddFixedSliceConfig("nudgeGate1", 2161, 90); AddFixedSliceConfig("nudgeGate2", 2169, 90); AddFixedSliceConfig("nudgeGate3", 2176, 90); AddFixedSliceConfig("nudgeGate4", 2174, 90); AddFixedSliceConfig("nudgeGate5", 2188, 90); AddFixedSliceConfig("nudgeGate6", 2198, 90); AddFixedSliceConfig("nudgeGate7", 2208, 90); AddFixedSliceConfig("nudgeGate8", 2228, 90); AddFixedSliceConfig("wideNudgeGate1", 2198, 100); AddFixedSliceConfig("narrowNudgeGate1", 2198, 75); AddFixedSliceConfig("narrowNudgeGate2", 2198, 65); AddFixedSliceConfig("narrowNudgeGate3", 2198, 55); AddFixedSliceConfig("narrowNudgeGate4", 2198, 45); // these two are the fast and slow halves of the 1.1 sigma central gate. AddFixedSliceConfig("fastFixed", 2110, 45); AddFixedSliceConfig("slowFixed", 2201, 45); // two fairly wide gates that take in most of the slow and fast molecules. // They've been chosed to try and capture the wiggliness of our fast-slow // wiggles. AddFixedSliceConfig("widefastFixed", 1950, 150); AddFixedSliceConfig("wideslowFixed", 2330, 150); // A narrow centre gate for correlation analysis AddFixedSliceConfig("cgateNarrowFixed", 2175, 25); // A gate containing no molecules to look for edms caused by rf pickup AddFixedSliceConfig("preMolecularBackground", 1850, 50); // A demodulation config for Kr AddFixedSliceConfig("centreFixedKr", 2950, 90); } //private static void AddSliceConfig(string name, double offset, double width) //{ // // the slow half of the fwhm // DemodulationConfigBuilder dcb = delegate(Block b) // { // DemodulationConfig dc; // GatedDetectorExtractSpec dg0, dg1, dg2, dg3, dg4; // dc = new DemodulationConfig(); // dc.AnalysisTag = name; // dg0 = GatedDetectorExtractSpec.MakeGateFWHM(b, 0, offset, width); // dg0.Name = "top"; // dg0.BackgroundSubtract = true; // dg1 = GatedDetectorExtractSpec.MakeGateFWHM(b, 1, offset, width); // dg1.Name = "norm"; // dg1.BackgroundSubtract = true; // dg2 = GatedDetectorExtractSpec.MakeWideGate(2); // dg2.Name = "mag1"; // dg2.Integrate = false; // dg3 = GatedDetectorExtractSpec.MakeWideGate(3); // dg3.Name = "short"; // dg3.Integrate = false; // dg4 = GatedDetectorExtractSpec.MakeWideGate(4); // dg4.Name = "battery"; // dc.GatedDetectorExtractSpecs.Add(dg0.Name, dg0); // dc.GatedDetectorExtractSpecs.Add(dg1.Name, dg1); // dc.GatedDetectorExtractSpecs.Add(dg2.Name, dg2); // dc.GatedDetectorExtractSpecs.Add(dg3.Name, dg3); // dc.GatedDetectorExtractSpecs.Add(dg4.Name, dg4); // dc.PointDetectorChannels.Add("MiniFlux1"); // dc.PointDetectorChannels.Add("MiniFlux2"); // dc.PointDetectorChannels.Add("MiniFlux3"); // dc.PointDetectorChannels.Add("NorthCurrent"); // dc.PointDetectorChannels.Add("SouthCurrent"); // dc.PointDetectorChannels.Add("PumpPD"); // dc.PointDetectorChannels.Add("ProbePD"); // return dc; // }; // standardConfigs.Add(name, dcb); //} private static void AddFixedSliceConfig(string name, double centre, double width) { // the slow half of the fwhm DemodulationConfigBuilder dcb = delegate(Block b) { DemodulationConfig dc; GatedDetectorExtractSpec dg0, dg1, dg2, dg3, dg4, dg5, dg6, dg7; //This dodgy bit of code is to make sure that the reflected rf power meters // only select a single point in the centre of the rf pulse. It won't work // if either of the rf pulses is centred at a time not divisible w/o rem. by 10us int rf1CT = (int)b.Config.Settings["rf1CentreTime"]; int rf2CT = (int)b.Config.Settings["rf2CentreTime"]; int clock = (int)b.Config.Settings["clockFrequency"]; int conFac = clock / 1000000; dc = new DemodulationConfig(); dc.AnalysisTag = name; dg0 = new GatedDetectorExtractSpec(); dg0.Index = 0; dg0.Name = "top"; dg0.BackgroundSubtract = false; dg0.GateLow = (int)(centre - width); dg0.GateHigh = (int)(centre + width); dg1 = new GatedDetectorExtractSpec(); dg1.Index = 1; dg1.Name = "norm"; dg1.BackgroundSubtract = false; dg1.GateLow = (int)((centre - width) / kDetectorDistanceRatio); dg1.GateHigh = (int)((centre + width) / kDetectorDistanceRatio); dg2 = GatedDetectorExtractSpec.MakeWideGate(2); dg2.Name = "magnetometer"; dg2.Integrate = false; dg3 = GatedDetectorExtractSpec.MakeWideGate(3); dg3.Name = "gnd"; dg3.Integrate = false; dg4 = GatedDetectorExtractSpec.MakeWideGate(4); dg4.Name = "battery"; dg4.Integrate = false; //Add this in to analyse By in 3 axis internal magnetometer tests dg5 = GatedDetectorExtractSpec.MakeWideGate(5); dg5.Name = "rfCurrent"; dg5.Integrate = false; dg6 = new GatedDetectorExtractSpec(); dg6.Index = 6; dg6.Name = "reflectedrf1Amplitude"; dg6.BackgroundSubtract = false; dg6.GateLow = (rf1CT / conFac) - 1; dg6.GateHigh = (rf1CT / conFac) + 1; dg7 = new GatedDetectorExtractSpec(); dg7.Index = 7 ; dg7.Name = "reflectedrf2Amplitude"; dg7.BackgroundSubtract = false; dg7.GateLow = (rf2CT / conFac) - 1; dg7.GateHigh = (rf2CT / conFac) + 1; dc.GatedDetectorExtractSpecs.Add(dg0.Name, dg0); dc.GatedDetectorExtractSpecs.Add(dg1.Name, dg1); dc.GatedDetectorExtractSpecs.Add(dg2.Name, dg2); dc.GatedDetectorExtractSpecs.Add(dg3.Name, dg3); dc.GatedDetectorExtractSpecs.Add(dg4.Name, dg4); dc.GatedDetectorExtractSpecs.Add(dg5.Name, dg5); dc.GatedDetectorExtractSpecs.Add(dg6.Name, dg6); dc.GatedDetectorExtractSpecs.Add(dg7.Name, dg7); dc.PointDetectorChannels.Add("MiniFlux1"); dc.PointDetectorChannels.Add("MiniFlux2"); dc.PointDetectorChannels.Add("MiniFlux3"); dc.PointDetectorChannels.Add("NorthCurrent"); dc.PointDetectorChannels.Add("SouthCurrent"); dc.PointDetectorChannels.Add("PumpPD"); dc.PointDetectorChannels.Add("ProbePD"); dc.PointDetectorChannels.Add("PhaseLockFrequency"); return dc; }; standardConfigs.Add(name, dcb); } } public delegate DemodulationConfig DemodulationConfigBuilder(Block b); }
// // http://code.google.com/p/servicestack/wiki/TypeSerializer // ServiceStack.Text: .NET C# POCO Type Text Serializer. // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2011 Liquidbit Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // using System; using System.Globalization; using System.IO; using ServiceStack.Text.Common; using ServiceStack.Text.Json; namespace ServiceStack.Text.Jsv { internal class JsvTypeSerializer : ITypeSerializer { public static ITypeSerializer Instance = new JsvTypeSerializer(); public string TypeAttrInObject { get { return "{__type:"; } } public WriteObjectDelegate GetWriteFn<T>() { return JsvWriter<T>.WriteFn(); } public WriteObjectDelegate GetWriteFn(Type type) { return JsvWriter.GetWriteFn(type); } static readonly TypeInfo DefaultTypeInfo = new TypeInfo { EncodeMapKey = false }; public TypeInfo GetTypeInfo(Type type) { return DefaultTypeInfo; } public void WriteRawString(TextWriter writer, string value) { writer.Write(value.ToCsvField()); } public void WritePropertyName(TextWriter writer, string value) { writer.Write(value); } public void WriteBuiltIn(TextWriter writer, object value) { writer.Write(value); } public void WriteObjectString(TextWriter writer, object value) { if (value != null) { writer.Write(value.ToString().ToCsvField()); } } public void WriteException(TextWriter writer, object value) { writer.Write(((Exception)value).Message.ToCsvField()); } public void WriteString(TextWriter writer, string value) { writer.Write(value.ToCsvField()); } public void WriteDateTime(TextWriter writer, object oDateTime) { writer.Write(DateTimeSerializer.ToShortestXsdDateTimeString((DateTime)oDateTime)); } public void WriteNullableDateTime(TextWriter writer, object dateTime) { if (dateTime == null) return; writer.Write(DateTimeSerializer.ToShortestXsdDateTimeString((DateTime)dateTime)); } public void WriteGuid(TextWriter writer, object oValue) { writer.Write(((Guid)oValue).ToString("N")); } public void WriteNullableGuid(TextWriter writer, object oValue) { if (oValue == null) return; writer.Write(((Guid)oValue).ToString("N")); } public void WriteBytes(TextWriter writer, object oByteValue) { if (oByteValue == null) return; writer.Write(Convert.ToBase64String((byte[])oByteValue)); } public void WriteChar(TextWriter writer, object charValue) { if (charValue == null) return; writer.Write((char)charValue); } public void WriteByte(TextWriter writer, object byteValue) { if (byteValue == null) return; writer.Write((byte)byteValue); } public void WriteInt16(TextWriter writer, object intValue) { if (intValue == null) return; writer.Write((short)intValue); } public void WriteUInt16(TextWriter writer, object intValue) { if (intValue == null) return; writer.Write((ushort)intValue); } public void WriteInt32(TextWriter writer, object intValue) { if (intValue == null) return; writer.Write((int)intValue); } public void WriteUInt32(TextWriter writer, object uintValue) { if (uintValue == null) return; writer.Write((uint)uintValue); } public void WriteUInt64(TextWriter writer, object ulongValue) { if (ulongValue == null) return; writer.Write((ulong)ulongValue); } public void WriteInt64(TextWriter writer, object longValue) { if (longValue == null) return; writer.Write((long)longValue); } public void WriteBool(TextWriter writer, object boolValue) { if (boolValue == null) return; writer.Write((bool)boolValue); } public void WriteFloat(TextWriter writer, object floatValue) { if (floatValue == null) return; var floatVal = (float)floatValue; if (Equals(floatVal, float.MaxValue) || Equals(floatVal, float.MinValue)) writer.Write(floatVal.ToString("r", CultureInfo.InvariantCulture)); else writer.Write(floatVal.ToString(CultureInfo.InvariantCulture)); } public void WriteDouble(TextWriter writer, object doubleValue) { if (doubleValue == null) return; var doubleVal = (double)doubleValue; if (Equals(doubleVal, double.MaxValue) || Equals(doubleVal, double.MinValue)) writer.Write(doubleVal.ToString("r", CultureInfo.InvariantCulture)); else writer.Write(doubleVal.ToString(CultureInfo.InvariantCulture)); } public void WriteDecimal(TextWriter writer, object decimalValue) { if (decimalValue == null) return; writer.Write(((decimal)decimalValue).ToString(CultureInfo.InvariantCulture)); } public void WriteEnum(TextWriter writer, object enumValue) { if (enumValue == null) return; writer.Write(enumValue.ToString()); } public void WriteEnumFlags(TextWriter writer, object enumFlagValue) { if (enumFlagValue == null) return; var intVal = (int)enumFlagValue; writer.Write(intVal); } public void WriteLinqBinary(TextWriter writer, object linqBinaryValue) { #if !MONOTOUCH && !SILVERLIGHT && !XBOX WriteRawString(writer, Convert.ToBase64String(((System.Data.Linq.Binary)linqBinaryValue).ToArray())); #endif } public object EncodeMapKey(object value) { return value; } public ParseStringDelegate GetParseFn<T>() { return JsvReader.Instance.GetParseFn<T>(); } public ParseStringDelegate GetParseFn(Type type) { return JsvReader.GetParseFn(type); } public string ParseRawString(string value) { return value; } public string ParseString(string value) { return value.FromCsvField(); } public string EatTypeValue(string value, ref int i) { return EatValue(value, ref i); } public bool EatMapStartChar(string value, ref int i) { var success = value[i] == JsWriter.MapStartChar; if (success) i++; return success; } public string EatMapKey(string value, ref int i) { var tokenStartPos = i; var valueLength = value.Length; var valueChar = value[tokenStartPos]; switch (valueChar) { case JsWriter.QuoteChar: while (++i < valueLength) { valueChar = value[i]; if (valueChar != JsWriter.QuoteChar) continue; var isLiteralQuote = i + 1 < valueLength && value[i + 1] == JsWriter.QuoteChar; i++; //skip quote if (!isLiteralQuote) break; } return value.Substring(tokenStartPos, i - tokenStartPos); //Is Type/Map, i.e. {...} case JsWriter.MapStartChar: var endsToEat = 1; var withinQuotes = false; while (++i < valueLength && endsToEat > 0) { valueChar = value[i]; if (valueChar == JsWriter.QuoteChar) withinQuotes = !withinQuotes; if (withinQuotes) continue; if (valueChar == JsWriter.MapStartChar) endsToEat++; if (valueChar == JsWriter.MapEndChar) endsToEat--; } return value.Substring(tokenStartPos, i - tokenStartPos); } while (value[++i] != JsWriter.MapKeySeperator) { } return value.Substring(tokenStartPos, i - tokenStartPos); } public bool EatMapKeySeperator(string value, ref int i) { return value[i++] == JsWriter.MapKeySeperator; } public bool EatItemSeperatorOrMapEndChar(string value, ref int i) { if (i == value.Length) return false; var success = value[i] == JsWriter.ItemSeperator || value[i] == JsWriter.MapEndChar; i++; return success; } public string EatValue(string value, ref int i) { var tokenStartPos = i; var valueLength = value.Length; if (i == valueLength) return null; var valueChar = value[i]; var withinQuotes = false; var endsToEat = 1; switch (valueChar) { //If we are at the end, return. case JsWriter.ItemSeperator: case JsWriter.MapEndChar: return null; //Is Within Quotes, i.e. "..." case JsWriter.QuoteChar: while (++i < valueLength) { valueChar = value[i]; if (valueChar != JsWriter.QuoteChar) continue; var isLiteralQuote = i + 1 < valueLength && value[i + 1] == JsWriter.QuoteChar; i++; //skip quote if (!isLiteralQuote) break; } return value.Substring(tokenStartPos, i - tokenStartPos).FromCsvField(); //Is Type/Map, i.e. {...} case JsWriter.MapStartChar: while (++i < valueLength && endsToEat > 0) { valueChar = value[i]; if (valueChar == JsWriter.QuoteChar) withinQuotes = !withinQuotes; if (withinQuotes) continue; if (valueChar == JsWriter.MapStartChar) endsToEat++; if (valueChar == JsWriter.MapEndChar) endsToEat--; } return value.Substring(tokenStartPos, i - tokenStartPos); //Is List, i.e. [...] case JsWriter.ListStartChar: while (++i < valueLength && endsToEat > 0) { valueChar = value[i]; if (valueChar == JsWriter.QuoteChar) withinQuotes = !withinQuotes; if (withinQuotes) continue; if (valueChar == JsWriter.ListStartChar) endsToEat++; if (valueChar == JsWriter.ListEndChar) endsToEat--; } return value.Substring(tokenStartPos, i - tokenStartPos); } //Is Value while (++i < valueLength) { valueChar = value[i]; if (valueChar == JsWriter.ItemSeperator || valueChar == JsWriter.MapEndChar) { break; } } return value.Substring(tokenStartPos, i - tokenStartPos); } } }
using System; using System.Collections.Generic; using System.Linq; using Nop.Core; using Nop.Core.Caching; using Nop.Core.Data; using Nop.Core.Domain.Customers; using Nop.Core.Domain.Directory; using Nop.Core.Plugins; using Nop.Services.Events; using Nop.Services.Stores; namespace Nop.Services.Directory { /// <summary> /// Currency service /// </summary> public partial class CurrencyService : ICurrencyService { #region Constants /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : currency ID /// </remarks> private const string CURRENCIES_BY_ID_KEY = "Nop.currency.id-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : show hidden records? /// </remarks> private const string CURRENCIES_ALL_KEY = "Nop.currency.all-{0}"; /// <summary> /// Key pattern to clear cache /// </summary> private const string CURRENCIES_PATTERN_KEY = "Nop.currency."; #endregion #region Fields private readonly IRepository<Currency> _currencyRepository; private readonly IStoreMappingService _storeMappingService; private readonly ICacheManager _cacheManager; private readonly CurrencySettings _currencySettings; private readonly IPluginFinder _pluginFinder; private readonly IEventPublisher _eventPublisher; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="cacheManager">Cache manager</param> /// <param name="currencyRepository">Currency repository</param> /// <param name="storeMappingService">Store mapping service</param> /// <param name="currencySettings">Currency settings</param> /// <param name="pluginFinder">Plugin finder</param> /// <param name="eventPublisher">Event published</param> public CurrencyService(ICacheManager cacheManager, IRepository<Currency> currencyRepository, IStoreMappingService storeMappingService, CurrencySettings currencySettings, IPluginFinder pluginFinder, IEventPublisher eventPublisher) { this._cacheManager = cacheManager; this._currencyRepository = currencyRepository; this._storeMappingService = storeMappingService; this._currencySettings = currencySettings; this._pluginFinder = pluginFinder; this._eventPublisher = eventPublisher; } #endregion #region Methods #region Currency /// <summary> /// Gets currency live rates /// </summary> /// <param name="exchangeRateCurrencyCode">Exchange rate currency code</param> /// <param name="customer">Load records allowed only to a specified customer; pass null to ignore ACL permissions</param> /// <returns>Exchange rates</returns> public virtual IList<ExchangeRate> GetCurrencyLiveRates(string exchangeRateCurrencyCode, Customer customer = null) { var exchangeRateProvider = LoadActiveExchangeRateProvider(customer); if (exchangeRateProvider == null) throw new Exception("Active exchange rate provider cannot be loaded"); return exchangeRateProvider.GetCurrencyLiveRates(exchangeRateCurrencyCode); } /// <summary> /// Deletes currency /// </summary> /// <param name="currency">Currency</param> public virtual void DeleteCurrency(Currency currency) { if (currency == null) throw new ArgumentNullException("currency"); _currencyRepository.Delete(currency); _cacheManager.RemoveByPattern(CURRENCIES_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(currency); } /// <summary> /// Gets a currency /// </summary> /// <param name="currencyId">Currency identifier</param> /// <returns>Currency</returns> public virtual Currency GetCurrencyById(int currencyId) { if (currencyId == 0) return null; string key = string.Format(CURRENCIES_BY_ID_KEY, currencyId); return _cacheManager.Get(key, () => _currencyRepository.GetById(currencyId)); } /// <summary> /// Gets a currency by code /// </summary> /// <param name="currencyCode">Currency code</param> /// <returns>Currency</returns> public virtual Currency GetCurrencyByCode(string currencyCode) { if (String.IsNullOrEmpty(currencyCode)) return null; return GetAllCurrencies(true).FirstOrDefault(c => c.CurrencyCode.ToLower() == currencyCode.ToLower()); } /// <summary> /// Gets all currencies /// </summary> /// <param name="showHidden">A value indicating whether to show hidden records</param> /// <param name="storeId">Load records allowed only in a specified store; pass 0 to load all records</param> /// <returns>Currencies</returns> public virtual IList<Currency> GetAllCurrencies(bool showHidden = false, int storeId = 0) { string key = string.Format(CURRENCIES_ALL_KEY, showHidden); var currencies = _cacheManager.Get(key, () => { var query = _currencyRepository.Table; if (!showHidden) query = query.Where(c => c.Published); query = query.OrderBy(c => c.DisplayOrder).ThenBy(c => c.Id); return query.ToList(); }); //store mapping if (storeId > 0) { currencies = currencies .Where(c => _storeMappingService.Authorize(c, storeId)) .ToList(); } return currencies; } /// <summary> /// Inserts a currency /// </summary> /// <param name="currency">Currency</param> public virtual void InsertCurrency(Currency currency) { if (currency == null) throw new ArgumentNullException("currency"); _currencyRepository.Insert(currency); _cacheManager.RemoveByPattern(CURRENCIES_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(currency); } /// <summary> /// Updates the currency /// </summary> /// <param name="currency">Currency</param> public virtual void UpdateCurrency(Currency currency) { if (currency == null) throw new ArgumentNullException("currency"); _currencyRepository.Update(currency); _cacheManager.RemoveByPattern(CURRENCIES_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(currency); } #endregion #region Conversions /// <summary> /// Converts currency /// </summary> /// <param name="amount">Amount</param> /// <param name="exchangeRate">Currency exchange rate</param> /// <returns>Converted value</returns> public virtual decimal ConvertCurrency(decimal amount, decimal exchangeRate) { if (amount != decimal.Zero && exchangeRate != decimal.Zero) return amount * exchangeRate; return decimal.Zero; } /// <summary> /// Converts currency /// </summary> /// <param name="amount">Amount</param> /// <param name="sourceCurrencyCode">Source currency code</param> /// <param name="targetCurrencyCode">Target currency code</param> /// <returns>Converted value</returns> public virtual decimal ConvertCurrency(decimal amount, Currency sourceCurrencyCode, Currency targetCurrencyCode) { if (sourceCurrencyCode == null) throw new ArgumentNullException("sourceCurrencyCode"); if (targetCurrencyCode == null) throw new ArgumentNullException("targetCurrencyCode"); decimal result = amount; if (sourceCurrencyCode.Id == targetCurrencyCode.Id) return result; if (result != decimal.Zero && sourceCurrencyCode.Id != targetCurrencyCode.Id) { result = ConvertToPrimaryExchangeRateCurrency(result, sourceCurrencyCode); result = ConvertFromPrimaryExchangeRateCurrency(result, targetCurrencyCode); } return result; } /// <summary> /// Converts to primary exchange rate currency /// </summary> /// <param name="amount">Amount</param> /// <param name="sourceCurrencyCode">Source currency code</param> /// <returns>Converted value</returns> public virtual decimal ConvertToPrimaryExchangeRateCurrency(decimal amount, Currency sourceCurrencyCode) { if (sourceCurrencyCode == null) throw new ArgumentNullException("sourceCurrencyCode"); var primaryExchangeRateCurrency = GetCurrencyById(_currencySettings.PrimaryExchangeRateCurrencyId); if (primaryExchangeRateCurrency == null) throw new Exception("Primary exchange rate currency cannot be loaded"); decimal result = amount; if (result != decimal.Zero && sourceCurrencyCode.Id != primaryExchangeRateCurrency.Id) { decimal exchangeRate = sourceCurrencyCode.Rate; if (exchangeRate == decimal.Zero) throw new NopException(string.Format("Exchange rate not found for currency [{0}]", sourceCurrencyCode.Name)); result = result / exchangeRate; } return result; } /// <summary> /// Converts from primary exchange rate currency /// </summary> /// <param name="amount">Amount</param> /// <param name="targetCurrencyCode">Target currency code</param> /// <returns>Converted value</returns> public virtual decimal ConvertFromPrimaryExchangeRateCurrency(decimal amount, Currency targetCurrencyCode) { if (targetCurrencyCode == null) throw new ArgumentNullException("targetCurrencyCode"); var primaryExchangeRateCurrency = GetCurrencyById(_currencySettings.PrimaryExchangeRateCurrencyId); if (primaryExchangeRateCurrency == null) throw new Exception("Primary exchange rate currency cannot be loaded"); decimal result = amount; if (result != decimal.Zero && targetCurrencyCode.Id != primaryExchangeRateCurrency.Id) { decimal exchangeRate = targetCurrencyCode.Rate; if (exchangeRate == decimal.Zero) throw new NopException(string.Format("Exchange rate not found for currency [{0}]", targetCurrencyCode.Name)); result = result * exchangeRate; } return result; } /// <summary> /// Converts to primary store currency /// </summary> /// <param name="amount">Amount</param> /// <param name="sourceCurrencyCode">Source currency code</param> /// <returns>Converted value</returns> public virtual decimal ConvertToPrimaryStoreCurrency(decimal amount, Currency sourceCurrencyCode) { if (sourceCurrencyCode == null) throw new ArgumentNullException("sourceCurrencyCode"); var primaryStoreCurrency = GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId); var result = ConvertCurrency(amount, sourceCurrencyCode, primaryStoreCurrency); return result; } /// <summary> /// Converts from primary store currency /// </summary> /// <param name="amount">Amount</param> /// <param name="targetCurrencyCode">Target currency code</param> /// <returns>Converted value</returns> public virtual decimal ConvertFromPrimaryStoreCurrency(decimal amount, Currency targetCurrencyCode) { var primaryStoreCurrency = GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId); var result = ConvertCurrency(amount, primaryStoreCurrency, targetCurrencyCode); return result; } #endregion #region Exchange rate providers /// <summary> /// Load active exchange rate provider /// </summary> /// <param name="customer">Load records allowed only to a specified customer; pass null to ignore ACL permissions</param> /// <returns>Active exchange rate provider</returns> public virtual IExchangeRateProvider LoadActiveExchangeRateProvider(Customer customer = null) { var exchangeRateProvider = LoadExchangeRateProviderBySystemName(_currencySettings.ActiveExchangeRateProviderSystemName); if (exchangeRateProvider == null || !_pluginFinder.AuthorizedForUser(exchangeRateProvider.PluginDescriptor, customer)) exchangeRateProvider = LoadAllExchangeRateProviders(customer).FirstOrDefault(); return exchangeRateProvider; } /// <summary> /// Load exchange rate provider by system name /// </summary> /// <param name="systemName">System name</param> /// <returns>Found exchange rate provider</returns> public virtual IExchangeRateProvider LoadExchangeRateProviderBySystemName(string systemName) { var descriptor = _pluginFinder.GetPluginDescriptorBySystemName<IExchangeRateProvider>(systemName); if (descriptor != null) return descriptor.Instance<IExchangeRateProvider>(); return null; } /// <summary> /// Load all exchange rate providers /// </summary> /// <param name="customer">Load records allowed only to a specified customer; pass null to ignore ACL permissions</param> /// <returns>Exchange rate providers</returns> public virtual IList<IExchangeRateProvider> LoadAllExchangeRateProviders(Customer customer = null) { var exchangeRateProviders = _pluginFinder.GetPlugins<IExchangeRateProvider>(customer: customer); return exchangeRateProviders.OrderBy(tp => tp.PluginDescriptor).ToList(); } #endregion #endregion } }
//Sourced from https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Net.Http.Formatting/FormattingUtilities.cs // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace RestBus.Client.Http { using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Runtime.Serialization; using System.Xml; using Newtonsoft.Json.Linq; using System.Net.Http; using System; using Formatting; using Internal; /// <summary> /// Provides various internal utility functions /// </summary> internal static class FormattingUtilities { // Supported date formats for input. private static readonly string[] dateFormats = new string[] { // "r", // RFC 1123, required output format but too strict for input "ddd, d MMM yyyy H:m:s 'GMT'", // RFC 1123 (r, except it allows both 1 and 01 for date and time) "ddd, d MMM yyyy H:m:s", // RFC 1123, no zone - assume GMT "d MMM yyyy H:m:s 'GMT'", // RFC 1123, no day-of-week "d MMM yyyy H:m:s", // RFC 1123, no day-of-week, no zone "ddd, d MMM yy H:m:s 'GMT'", // RFC 1123, short year "ddd, d MMM yy H:m:s", // RFC 1123, short year, no zone "d MMM yy H:m:s 'GMT'", // RFC 1123, no day-of-week, short year "d MMM yy H:m:s", // RFC 1123, no day-of-week, short year, no zone "dddd, d'-'MMM'-'yy H:m:s 'GMT'", // RFC 850 "dddd, d'-'MMM'-'yy H:m:s", // RFC 850 no zone "ddd MMM d H:m:s yyyy", // ANSI C's asctime() format "ddd, d MMM yyyy H:m:s zzz", // RFC 5322 "ddd, d MMM yyyy H:m:s", // RFC 5322 no zone "d MMM yyyy H:m:s zzz", // RFC 5322 no day-of-week "d MMM yyyy H:m:s", // RFC 5322 no day-of-week, no zone }; // Valid header token characters are within the range 0x20 < c < 0x7F excluding the following characters private const string NonTokenChars = "()<>@,;:\\\"/[]?={}"; /// <summary> /// Quality factor to indicate a perfect match. /// </summary> public const double Match = 1.0; /// <summary> /// Quality factor to indicate no match. /// </summary> public const double NoMatch = 0.0; /// <summary> /// The default max depth for our formatter is 256 /// </summary> public const int DefaultMaxDepth = 256; /// <summary> /// The default min depth for our formatter is 1 /// </summary> public const int DefaultMinDepth = 1; /// <summary> /// HTTP X-Requested-With header field name /// </summary> public const string HttpRequestedWithHeader = @"x-requested-with"; /// <summary> /// HTTP X-Requested-With header field value /// </summary> public const string HttpRequestedWithHeaderValue = @"XMLHttpRequest"; /// <summary> /// HTTP Host header field name /// </summary> public const string HttpHostHeader = "Host"; /// <summary> /// HTTP Version token /// </summary> public const string HttpVersionToken = "HTTP"; /// <summary> /// A <see cref="Type"/> representing <see cref="HttpRequestMessage"/>. /// </summary> public static readonly Type HttpRequestMessageType = typeof(HttpRequestMessage); /// <summary> /// A <see cref="Type"/> representing <see cref="HttpResponseMessage"/>. /// </summary> public static readonly Type HttpResponseMessageType = typeof(HttpResponseMessage); /// <summary> /// A <see cref="Type"/> representing <see cref="HttpContent"/>. /// </summary> public static readonly Type HttpContentType = typeof(HttpContent); /// <summary> /// A <see cref="Type"/> representing <see cref="DelegatingEnumerable{T}"/>. /// </summary> public static readonly Type DelegatingEnumerableGenericType = typeof(DelegatingEnumerable<>); /// <summary> /// A <see cref="Type"/> representing <see cref="IEnumerable{T}"/>. /// </summary> public static readonly Type EnumerableInterfaceGenericType = typeof(IEnumerable<>); /// <summary> /// A <see cref="Type"/> representing <see cref="IQueryable{T}"/>. /// </summary> public static readonly Type QueryableInterfaceGenericType = typeof(IQueryable<>); #if !NETFX_CORE // XsdDataContractExporter is not supported in portable libraries /// <summary> /// An instance of <see cref="XsdDataContractExporter"/>. /// </summary> public static readonly XsdDataContractExporter XsdDataContractExporter = new XsdDataContractExporter(); #endif /// <summary> /// Determines whether <paramref name="type"/> is a <see cref="JToken"/> type. /// </summary> /// <param name="type">The type to test.</param> /// <returns> /// <c>true</c> if <paramref name="type"/> is a <see cref="JToken"/> type; otherwise, <c>false</c>. /// </returns> public static bool IsJTokenType(Type type) { return typeof(JToken).IsAssignableFrom(type); } /// <summary> /// Creates an empty <see cref="HttpContentHeaders"/> instance. The only way is to get it from a dummy /// <see cref="HttpContent"/> instance. /// </summary> /// <returns>The created instance.</returns> public static HttpContentHeaders CreateEmptyContentHeaders() { HttpContent tempContent = null; HttpContentHeaders contentHeaders = null; try { tempContent = new StringContent(String.Empty); contentHeaders = tempContent.Headers; contentHeaders.Clear(); } finally { // We can dispose the content without touching the headers if (tempContent != null) { tempContent.Dispose(); } } return contentHeaders; } /// <summary> /// Create a default reader quotas with a default depth quota of 1K /// </summary> /// <returns></returns> public static XmlDictionaryReaderQuotas CreateDefaultReaderQuotas() { #if NETFX_CORE // MaxDepth is a DOS mitigation. We don't support MaxDepth in portable libraries because it is strictly client side. return XmlDictionaryReaderQuotas.Max; #else return new XmlDictionaryReaderQuotas() { MaxArrayLength = Int32.MaxValue, MaxBytesPerRead = Int32.MaxValue, MaxDepth = DefaultMaxDepth, MaxNameTableCharCount = Int32.MaxValue, MaxStringContentLength = Int32.MaxValue }; #endif } /// <summary> /// Remove bounding quotes on a token if present /// </summary> /// <param name="token">Token to unquote.</param> /// <returns>Unquoted token.</returns> public static string UnquoteToken(string token) { if (String.IsNullOrWhiteSpace(token)) { return token; } if (token.StartsWith("\"", StringComparison.Ordinal) && token.EndsWith("\"", StringComparison.Ordinal) && token.Length > 1) { return token.Substring(1, token.Length - 2); } return token; } public static bool ValidateHeaderToken(string token) { if (token == null) { return false; } foreach (char c in token) { if (c < 0x21 || c > 0x7E || NonTokenChars.IndexOf(c) != -1) { return false; } } return true; } public static string DateToString(DateTimeOffset dateTime) { // Format according to RFC1123; 'r' uses invariant info (DateTimeFormatInfo.InvariantInfo) return dateTime.ToUniversalTime().ToString("r", CultureInfo.InvariantCulture); } public static bool TryParseDate(string input, out DateTimeOffset result) { return DateTimeOffset.TryParseExact(input, dateFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeUniversal, out result); } /// <summary> /// Parses valid integer strings with no leading signs, whitespace or other <see cref="NumberStyles"/> /// </summary> /// <param name="value">The value to parse</param> /// <param name="result">The result</param> /// <returns>True if value was valid; false otherwise.</returns> public static bool TryParseInt32(string value, out int result) { return Int32.TryParse(value, NumberStyles.None, NumberFormatInfo.InvariantInfo, out result); } } }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using System.Linq; using Microsoft.Data.Edm.Annotations; namespace Microsoft.Data.Edm.Csdl.Internal.Serialization { internal class EdmModelSchemaSeparationSerializationVisitor : EdmModelVisitor { private bool visitCompleted = false; private Dictionary<string, EdmSchema> modelSchemas = new Dictionary<string, EdmSchema>(); private EdmSchema activeSchema; public EdmModelSchemaSeparationSerializationVisitor(IEdmModel visitedModel) : base(visitedModel) { } public IEnumerable<EdmSchema> GetSchemas() { if (!this.visitCompleted) { this.Visit(); } return this.modelSchemas.Values; } protected void Visit() { this.VisitEdmModel(); this.visitCompleted = true; } protected override void ProcessModel(IEdmModel model) { this.ProcessElement(model); this.VisitSchemaElements(model.SchemaElements); this.VisitVocabularyAnnotations(model.VocabularyAnnotations.Where(a => !a.IsInline(this.Model))); } protected override void ProcessVocabularyAnnotatable(IEdmVocabularyAnnotatable element) { this.VisitAnnotations(this.Model.DirectValueAnnotations(element)); this.VisitVocabularyAnnotations(this.Model.FindDeclaredVocabularyAnnotations(element).Where(a => a.IsInline(this.Model))); } protected override void ProcessSchemaElement(IEdmSchemaElement element) { string namespaceName = element.Namespace; // Put all of the namespaceless stuff into one schema. if (EdmUtil.IsNullOrWhiteSpaceInternal(namespaceName)) { namespaceName = string.Empty; } EdmSchema schema; if (!this.modelSchemas.TryGetValue(namespaceName, out schema)) { schema = new EdmSchema(namespaceName); this.modelSchemas.Add(namespaceName, schema); } schema.AddSchemaElement(element); this.activeSchema = schema; base.ProcessSchemaElement(element); } protected override void ProcessVocabularyAnnotation(IEdmVocabularyAnnotation annotation) { if (!annotation.IsInline(this.Model)) { var annotationSchemaNamespace = annotation.GetSchemaNamespace(this.Model) ?? this.modelSchemas.Select(s => s.Key).FirstOrDefault() ?? string.Empty; EdmSchema annotationSchema; if (!this.modelSchemas.TryGetValue(annotationSchemaNamespace, out annotationSchema)) { annotationSchema = new EdmSchema(annotationSchemaNamespace); this.modelSchemas.Add(annotationSchema.Namespace, annotationSchema); } annotationSchema.AddVocabularyAnnotation(annotation); this.activeSchema = annotationSchema; } if (annotation.Term != null) { this.CheckSchemaElementReference(annotation.Term); } base.ProcessVocabularyAnnotation(annotation); } /// <summary> /// When we see an entity container, we see if it has <see cref="CsdlConstants.SchemaNamespaceAnnotation"/>. /// If it does, then we attach it to that schema, otherwise we attached to the first existing schema. /// If there are no schemas, we create the one named "Default" and attach container to it. /// </summary> /// <param name="element">The entity container being processed.</param> protected override void ProcessEntityContainer(IEdmEntityContainer element) { var containerSchemaNamespace = element.Namespace; EdmSchema containerSchema; if (!this.modelSchemas.TryGetValue(containerSchemaNamespace, out containerSchema)) { containerSchema = new EdmSchema(containerSchemaNamespace); this.modelSchemas.Add(containerSchema.Namespace, containerSchema); } containerSchema.AddEntityContainer(element); this.activeSchema = containerSchema; base.ProcessEntityContainer(element); } protected override void ProcessComplexTypeReference(IEdmComplexTypeReference element) { this.CheckSchemaElementReference(element.ComplexDefinition()); } protected override void ProcessEntityTypeReference(IEdmEntityTypeReference element) { this.CheckSchemaElementReference(element.EntityDefinition()); } protected override void ProcessEntityReferenceTypeReference(IEdmEntityReferenceTypeReference element) { this.CheckSchemaElementReference(element.EntityType()); } protected override void ProcessEnumTypeReference(IEdmEnumTypeReference element) { this.CheckSchemaElementReference(element.EnumDefinition()); } protected override void ProcessEntityType(IEdmEntityType element) { base.ProcessEntityType(element); if (element.BaseEntityType() != null) { this.CheckSchemaElementReference(element.BaseEntityType()); } } protected override void ProcessComplexType(IEdmComplexType element) { base.ProcessComplexType(element); if (element.BaseComplexType() != null) { this.CheckSchemaElementReference(element.BaseComplexType()); } } protected override void ProcessEnumType(IEdmEnumType element) { base.ProcessEnumType(element); this.CheckSchemaElementReference(element.UnderlyingType); } protected override void ProcessNavigationProperty(IEdmNavigationProperty property) { var associationNamespace = SerializationExtensionMethods.GetAssociationNamespace(Model, property); EdmSchema associationSchema; if (!this.modelSchemas.TryGetValue(associationNamespace, out associationSchema)) { associationSchema = new EdmSchema(associationNamespace); this.modelSchemas.Add(associationSchema.Namespace, associationSchema); } associationSchema.AddAssociatedNavigationProperty(property); associationSchema.AddNamespaceUsing(property.DeclaringEntityType().Namespace); associationSchema.AddNamespaceUsing(property.Partner.DeclaringEntityType().Namespace); this.activeSchema.AddNamespaceUsing(associationNamespace); base.ProcessNavigationProperty(property); } private void CheckSchemaElementReference(IEdmSchemaElement element) { this.CheckSchemaElementReference(element.Namespace); } private void CheckSchemaElementReference(string namespaceName) { if (this.activeSchema != null) { this.activeSchema.AddNamespaceUsing(namespaceName); } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; using Orleans.Providers.Streams.Common; using Orleans.Runtime; using Orleans.Streams; namespace Orleans.Providers.Streams.Generator { /// <summary> /// Stream generator commands /// </summary> public enum StreamGeneratorCommand { /// <summary> /// Command to configure the generator /// </summary> Configure = PersistentStreamProviderCommand.AdapterFactoryCommandStartRange } /// <summary> /// Adapter factory for stream generator stream provider. /// This factory acts as the adapter and the adapter factory. It creates receivers that use configurable generator /// to generate event streams, rather than reading them from storage. /// </summary> public class GeneratorAdapterFactory : IQueueAdapterFactory, IQueueAdapter, IQueueAdapterCache, IControllable { /// <summary> /// Configuration property name for generator configuration type /// </summary> public const string GeneratorConfigTypeName = "StreamGeneratorConfigType"; private IServiceProvider serviceProvider; private GeneratorAdapterConfig adapterConfig; private IStreamGeneratorConfig generatorConfig; private IStreamQueueMapper streamQueueMapper; private IStreamFailureHandler streamFailureHandler; private ConcurrentDictionary<QueueId, Receiver> receivers; private IObjectPool<FixedSizeBuffer> bufferPool; private Logger logger; /// <summary> /// Determines whether this is a rewindable stream adapter - supports subscribing from previous point in time. /// </summary> /// <returns>True if this is a rewindable stream adapter, false otherwise.</returns> public bool IsRewindable => true; /// <summary> /// Direction of this queue adapter: Read, Write or ReadWrite. /// </summary> /// <returns>The direction in which this adapter provides data.</returns> public StreamProviderDirection Direction => StreamProviderDirection.ReadOnly; /// <summary> /// Initialize the factory /// </summary> /// <param name="providerConfig"></param> /// <param name="providerName"></param> /// <param name="log"></param> /// <param name="svcProvider"></param> public void Init(IProviderConfiguration providerConfig, string providerName, Logger log, IServiceProvider svcProvider) { logger = log; serviceProvider = svcProvider; receivers = new ConcurrentDictionary<QueueId, Receiver>(); adapterConfig = new GeneratorAdapterConfig(providerName); adapterConfig.PopulateFromProviderConfig(providerConfig); if (adapterConfig.GeneratorConfigType != null) { generatorConfig = (IStreamGeneratorConfig)(serviceProvider?.GetService(adapterConfig.GeneratorConfigType) ?? Activator.CreateInstance(adapterConfig.GeneratorConfigType)); if (generatorConfig == null) { throw new ArgumentOutOfRangeException(nameof(providerConfig), "GeneratorConfigType not valid."); } generatorConfig.PopulateFromProviderConfig(providerConfig); } // 10 meg buffer pool. 10 1 meg blocks bufferPool = new FixedSizeObjectPool<FixedSizeBuffer>(10, () => new FixedSizeBuffer(1<<20)); } /// <summary> /// Create an adapter /// </summary> /// <returns></returns> public Task<IQueueAdapter> CreateAdapter() { return Task.FromResult<IQueueAdapter>(this); } /// <summary> /// Get the cache adapter /// </summary> /// <returns></returns> public IQueueAdapterCache GetQueueAdapterCache() { return this; } /// <summary> /// Get the stream queue mapper /// </summary> /// <returns></returns> public IStreamQueueMapper GetStreamQueueMapper() { return streamQueueMapper ?? (streamQueueMapper = new HashRingBasedStreamQueueMapper(adapterConfig.TotalQueueCount, adapterConfig.StreamProviderName)); } /// <summary> /// Get the delivery failure handler /// </summary> /// <param name="queueId"></param> /// <returns></returns> public Task<IStreamFailureHandler> GetDeliveryFailureHandler(QueueId queueId) { return Task.FromResult(streamFailureHandler ?? (streamFailureHandler = new NoOpStreamDeliveryFailureHandler())); } /// <summary> /// Name of the adapter. Primarily for logging purposes /// </summary> public string Name => adapterConfig.StreamProviderName; /// <summary> /// Stores a batch of messages /// </summary> /// <typeparam name="T"></typeparam> /// <param name="streamGuid"></param> /// <param name="streamNamespace"></param> /// <param name="events"></param> /// <param name="token"></param> /// <param name="requestContext"></param> /// <returns></returns> public Task QueueMessageBatchAsync<T>(Guid streamGuid, string streamNamespace, IEnumerable<T> events, StreamSequenceToken token, Dictionary<string, object> requestContext) { return TaskDone.Done; } /// <summary> /// Creates a quere receiver for the specificed queueId /// </summary> /// <param name="queueId"></param> /// <returns></returns> public IQueueAdapterReceiver CreateReceiver(QueueId queueId) { Receiver receiver = receivers.GetOrAdd(queueId, qid => new Receiver()); SetGeneratorOnReciever(receiver); return receiver; } /// <summary> /// A function to execute a control command. /// </summary> /// <param name="command">A serial number of the command.</param> /// <param name="arg">An opaque command argument</param> public Task<object> ExecuteCommand(int command, object arg) { if (arg == null) { throw new ArgumentNullException("arg"); } generatorConfig = arg as IStreamGeneratorConfig; if (generatorConfig == null) { throw new ArgumentOutOfRangeException("arg", "Arg must by of type IStreamGeneratorConfig"); } // update generator on recievers foreach (Receiver receiver in receivers.Values) { SetGeneratorOnReciever(receiver); } return Task.FromResult<object>(true); } private class Receiver : IQueueAdapterReceiver { const int MaxDelayMs = 20; private readonly Random random = new Random((int)DateTime.UtcNow.Ticks % int.MaxValue); public IStreamGenerator QueueGenerator { private get; set; } public Task Initialize(TimeSpan timeout) { return TaskDone.Done; } public async Task<IList<IBatchContainer>> GetQueueMessagesAsync(int maxCount) { await Task.Delay(random.Next(1,MaxDelayMs)); List<IBatchContainer> batches; if (QueueGenerator == null || !QueueGenerator.TryReadEvents(DateTime.UtcNow, out batches)) { return new List<IBatchContainer>(); } return batches; } public Task MessagesDeliveredAsync(IList<IBatchContainer> messages) { return TaskDone.Done; } public Task Shutdown(TimeSpan timeout) { return TaskDone.Done; } } private void SetGeneratorOnReciever(Receiver receiver) { // if we don't have generator configuration, don't set generator if (generatorConfig == null) { return; } var generator = (IStreamGenerator)(serviceProvider?.GetService(generatorConfig.StreamGeneratorType) ?? Activator.CreateInstance(generatorConfig.StreamGeneratorType)); if (generator == null) { throw new OrleansException($"StreamGenerator type not supported: {generatorConfig.StreamGeneratorType}"); } generator.Configure(serviceProvider, generatorConfig); receiver.QueueGenerator = generator; } /// <summary> /// Create a cache for a given queue id /// </summary> /// <param name="queueId"></param> public IQueueCache CreateQueueCache(QueueId queueId) { return new GeneratorPooledCache(bufferPool, logger); } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Microsoft Public License. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Windows.Media.Capture; using Windows.Media.MediaProperties; using Windows.Storage; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace SDKTemplate { /// <summary> /// Scenario 3 keep aspect ratios the same /// </summary> public sealed partial class Scenario3_AspectRatio : Page { // Private MainPage object for status updates private MainPage rootPage = MainPage.Current; // Object to manage access to camera devices private MediaCapturePreviewer _previewer = null; // Folder in which the captures will be stored (initialized in InitializeCameraButton_Click) private StorageFolder _captureFolder = null; /// <summary> /// Initializes a new instance of the <see cref="Scenario1_PreviewSettings"/> class. /// </summary> public Scenario3_AspectRatio() { this.InitializeComponent(); _previewer = new MediaCapturePreviewer(PreviewControl, Dispatcher); } protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e) { await _previewer.CleanupCameraAsync(); } /// <summary> /// On some devices there may not be seperate streams for preview/photo/video. In this case, changing any of them /// will change all of them since they are the same stream /// </summary> private void CheckIfStreamsAreIdentical() { if (_previewer.MediaCapture.MediaCaptureSettings.VideoDeviceCharacteristic == VideoDeviceCharacteristic.AllStreamsIdentical || _previewer.MediaCapture.MediaCaptureSettings.VideoDeviceCharacteristic == VideoDeviceCharacteristic.PreviewRecordStreamsIdentical) { rootPage.NotifyUser("Warning: Preview and video streams for this device are identical, changing one will affect the other", NotifyType.ErrorMessage); } } /// <summary> /// Initializes the camera and populates the UI /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void InitializeCameraButton_Click(object sender, RoutedEventArgs e) { var button = sender as Button; // Clear any previous message. rootPage.NotifyUser("", NotifyType.StatusMessage); button.IsEnabled = false; await _previewer.InitializeCameraAsync(); button.IsEnabled = true; if (_previewer.IsPreviewing) { if (string.IsNullOrEmpty(_previewer.MediaCapture.MediaCaptureSettings.AudioDeviceId)) { rootPage.NotifyUser("No audio device available. Cannot capture.", NotifyType.ErrorMessage); } else { button.Visibility = Visibility.Collapsed; PreviewControl.Visibility = Visibility.Visible; CheckIfStreamsAreIdentical(); PopulateComboBoxes(); VideoButton.IsEnabled = true; } } var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures); // Fall back to the local app storage if the Pictures Library is not available _captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder; } /// <summary> /// Event handler for Preview settings combo box. Updates stream resolution based on the selection. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void PreviewSettings_Changed(object sender, RoutedEventArgs e) { if (_previewer.IsPreviewing) { var selectedItem = (sender as ComboBox).SelectedItem as ComboBoxItem; var encodingProperties = (selectedItem.Tag as StreamResolution).EncodingProperties; await _previewer.MediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, encodingProperties); // The preview just changed, update the video combo box MatchPreviewAspectRatio(); } } /// <summary> /// Event handler for Video settings combo box. Updates stream resolution based on the selection. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void VideoSettings_Changed(object sender, RoutedEventArgs e) { if (_previewer.IsPreviewing) { if (VideoSettings.SelectedIndex > -1) { var selectedItem = (sender as ComboBox).SelectedItem as ComboBoxItem; var encodingProperties = (selectedItem.Tag as StreamResolution).EncodingProperties; await _previewer.MediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoRecord, encodingProperties); } } } /// <summary> /// Records an MP4 video to a StorageFile /// </summary> private async void VideoButton_Click(object sender, RoutedEventArgs e) { if (_previewer.IsPreviewing) { if (!_previewer.IsRecording) { try { // Create storage file in Video Library var videoFile = await _captureFolder.CreateFileAsync("SimpleVideo.mp4", CreationCollisionOption.GenerateUniqueName); var encodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); await _previewer.MediaCapture.StartRecordToStorageFileAsync(encodingProfile, videoFile); // Reflect changes in the UI VideoButton.Content = "Stop Video"; _previewer.IsRecording = true; rootPage.NotifyUser("Recording file, saving to: " + videoFile.Path, NotifyType.StatusMessage); } catch (Exception ex) { // File I/O errors are reported as exceptions. rootPage.NotifyUser("Exception when starting video recording: " + ex.Message, NotifyType.ErrorMessage); } } else { // Reflect the changes in UI and stop recording VideoButton.Content = "Record Video"; _previewer.IsRecording = false; await _previewer.MediaCapture.StopRecordAsync(); rootPage.NotifyUser("Stopped recording!", NotifyType.StatusMessage); } } } /// <summary> /// Populates the combo boxes with preview settings and matching ratio settings for the video stream /// </summary> private void PopulateComboBoxes() { // Query all properties of the device IEnumerable<StreamResolution> allPreviewProperties = _previewer.MediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview).Select(x => new StreamResolution(x)); // Order them by resolution then frame rate allPreviewProperties = allPreviewProperties.OrderByDescending(x => x.Height * x.Width).ThenByDescending(x => x.FrameRate); // Populate the preview combo box with the entries foreach (var property in allPreviewProperties) { ComboBoxItem comboBoxItem = new ComboBoxItem(); comboBoxItem.Content = property.GetFriendlyName() + String.Format(" A. Ratio: {0}", property.AspectRatio.ToString("#.##")); comboBoxItem.Tag = property; PreviewSettings.Items.Add(comboBoxItem); } // Keep the same aspect ratio with the video stream MatchPreviewAspectRatio(); } /// <summary> /// Finds all the available video resolutions that match the aspect ratio of the preview stream /// Note: This should also be done with photos as well. This same method can be modified for photos /// by changing the MediaStreamType from VideoPreview to Photo. /// </summary> private void MatchPreviewAspectRatio() { // Query all properties of the device IEnumerable<StreamResolution> allVideoProperties = _previewer.MediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoRecord).Select(x => new StreamResolution(x)); // Query the current preview settings StreamResolution previewProperties = new StreamResolution(_previewer.MediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview)); // Get all formats that have the same-ish aspect ratio as the preview // Allow for some tolerance in the aspect ratio comparison const double ASPECT_RATIO_TOLERANCE = 0.015; var matchingFormats = allVideoProperties.Where(x => Math.Abs(x.AspectRatio - previewProperties.AspectRatio) < ASPECT_RATIO_TOLERANCE); // Order them by resolution then frame rate allVideoProperties = matchingFormats.OrderByDescending(x => x.Height * x.Width).ThenByDescending(x => x.FrameRate); // Clear out old entries and populate the video combo box with new matching entries VideoSettings.Items.Clear(); foreach (var property in allVideoProperties) { ComboBoxItem comboBoxItem = new ComboBoxItem(); comboBoxItem.Content = property.GetFriendlyName(); comboBoxItem.Tag = property; VideoSettings.Items.Add(comboBoxItem); } VideoSettings.SelectedIndex = -1; } } }
/******************************************************************************* INTEL CORPORATION PROPRIETARY INFORMATION This software is supplied under the terms of a license agreement or nondisclosure agreement with Intel Corporation and may not be copied or disclosed except in accordance with the terms of that agreement Copyright(c) 2012-2014 Intel Corporation. All Rights Reserved. *******************************************************************************/ //This Action Is Available to Unity 4.3+ Only #if (UNITY_4_2_2 || UNITY_4_2_1 || UNITY_4_2_0 || UNITY_4_1_5 || UNITY_4_1_4 || UNITY_4_1_3 || UNITY_4_1_2 || UNITY_4_1_0 || UNITY_4_0_1 || UNITY_4_0_0 || UNITY_3_5_7 || UNITY_3_5_6 || UNITY_3_5_5 || UNITY_3_5_4 || UNITY_3_5_3 || UNITY_3_5_2 || UNITY_3_5_1 || UNITY_3_5_0 || UNITY_3_4_2 || UNITY_3_4_1 || UNITY_3_4_0) #define PRE_UNITY_4_3 #endif #if !PRE_UNITY_4_3 using UnityEngine; using System.Collections; using System.Collections.Generic; using RSUnityToolkit; /// <summary> /// Activate action: Activate the game objects on trigger /// </summary> public class BlendShapeAnimationAction : BaseAction { #region Constants private const float RETURN_FROM_FAILURE_SMOOTH_FACTOR = 0.3f; private const float FAILURE_SMOOTH_FACTOR = 0.1f; private const float MIN_SMOOTH_BLEND_SHAPE = 2f; #endregion #region Public Fields [SerializeField, HideInInspector] public string[] _blendShapeNames; [SerializeField, HideInInspector] public string[] _blendShapeExpressions; #endregion #region Public Static Fields public static bool IsBlendShapeListVisible = false; #endregion #region Private Fields private SkinnedMeshRenderer _renderer = null; private bool[] _executeSmoothing; #endregion #region Public methods override public string GetActionDescription() { return "...."; } override public void SetDefaultTriggerValues(int index, Trigger trigger) { switch (index) { case 0: ((AnimationTrigger)trigger).Rules = new BaseRule[1] { AddHiddenComponent<FacialExpressionAnimationRule>() }; break; // case 1: // ((TrackTrigger)trigger).Rules = new BaseRule[1] { AddHiddenComponent<FaceTrackingRule>() }; // break; } } override public bool IsSupportCustomTriggers() { return false; } #endregion #region Protected methods override protected void SetDefaultTriggers() { // SupportedTriggers = new Trigger[2] // { // AddHiddenComponent<AnimationTrigger>(), // AddHiddenComponent<TrackTrigger>() // }; SupportedTriggers = new Trigger[1] { AddHiddenComponent<AnimationTrigger>() }; } #endregion #region Private Methods void Awake() { _renderer = gameObject.GetComponent<SkinnedMeshRenderer>(); _executeSmoothing = new bool[_blendShapeNames.Length]; } void Update() { ProcessAllTriggers(); AnimationTrigger animationTrigger = SupportedTriggers[0] as AnimationTrigger; if (animationTrigger == null) { return; } UpdateFace(animationTrigger); } private void UpdateFace(AnimationTrigger animationTrigger) { for (int i = 0; i < _blendShapeExpressions.Length; i++) { if ((_blendShapeExpressions[i].Length > 0) && (animationTrigger.Animations.ContainsKey(_blendShapeExpressions[i]))) { SetBlendShapeValue(animationTrigger.Animations[_blendShapeExpressions[i]], i, ref _executeSmoothing[i], animationTrigger.IsAnimationDataValid); } } } private void SetBlendShapeValue(float rawValue, int blendShapeIndex, ref bool executeSmoothing, bool isAnimationDataValid) { if (_renderer && blendShapeIndex >= 0) { float value = CalcBlendShapeValue(rawValue, blendShapeIndex, ref executeSmoothing, isAnimationDataValid); _renderer.SetBlendShapeWeight(blendShapeIndex, value); return; } return; } private float CalcBlendShapeValue(float rawValue, int blendShapeIndex, ref bool executeSmoothing, bool isAnimationDataValid) { float value = 0f; float currentValue = _renderer.GetBlendShapeWeight(blendShapeIndex); if (isAnimationDataValid) { if (executeSmoothing) { value = rawValue; if (Mathf.Abs(value - currentValue) > MIN_SMOOTH_BLEND_SHAPE) { value = Mathf.Lerp(currentValue, value, RETURN_FROM_FAILURE_SMOOTH_FACTOR); } else { executeSmoothing = false; } } else { value = rawValue; } } else { executeSmoothing = true; value = Mathf.Lerp(currentValue, 0, FAILURE_SMOOTH_FACTOR); } return value; } #endregion #region Menu #if UNITY_EDITOR [UnityEditor.MenuItem ("Toolkit/Add Action/Facial Animation Action")] static void AddThisAction () { AddAction<BlendShapeAnimationAction>(); } #endif #endregion } #endif
using System; using System.IO; using UnityEngine; using UnityEditor; using System.Collections.Generic; using EditorCommon; namespace BundleManager { public static class BundleBuildHelper { public static void PushAssetDependencies() { #pragma warning disable 0618 BuildPipeline.PushAssetDependencies(); #pragma warning restore 0618 } public static void PopAssetDependencies() { #pragma warning disable 0618 BuildPipeline.PopAssetDependencies(); #pragma warning restore 0618 } public static bool BuildSingleBundle(BundleData bundle, BundleState state, bool pushDepend) { if (pushDepend) PushAssetDependencies(); bool ret = BuildSingleBundle(bundle, state); if (pushDepend) PopAssetDependencies(); return ret; } public static bool BuildSingleBundle(BundleData bundle, BundleState state) { if (bundle == null) return false; string outputPath = BuildConfig.GetBuildOutputPath(bundle.name); EditorTool.CreateDirectory(outputPath); uint crc = 0; string[] assetPaths = bundle.includs.ToArray(); bool succeed = false; if (bundle.type == BundleType.UnityMap) { succeed = BuildSceneBundle(assetPaths, outputPath, out crc); } else { succeed = BuildAssetBundle(assetPaths, outputPath, out crc, bundle.type); } succeed = UpdateBundleState(bundle, state, outputPath, succeed, crc); return succeed; } public static bool BuildShaderBundle(BundleData bundle, BundleState state) { if (bundle == null || state == null) { return false; } List<UnityEngine.Object> list = new List<UnityEngine.Object>(); for (int i = 0; i < bundle.includs.Count; ++i) { string path = bundle.includs[i]; if (path.StartsWith("Assets", StringComparison.OrdinalIgnoreCase)) { UnityEngine.Object[] assetsAtPath = AssetDatabase.LoadAllAssetsAtPath(path); if (assetsAtPath != null || assetsAtPath.Length != 0) { list.AddRange(assetsAtPath); } else { Debug.LogError("Cannnot load [" + path + "] as asset object"); } } else { UnityEngine.Object obj = Shader.Find(path); if (obj == null) { Debug.LogError("Find shader " + path + " failed."); } else { list.Add(obj); } } } if (list.Count == 0) { Debug.LogError("Empty Shader Bundle " + bundle.name); return false; } uint crc = 0; string outputPath = BuildConfig.GetBuildOutputPath(bundle.name); EditorTool.CreateDirectory(outputPath); bool succeed = BuildAssetBundle(list.ToArray(), outputPath, out crc); succeed = UpdateBundleState(bundle, state, outputPath, succeed, crc); return succeed; } public static bool BuildAssetBundle(string[] assetsList, string outputPath, out uint crc, BundleType bundleType) { crc = 0; List<UnityEngine.Object> assets = new List<UnityEngine.Object>(); foreach (string assetPath in assetsList) { // Load all of assets in this bundle UnityEngine.Object[] assetsAtPath = AssetDatabase.LoadAllAssetsAtPath(assetPath); if (assetsAtPath != null || assetsAtPath.Length != 0) { List<UnityEngine.Object> filterResult = AssetFilter.FilterObjectByType(assetsAtPath, bundleType, assetPath); assets.AddRange(filterResult); } else { Debug.LogErrorFormat("Cannnot load [{0}] as asset object", assetPath); } } if (assets.Count == 0) { Debug.LogFormat("bundle name {0} empty", outputPath); return false; } // Build bundle return BuildAssetBundle(assets.ToArray(), outputPath, out crc); } private static bool BuildAssetBundle(UnityEngine.Object[] objs, string outputPath, out uint crc) { crc = 0; #pragma warning disable 0618 bool succeed = BuildPipeline.BuildAssetBundle(null, objs, outputPath, out crc, BuildConfig.CurrentBuildAssetOpts, BuildConfig.UnityBuildTarget); #pragma warning restore 0618 if (succeed) { crc = LZF.NET.CRC.CalculateDigest(outputPath); } else { Debug.LogErrorFormat("[BuildHelper] BuildAssetBundle Failed OutputPath = {0}.", outputPath); } return succeed; } private static bool BuildSceneBundle(string[] sceneList, string outputPath, out uint crc) { crc = 0; if (sceneList.Length == 0) { Debug.LogError("No scenes were provided for the scene bundle"); return false; } if (File.Exists(outputPath)) { File.Delete(outputPath); } #pragma warning disable 0618 string error = BuildPipeline.BuildStreamedSceneAssetBundle(sceneList, outputPath, BuildConfig.UnityBuildTarget, out crc, BuildConfig.CurrentBuildSceneOpts); #pragma warning restore 0618 if (!string.IsNullOrEmpty(error)) { Debug.LogErrorFormat("[BuildHelper] BuildSceneBundle error {0}.", error); } if (File.Exists(outputPath)) { crc = LZF.NET.CRC.CalculateDigest(outputPath); return true; } return false; } private static bool UpdateBundleState(BundleData bundle, BundleState state, string outputPath, bool succeed, uint crc) { if (!succeed || (crc == state.crc && state.size > 0)) { return succeed; } state.version++; if (state.version == int.MaxValue) state.version = 0; state.crc = crc; FileInfo bundleFileInfo = new FileInfo(outputPath); state.size = bundleFileInfo.Length; state.loadState = bundle.loadState; state.storePos = BundleStorePos.Building; return succeed; } } }
//---------------------------------------- // BoxMesh.cs (c) 2007 by Charles Petzold //---------------------------------------- using System; using System.Windows; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Media3D; namespace Petzold.Media3D { /// <summary> /// Generates a MeshGeometry3D object for a box centered on the origin. /// </summary> /// <remarks> /// The MeshGeometry3D object this class creates is available as the /// Geometry property. You can share the same instance of a BoxMesh /// object with multiple 3D visuals. In XAML files, the BoxMesh /// tag will probably appear in a resource section. /// </remarks> public class BoxMesh : MeshGeneratorBase { /// <summary> /// Initializes a new instance of the BoxMesh class. /// </summary> public BoxMesh() { PropertyChanged(new DependencyPropertyChangedEventArgs()); } /// <summary> /// Identifies the Width dependency property. /// </summary> /// <value> /// The width of the box in world units. /// The default is 1. /// </value> public static readonly DependencyProperty WidthProperty = DependencyProperty.Register("Width", typeof(double), typeof(BoxMesh), new PropertyMetadata(1.0, PropertyChanged)); /// <summary> /// Gets or sets the width of the box. /// </summary> public double Width { set { SetValue(WidthProperty, value); } get { return (double)GetValue(WidthProperty); } } /// <summary> /// Identifies the Height dependency property. /// </summary> /// <value> /// The height of the box in world units. /// The default is 1. /// </value> public static readonly DependencyProperty HeightProperty = DependencyProperty.Register("Height", typeof(double), typeof(BoxMesh), new PropertyMetadata(1.0, PropertyChanged)); /// <summary> /// Gets or sets the height of the box. /// </summary> public double Height { set { SetValue(HeightProperty, value); } get { return (double)GetValue(HeightProperty); } } /// <summary> /// Identifies the Depth dependency property. /// </summary> /// <value> /// The depth of the box in world units. /// The default is 1. /// </value> public static readonly DependencyProperty DepthProperty = DependencyProperty.Register("Depth", typeof(double), typeof(BoxMesh), new PropertyMetadata(1.0, PropertyChanged)); /// <summary> /// Gets or sets the depth of the box. /// </summary> public double Depth { set { SetValue(DepthProperty, value); } get { return (double)GetValue(DepthProperty); } } /// <summary> /// Identifies the Slices dependency property. /// </summary> public static readonly DependencyProperty SlicesProperty = DependencyProperty.Register("Slices", typeof(int), typeof(BoxMesh), new PropertyMetadata(1, PropertyChanged), ValidateDivisions); /// <summary> /// Gets or sets the number of divisions across the box width. /// </summary> /// <value> /// The number of divisions across the box width. /// This property must be at least 1. /// The default value is 1. /// </value> public int Slices { set { SetValue(SlicesProperty, value); } get { return (int)GetValue(SlicesProperty); } } /// <summary> /// Identifies the Stacks dependency property. /// </summary> public static readonly DependencyProperty StacksProperty = DependencyProperty.Register("Stacks", typeof(int), typeof(BoxMesh), new PropertyMetadata(1, PropertyChanged), ValidateDivisions); /// <summary> /// Gets or sets the number of divisions in the box height. /// </summary> /// <value> /// This property must be at least 1. /// The default value is 1. /// </value> public int Stacks { set { SetValue(StacksProperty, value); } get { return (int)GetValue(StacksProperty); } } /// <summary> /// Identifies the Layers dependency property. /// </summary> public static readonly DependencyProperty LayersProperty = DependencyProperty.Register("Layers", typeof(int), typeof(BoxMesh), new PropertyMetadata(1, PropertyChanged), ValidateDivisions); /// <summary> /// Gets or sets the number of divisions in the box depth. /// </summary> /// <value> /// This property must be at least 1. /// The default value is 1. /// </value> public int Layers { set { SetValue(LayersProperty, value); } get { return (int)GetValue(LayersProperty); } } // Validation callback for Slices, Stacks, Layers. static bool ValidateDivisions(object obj) { return (int)obj > 0; } /// <summary> /// /// </summary> /// <param name="args"></param> /// <param name="vertices"></param> /// <param name="normals"></param> /// <param name="indices"></param> /// <param name="textures"></param> protected override void Triangulate(DependencyPropertyChangedEventArgs args, Point3DCollection vertices, Vector3DCollection normals, Int32Collection indices, PointCollection textures) { // Clear all four collections. vertices.Clear(); normals.Clear(); indices.Clear(); textures.Clear(); double x, y, z; int indexBase = 0; // Front side. // ----------- z = Depth / 2; // Fill the vertices, normals, textures collections. for (int stack = 0; stack <= Stacks; stack++) { y = Height / 2 - stack * Height / Stacks; for (int slice = 0; slice <= Slices; slice++) { x = -Width / 2 + slice * Width / Slices; Point3D point = new Point3D(x, y, z); vertices.Add(point); normals.Add(point - new Point3D(x, y, 0)); textures.Add(new Point((double)slice / Slices, (double)stack / Stacks)); } } // Fill the indices collection. for (int stack = 0; stack < Stacks; stack++) { for (int slice = 0; slice < Slices; slice++) { indices.Add((stack + 0) * (Slices + 1) + slice); indices.Add((stack + 1) * (Slices + 1) + slice); indices.Add((stack + 0) * (Slices + 1) + slice + 1); indices.Add((stack + 0) * (Slices + 1) + slice + 1); indices.Add((stack + 1) * (Slices + 1) + slice); indices.Add((stack + 1) * (Slices + 1) + slice + 1); } } // Rear side. // ----------- indexBase = vertices.Count; z = -Depth / 2; // Fill the vertices, normals, textures collections. for (int stack = 0; stack <= Stacks; stack++) { y = Height / 2 - stack * Height / Stacks; for (int slice = 0; slice <= Slices; slice++) { x = Width / 2 - slice * Width / Slices; Point3D point = new Point3D(x, y, z); vertices.Add(point); normals.Add(point - new Point3D(x, y, 0)); textures.Add(new Point((double)slice / Slices, (double)stack / Stacks)); } } // Fill the indices collection. for (int stack = 0; stack < Stacks; stack++) { for (int slice = 0; slice < Slices; slice++) { indices.Add(indexBase + (stack + 0) * (Slices + 1) + slice); indices.Add(indexBase + (stack + 1) * (Slices + 1) + slice); indices.Add(indexBase + (stack + 0) * (Slices + 1) + slice + 1); indices.Add(indexBase + (stack + 0) * (Slices + 1) + slice + 1); indices.Add(indexBase + (stack + 1) * (Slices + 1) + slice); indices.Add(indexBase + (stack + 1) * (Slices + 1) + slice + 1); } } // Left side. // ----------- indexBase = vertices.Count; x = -Width / 2; // Fill the vertices, normals, textures collections. for (int stack = 0; stack <= Stacks; stack++) { y = Height / 2 - stack * Height / Stacks; for (int layer = 0; layer <= Layers; layer++) { z = -Depth / 2 + layer * Depth / Layers; Point3D point = new Point3D(x, y, z); vertices.Add(point); normals.Add(point - new Point3D(0, y, z)); textures.Add(new Point((double)layer / Layers, (double)stack / Stacks)); } } // Fill the indices collection. for (int stack = 0; stack < Stacks; stack++) { for (int layer = 0; layer < Layers; layer++) { indices.Add(indexBase + (stack + 0) * (Layers + 1) + layer); indices.Add(indexBase + (stack + 1) * (Layers + 1) + layer); indices.Add(indexBase + (stack + 0) * (Layers + 1) + layer + 1); indices.Add(indexBase + (stack + 0) * (Layers + 1) + layer + 1); indices.Add(indexBase + (stack + 1) * (Layers + 1) + layer); indices.Add(indexBase + (stack + 1) * (Layers + 1) + layer + 1); } } // Right side. // ----------- indexBase = vertices.Count; x = Width / 2; // Fill the vertices, normals, textures collections. for (int stack = 0; stack <= Stacks; stack++) { y = Height / 2 - stack * Height / Stacks; for (int layer = 0; layer <= Layers; layer++) { z = Depth / 2 - layer * Depth / Layers; Point3D point = new Point3D(x, y, z); vertices.Add(point); normals.Add(point - new Point3D(0, y, z)); textures.Add(new Point((double)layer / Layers, (double)stack / Stacks)); } } // Fill the indices collection. for (int stack = 0; stack < Stacks; stack++) { for (int layer = 0; layer < Layers; layer++) { indices.Add(indexBase + (stack + 0) * (Layers + 1) + layer); indices.Add(indexBase + (stack + 1) * (Layers + 1) + layer); indices.Add(indexBase + (stack + 0) * (Layers + 1) + layer + 1); indices.Add(indexBase + (stack + 0) * (Layers + 1) + layer + 1); indices.Add(indexBase + (stack + 1) * (Layers + 1) + layer); indices.Add(indexBase + (stack + 1) * (Layers + 1) + layer + 1); } } // Top side. // ----------- indexBase = vertices.Count; y = Height / 2; // Fill the vertices, normals, textures collections. for (int layer = 0; layer <= Layers; layer++) { z = -Depth / 2 + layer * Depth / Layers; for (int slice = 0; slice <= Slices; slice++) { x = -Width / 2 + slice * Width / Slices; Point3D point = new Point3D(x, y, z); vertices.Add(point); normals.Add(point - new Point3D(x, 0, z)); textures.Add(new Point((double)slice / Slices, (double)layer / Layers)); } } // Fill the indices collection. for (int layer = 0; layer < Layers; layer++) { for (int slice = 0; slice < Slices; slice++) { indices.Add(indexBase + (layer + 0) * (Slices + 1) + slice); indices.Add(indexBase + (layer + 1) * (Slices + 1) + slice); indices.Add(indexBase + (layer + 0) * (Slices + 1) + slice + 1); indices.Add(indexBase + (layer + 0) * (Slices + 1) + slice + 1); indices.Add(indexBase + (layer + 1) * (Slices + 1) + slice); indices.Add(indexBase + (layer + 1) * (Slices + 1) + slice + 1); } } // Bottom side. // ----------- indexBase = vertices.Count; y = -Height / 2; // Fill the vertices, normals, textures collections. for (int layer = 0; layer <= Layers; layer++) { z = Depth / 2 - layer * Depth / Layers; for (int slice = 0; slice <= Slices; slice++) { x = -Width / 2 + slice * Width / Slices; Point3D point = new Point3D(x, y, z); vertices.Add(point); normals.Add(point - new Point3D(x, 0, z)); textures.Add(new Point((double)slice / Slices, (double)layer / Layers)); } } // Fill the indices collection. for (int layer = 0; layer < Layers; layer++) { for (int slice = 0; slice < Slices; slice++) { indices.Add(indexBase + (layer + 0) * (Slices + 1) + slice); indices.Add(indexBase + (layer + 1) * (Slices + 1) + slice); indices.Add(indexBase + (layer + 0) * (Slices + 1) + slice + 1); indices.Add(indexBase + (layer + 0) * (Slices + 1) + slice + 1); indices.Add(indexBase + (layer + 1) * (Slices + 1) + slice); indices.Add(indexBase + (layer + 1) * (Slices + 1) + slice + 1); } } } /// <summary> /// Creates a new instance of the BoxMesh class. /// </summary> /// <returns> /// A new instance of BoxMesh. /// </returns> /// <remarks> /// Overriding this method is required when deriving /// from the Freezable class. /// </remarks> protected override Freezable CreateInstanceCore() { return new BoxMesh(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace CalcIP { public static class Minimize { public static int PerformMinimize(string[] args) { if (args.Length < 2) { Program.UsageAndExit(); } var firstIPv4SubnetMatch = Program.IPv4WithSubnetRegex.Match(args[1]); var firstIPv4CidrMatch = Program.IPv4WithCidrRegex.Match(args[1]); if (firstIPv4SubnetMatch.Success || firstIPv4CidrMatch.Success) { var subnets = new List<IPv4Network>(); IPv4Network firstNet = (firstIPv4CidrMatch.Success) ? Program.ParseIPv4CidrSpec(firstIPv4CidrMatch)?.Item2 : Program.ParseIPv4SubnetSpec(firstIPv4SubnetMatch)?.Item2; if (firstNet == null) { return 1; } subnets.Add(firstNet); for (int i = 2; i < args.Length; ++i) { var cidrMatch = Program.IPv4WithCidrRegex.Match(args[i]); if (cidrMatch.Success) { var subnet = Program.ParseIPv4CidrSpec(cidrMatch)?.Item2; if (subnet == null) { return 1; } subnets.Add(subnet); continue; } var subnetMatch = Program.IPv4WithSubnetRegex.Match(args[i]); if (subnetMatch.Success) { var subnet = Program.ParseIPv4SubnetSpec(subnetMatch)?.Item2; if (subnet == null) { return 1; } subnets.Add(subnet); continue; } Console.Error.WriteLine("Could not detect IPv4 network spec type of {0}.", args[i]); return 1; } MinimizeAndOutput(subnets, (addr, mask) => new IPv4Network(addr, mask)); return 0; } var firstIPv6SubnetMatch = Program.IPv6WithSubnetRegex.Match(args[1]); var firstIPv6CidrMatch = Program.IPv6WithCidrRegex.Match(args[1]); if (firstIPv6SubnetMatch.Success || firstIPv6CidrMatch.Success) { var subnets = new List<IPv6Network>(); IPv6Network firstNet = (firstIPv6CidrMatch.Success) ? Program.ParseIPv6CidrSpec(firstIPv6CidrMatch)?.Item2 : Program.ParseIPv6SubnetSpec(firstIPv6SubnetMatch)?.Item2; if (firstNet == null) { return 1; } subnets.Add(firstNet); for (int i = 2; i < args.Length; ++i) { var cidrMatch = Program.IPv6WithCidrRegex.Match(args[i]); if (cidrMatch.Success) { var subnet = Program.ParseIPv6CidrSpec(cidrMatch)?.Item2; if (subnet == null) { return 1; } subnets.Add(subnet); continue; } var subnetMatch = Program.IPv6WithSubnetRegex.Match(args[i]); if (subnetMatch.Success) { var subnet = Program.ParseIPv6SubnetSpec(subnetMatch)?.Item2; if (subnet == null) { return 1; } subnets.Add(subnet); continue; } Console.Error.WriteLine("Could not detect IPv6 network spec type of {0}.", args[i]); return 1; } MinimizeAndOutput(subnets, (addr, mask) => new IPv6Network(addr, mask)); return 0; } Console.Error.WriteLine("Could not detect network spec type of {0}.", args[1]); return 1; } public static List<IPNetwork<TAddress>> MinimizeSubnets<TAddress>(IEnumerable<IPNetwork<TAddress>> subnets, Func<TAddress, TAddress, IPNetwork<TAddress>> createSubnet) where TAddress : struct, IIPAddress<TAddress> { List<IPNetwork<TAddress>> sortedSubnets = subnets .OrderBy(n => n.BaseAddress) .ThenBy(n => n.SubnetMask) .ToList(); var filteredSubnets = new HashSet<IPNetwork<TAddress>>(sortedSubnets); // eliminate subsets for (int i = 0; i < sortedSubnets.Count; ++i) { for (int j = i + 1; j < sortedSubnets.Count; ++j) { if (sortedSubnets[i].IsSupersetOf(sortedSubnets[j]) && !sortedSubnets[i].Equals(sortedSubnets[j])) { // i is a subset of j filteredSubnets.Remove(sortedSubnets[j]); } } } // try joining adjacent same-size subnets bool subnetsMerged = true; while (subnetsMerged) { subnetsMerged = false; sortedSubnets = filteredSubnets .OrderBy(n => n.BaseAddress) .ThenBy(n => n.SubnetMask) .ToList(); for (int i = 0; i < sortedSubnets.Count; ++i) { for (int j = i + 1; j < sortedSubnets.Count; ++j) { if (!sortedSubnets[i].SubnetMask.Equals(sortedSubnets[j].SubnetMask)) { // not the same size continue; } var lastIPlusOne = sortedSubnets[i].LastAddressOfSubnet.Add(1); if (!lastIPlusOne.Equals(sortedSubnets[j].BaseAddress)) { // not adjacent continue; } // adjacent! // which bit do they differ in? var differBitAddress = sortedSubnets[i].BaseAddress.BitwiseXor(sortedSubnets[j].BaseAddress); // ensure it's only one bit int differencePopCount = differBitAddress.Bytes.Sum(b => CalcIPUtils.BytePopCount[b]); if (differencePopCount > 1) { // not just a single-bit difference continue; } // remove that bit from the subnet mask var newSubnetMask = sortedSubnets[i].SubnetMask.BitwiseAnd(differBitAddress.BitwiseNot()); // create the new subnet var newSubnet = createSubnet(sortedSubnets[i].BaseAddress, newSubnetMask); // quick sanity check Debug.Assert(newSubnet.IsSupersetOf(sortedSubnets[i])); Debug.Assert(newSubnet.IsSupersetOf(sortedSubnets[j])); // replace the lower subnets with the upper subnet filteredSubnets.Remove(sortedSubnets[i]); filteredSubnets.Remove(sortedSubnets[j]); filteredSubnets.Add(newSubnet); subnetsMerged = true; break; } if (subnetsMerged) { break; } } } return filteredSubnets .OrderBy(n => n.BaseAddress) .ThenBy(n => n.SubnetMask) .ToList(); } private static void MinimizeAndOutput<TAddress>(IEnumerable<IPNetwork<TAddress>> subnets, Func<TAddress, TAddress, IPNetwork<TAddress>> createSubnet) where TAddress : struct, IIPAddress<TAddress> { List<IPNetwork<TAddress>> finalSubnets = MinimizeSubnets(subnets, createSubnet); foreach (IPNetwork<TAddress> subnet in finalSubnets) { Console.WriteLine("{0}/{1}", subnet.BaseAddress, subnet.CidrPrefix?.ToString() ?? subnet.SubnetMask.ToString()); } } } }
// QuickGraph Library // // Copyright (c) 2004 Jonathan de Halleux // // 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. // // QuickGraph Library HomePage: http://www.mbunit.com // Author: Jonathan de Halleux using System; namespace QuickGraph.Tests.Algorithms.MaximumFlow { using MbUnit.Core.Framework; using MbUnit.Framework; using QuickGraph.Tests.Generators; using QuickGraph.Concepts; using QuickGraph.Algorithms; using QuickGraph.Algorithms.Search; using QuickGraph.Algorithms.MaximumFlow; using QuickGraph.Algorithms.Visitors; using QuickGraph.Collections; using QuickGraph.Collections.Filtered; using QuickGraph.Predicates; using QuickGraph.Representations; [TypeFixture(typeof(MaximumFlowAlgorithm))] [Author("Arun Bhalla", "bhalla@uiuc.edu")] public class MaximumFlowAlgorithmTest { private EdgeDoubleDictionary capacities; private EdgeEdgeDictionary reversedEdges; private AdjacencyGraph graph; private IVertex source; private IVertex sink; public EdgeDoubleDictionary Capacities { get { return capacities; } } public EdgeEdgeDictionary ReversedEdges { get { return reversedEdges; } } public AdjacencyGraph Graph { get { return graph; } } [SetUp] public void Init() { this.capacities = new EdgeDoubleDictionary(); this.reversedEdges = new EdgeEdgeDictionary(); this.graph = new AdjacencyGraph(); this.source = graph.AddVertex(); this.sink = graph.AddVertex(); BuildSimpleGraph(source, sink); } [Provider(typeof(EdmondsKarpMaximumFlowAlgorithm))] public EdmondsKarpMaximumFlowAlgorithm EdmundsKarp() { EdmondsKarpMaximumFlowAlgorithm maxFlow = new EdmondsKarpMaximumFlowAlgorithm( Graph, Capacities, ReversedEdges ); return maxFlow; } [Provider(typeof(PushRelabelMaximumFlowAlgorithm))] public PushRelabelMaximumFlowAlgorithm PushRelabel() { PushRelabelMaximumFlowAlgorithm maxFlow = new PushRelabelMaximumFlowAlgorithm( Graph, Capacities, ReversedEdges ); return maxFlow; } [Test] public void SimpleGraph(MaximumFlowAlgorithm maxFlow) { double flow = maxFlow.Compute(source, sink); Assert.AreEqual(23, flow, double.Epsilon); Assert.IsTrue(IsFlow(maxFlow)); Assert.IsTrue(IsOptimal(maxFlow)); } private void BuildSimpleGraph(IVertex source, IVertex sink) { IVertex v1, v2, v3, v4; v1 = graph.AddVertex(); v2 = graph.AddVertex(); v3 = graph.AddVertex(); v4 = graph.AddVertex(); AddLink(source, v1, 16); AddLink(source, v2, 13); AddLink(v1, v2, 10); AddLink(v2, v1, 4); AddLink(v1, v3, 12); AddLink(v2, v4, 14); AddLink(v3, v2, 9); AddLink(v4, v3, 7); AddLink(v3, sink, 20); AddLink(v4, sink, 4); } private void AddLink(IVertex u, IVertex v, double capacity) { IEdge edge, reverseEdge; edge = Graph.AddEdge(u, v); Capacities[edge] = capacity; reverseEdge = Graph.AddEdge(v, u); Capacities[reverseEdge] = 0; ReversedEdges[edge] = reverseEdge; ReversedEdges[reverseEdge] = edge; } private bool IsFlow(MaximumFlowAlgorithm maxFlow) { // check edge flow values foreach (IVertex u in maxFlow.VisitedGraph.Vertices) { foreach (IEdge a in maxFlow.VisitedGraph.OutEdges(u)) { if (maxFlow.Capacities[a] > 0) if ((maxFlow.ResidualCapacities[a] + maxFlow.ResidualCapacities[maxFlow.ReversedEdges[a]] != maxFlow.Capacities[a]) || (maxFlow.ResidualCapacities[a] < 0) || (maxFlow.ResidualCapacities[maxFlow.ReversedEdges[a]] < 0)) return false; } } // check conservation VertexDoubleDictionary inFlows = new VertexDoubleDictionary(); VertexDoubleDictionary outFlows = new VertexDoubleDictionary(); foreach (IVertex u in maxFlow.VisitedGraph.Vertices) { inFlows[u] = 0; outFlows[u] = 0; } foreach (IVertex u in maxFlow.VisitedGraph.Vertices) { foreach (IEdge e in maxFlow.VisitedGraph.OutEdges(u)) { if (maxFlow.Capacities[e] > 0) { double flow = maxFlow.Capacities[e] - maxFlow.ResidualCapacities[e]; inFlows[e.Target] += flow; outFlows[e.Source] += flow; } } } foreach (IVertex u in maxFlow.VisitedGraph.Vertices) { if (u != source && u != sink) if (inFlows[u] != outFlows[u]) return false; } return true; } private bool IsOptimal(MaximumFlowAlgorithm maxFlow) { // check if mincut is saturated... FilteredVertexListGraph residualGraph = new FilteredVertexListGraph( maxFlow.VisitedGraph, new ReversedResidualEdgePredicate(maxFlow.ResidualCapacities, maxFlow.ReversedEdges) ); BreadthFirstSearchAlgorithm bfs = new BreadthFirstSearchAlgorithm(residualGraph); VertexIntDictionary distances = new VertexIntDictionary(); DistanceRecorderVisitor vis = new DistanceRecorderVisitor(distances); bfs.RegisterDistanceRecorderHandlers(vis); bfs.Compute(sink); return distances[source] >= maxFlow.VisitedGraph.VerticesCount; } } }
// 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.Reflection; using Internal.Metadata.NativeFormat; using System.Reflection.Runtime.General; namespace Internal.TypeSystem.NativeFormat { public static class MetadataExtensions { public static bool HasCustomAttribute(this MetadataReader metadataReader, CustomAttributeHandleCollection customAttributes, string attributeNamespace, string attributeName) { foreach (var attributeHandle in customAttributes) { ConstantStringValueHandle nameHandle; string namespaceName; if (!metadataReader.GetAttributeNamespaceAndName(attributeHandle, out namespaceName, out nameHandle)) continue; if (namespaceName.Equals(attributeNamespace) && nameHandle.StringEquals(attributeName, metadataReader)) { return true; } } return false; } public static bool GetAttributeNamespaceAndName(this MetadataReader metadataReader, CustomAttributeHandle attributeHandle, out string namespaceString, out ConstantStringValueHandle nameHandle) { Handle attributeType, attributeCtor; if (!GetAttributeTypeAndConstructor(metadataReader, attributeHandle, out attributeType, out attributeCtor)) { namespaceString = null; nameHandle = default(ConstantStringValueHandle); return false; } return GetAttributeTypeNamespaceAndName(metadataReader, attributeType, out namespaceString, out nameHandle); } private static Handle GetAttributeTypeHandle(this CustomAttribute customAttribute, MetadataReader reader) { HandleType constructorHandleType = customAttribute.Constructor.HandleType; if (constructorHandleType == HandleType.QualifiedMethod) return customAttribute.Constructor.ToQualifiedMethodHandle(reader).GetQualifiedMethod(reader).EnclosingType; else if (constructorHandleType == HandleType.MemberReference) return customAttribute.Constructor.ToMemberReferenceHandle(reader).GetMemberReference(reader).Parent; else throw new BadImageFormatException(); } public static bool GetAttributeTypeAndConstructor(this MetadataReader metadataReader, CustomAttributeHandle attributeHandle, out Handle attributeType, out Handle attributeCtor) { CustomAttribute attribute = metadataReader.GetCustomAttribute(attributeHandle); attributeCtor = attribute.Constructor; attributeType = attribute.GetAttributeTypeHandle(metadataReader); return true; } public static bool GetAttributeTypeNamespaceAndName(this MetadataReader metadataReader, Handle attributeType, out string namespaceString, out ConstantStringValueHandle nameHandle) { namespaceString = null; nameHandle = default(ConstantStringValueHandle); if (attributeType.HandleType == HandleType.TypeReference) { TypeReference typeRefRow = metadataReader.GetTypeReference(attributeType.ToTypeReferenceHandle(metadataReader)); HandleType handleType = typeRefRow.ParentNamespaceOrType.HandleType; // Nested type? if (handleType == HandleType.TypeReference || handleType == HandleType.TypeDefinition) return false; nameHandle = typeRefRow.TypeName; namespaceString = metadataReader.GetNamespaceName(typeRefRow.ParentNamespaceOrType.ToNamespaceReferenceHandle(metadataReader)); return true; } else if (attributeType.HandleType == HandleType.TypeDefinition) { var def = metadataReader.GetTypeDefinition(attributeType.ToTypeDefinitionHandle(metadataReader)); // Nested type? if (IsNested(def.Flags)) return false; nameHandle = def.Name; namespaceString = metadataReader.GetNamespaceName(def.NamespaceDefinition); return true; } else { // unsupported metadata return false; } } internal static string GetNamespaceName(this MetadataReader metadataReader, NamespaceDefinitionHandle namespaceDefinitionHandle) { if (namespaceDefinitionHandle.IsNull(metadataReader)) { return null; } else { // TODO! Cache this result, or do something to make it more efficient. NamespaceDefinition namespaceDefinition = namespaceDefinitionHandle.GetNamespaceDefinition(metadataReader); string name = metadataReader.GetString(namespaceDefinition.Name) ?? ""; if (namespaceDefinition.ParentScopeOrNamespace.HandleType == HandleType.NamespaceDefinition) { string parentName = metadataReader.GetNamespaceName(namespaceDefinition.ParentScopeOrNamespace.ToNamespaceDefinitionHandle(metadataReader)); if (!string.IsNullOrEmpty(parentName)) { name = parentName + "." + name; } } return name; } } internal static string GetNamespaceName(this MetadataReader metadataReader, NamespaceReferenceHandle namespaceReferenceHandle) { if (namespaceReferenceHandle.IsNull(metadataReader)) { return null; } else { // TODO! Cache this result, or do something to make it more efficient. NamespaceReference namespaceReference = namespaceReferenceHandle.GetNamespaceReference(metadataReader); string name = metadataReader.GetString(namespaceReference.Name) ?? ""; if (namespaceReference.ParentScopeOrNamespace.HandleType == HandleType.NamespaceReference) { string parentName = metadataReader.GetNamespaceName(namespaceReference.ParentScopeOrNamespace.ToNamespaceReferenceHandle(metadataReader)); if (!string.IsNullOrEmpty(parentName)) { name = parentName + "." + name; } } return name; } } // This mask is the fastest way to check if a type is nested from its flags, // but it should not be added to the BCL enum as its semantics can be misleading. // Consider, for example, that (NestedFamANDAssem & NestedMask) == NestedFamORAssem. // Only comparison of the masked value to 0 is meaningful, which is different from // the other masks in the enum. private const TypeAttributes NestedMask = (TypeAttributes)0x00000006; private static bool IsNested(TypeAttributes flags) { return (flags & NestedMask) != 0; } public static bool IsRuntimeSpecialName(this MethodAttributes flags) { return (flags & (MethodAttributes.SpecialName | MethodAttributes.RTSpecialName)) == (MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); } public static bool IsPublic(this MethodAttributes flags) { return (flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; } /// <summary> /// Convert a metadata Handle to a integer (that can be round-tripped back into a handle) /// </summary> public static int ToInt(this Handle handle) { // This is gross, but its the only api I can find that directly returns the handle into a token // The assert is used to verify this round-trips properly int handleAsToken = handle.GetHashCode(); Debug.Assert(handleAsToken.AsHandle().Equals(handle)); return handleAsToken; } /// <summary> /// Convert a metadata MethodHandle to a integer (that can be round-tripped back into a handle) /// This differs from the above function only be parameter type. /// </summary> public static int ToInt(this MethodHandle handle) { // This is gross, but its the only api I can find that directly returns the handle into a token // The assert is used to verify this round-trips properly int handleAsToken = handle.GetHashCode(); Debug.Assert(handleAsToken.AsHandle().Equals(handle)); return handleAsToken; } public static byte[] ConvertByteCollectionToArray(this ByteCollection collection) { byte[] array = new byte[collection.Count]; int i = 0; foreach (byte b in collection) array[i++] = b; return array; } } }
// <copyright file="OtlpExporterOptionsExtensions.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Net.Http; using System.Reflection; using Grpc.Core; using OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation.ExportClient; using OpenTelemetry.Internal; #if NETSTANDARD2_1 || NET5_0_OR_GREATER using Grpc.Net.Client; #endif using MetricsOtlpCollector = Opentelemetry.Proto.Collector.Metrics.V1; using TraceOtlpCollector = Opentelemetry.Proto.Collector.Trace.V1; namespace OpenTelemetry.Exporter { internal static class OtlpExporterOptionsExtensions { #if NETSTANDARD2_1 || NET5_0_OR_GREATER public static GrpcChannel CreateChannel(this OtlpExporterOptions options) #else public static Channel CreateChannel(this OtlpExporterOptions options) #endif { if (options.Endpoint.Scheme != Uri.UriSchemeHttp && options.Endpoint.Scheme != Uri.UriSchemeHttps) { throw new NotSupportedException($"Endpoint URI scheme ({options.Endpoint.Scheme}) is not supported. Currently only \"http\" and \"https\" are supported."); } #if NETSTANDARD2_1 || NET5_0_OR_GREATER return GrpcChannel.ForAddress(options.Endpoint); #else ChannelCredentials channelCredentials; if (options.Endpoint.Scheme == Uri.UriSchemeHttps) { channelCredentials = new SslCredentials(); } else { channelCredentials = ChannelCredentials.Insecure; } return new Channel(options.Endpoint.Authority, channelCredentials); #endif } public static Metadata GetMetadataFromHeaders(this OtlpExporterOptions options) { return options.GetHeaders<Metadata>((m, k, v) => m.Add(k, v)); } public static THeaders GetHeaders<THeaders>(this OtlpExporterOptions options, Action<THeaders, string, string> addHeader) where THeaders : new() { var optionHeaders = options.Headers; var headers = new THeaders(); if (!string.IsNullOrEmpty(optionHeaders)) { Array.ForEach( optionHeaders.Split(','), (pair) => { // Specify the maximum number of substrings to return to 2 // This treats everything that follows the first `=` in the string as the value to be added for the metadata key var keyValueData = pair.Split(new char[] { '=' }, 2); if (keyValueData.Length != 2) { throw new ArgumentException("Headers provided in an invalid format."); } var key = keyValueData[0].Trim(); var value = keyValueData[1].Trim(); addHeader(headers, key, value); }); } return headers; } public static IExportClient<TraceOtlpCollector.ExportTraceServiceRequest> GetTraceExportClient(this OtlpExporterOptions options) => options.Protocol switch { OtlpExportProtocol.Grpc => new OtlpGrpcTraceExportClient(options), OtlpExportProtocol.HttpProtobuf => new OtlpHttpTraceExportClient( options, options.HttpClientFactory?.Invoke() ?? throw new InvalidOperationException("OtlpExporterOptions was missing HttpClientFactory or it returned null.")), _ => throw new NotSupportedException($"Protocol {options.Protocol} is not supported."), }; public static IExportClient<MetricsOtlpCollector.ExportMetricsServiceRequest> GetMetricsExportClient(this OtlpExporterOptions options) => options.Protocol switch { OtlpExportProtocol.Grpc => new OtlpGrpcMetricsExportClient(options), OtlpExportProtocol.HttpProtobuf => new OtlpHttpMetricsExportClient( options, options.HttpClientFactory?.Invoke() ?? throw new InvalidOperationException("OtlpExporterOptions was missing HttpClientFactory or it returned null.")), _ => throw new NotSupportedException($"Protocol {options.Protocol} is not supported."), }; public static OtlpExportProtocol? ToOtlpExportProtocol(this string protocol) => protocol.Trim() switch { "grpc" => OtlpExportProtocol.Grpc, "http/protobuf" => OtlpExportProtocol.HttpProtobuf, _ => null, }; public static void TryEnableIHttpClientFactoryIntegration(this OtlpExporterOptions options, IServiceProvider serviceProvider, string httpClientName) { if (serviceProvider != null && options.Protocol == OtlpExportProtocol.HttpProtobuf && options.HttpClientFactory == options.DefaultHttpClientFactory) { options.HttpClientFactory = () => { Type httpClientFactoryType = Type.GetType("System.Net.Http.IHttpClientFactory, Microsoft.Extensions.Http", throwOnError: false); if (httpClientFactoryType != null) { object httpClientFactory = serviceProvider.GetService(httpClientFactoryType); if (httpClientFactory != null) { MethodInfo createClientMethod = httpClientFactoryType.GetMethod( "CreateClient", BindingFlags.Public | BindingFlags.Instance, binder: null, new Type[] { typeof(string) }, modifiers: null); if (createClientMethod != null) { HttpClient client = (HttpClient)createClientMethod.Invoke(httpClientFactory, new object[] { httpClientName }); client.Timeout = TimeSpan.FromMilliseconds(options.TimeoutMilliseconds); return client; } } } return options.DefaultHttpClientFactory(); }; } } internal static void AppendExportPath(this OtlpExporterOptions options, string exportRelativePath) { // The exportRelativePath is only appended when the options.Endpoint property wasn't set by the user, // the protocol is HttpProtobuf and the OTEL_EXPORTER_OTLP_ENDPOINT environment variable // is present. If the user provides a custom value for options.Endpoint that value is taken as is. if (!options.ProgrammaticallyModifiedEndpoint) { if (options.Protocol == OtlpExportProtocol.HttpProtobuf) { if (EnvironmentVariableHelper.LoadUri(OtlpExporterOptions.EndpointEnvVarName, out Uri endpoint)) { // At this point we can conclude that endpoint was initialized from OTEL_EXPORTER_OTLP_ENDPOINT // and has to be appended by export relative path (traces/metrics). options.Endpoint = endpoint.AppendPathIfNotPresent(exportRelativePath); } } } } internal static Uri AppendPathIfNotPresent(this Uri uri, string path) { var absoluteUri = uri.AbsoluteUri; var separator = string.Empty; if (absoluteUri.EndsWith("/")) { // Endpoint already ends with 'path/' if (absoluteUri.EndsWith(string.Concat(path, "/"), StringComparison.OrdinalIgnoreCase)) { return uri; } } else { // Endpoint already ends with 'path' if (absoluteUri.EndsWith(path, StringComparison.OrdinalIgnoreCase)) { return uri; } separator = "/"; } return new Uri(string.Concat(uri.AbsoluteUri, separator, path)); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Net.NetworkInformation; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace WifiMonitor { /// <summary> /// Represents a client to the Zeroconf (Native Wifi) service. /// </summary> /// <remarks> /// This class is the entrypoint to Native Wifi management. To manage WiFi settings, create an instance /// of this class. /// </remarks> public class WlanClient { /// <summary> /// Represents a Wifi network interface. /// </summary> public class WlanInterface { private WlanClient client; private Wlan.WlanInterfaceInfo info; #region Events /// <summary> /// Represents a method that will handle <see cref="WlanNotification"/> events. /// </summary> /// <param name="notifyData">The notification data.</param> public delegate void WlanNotificationEventHandler(Wlan.WlanNotificationData notifyData); /// <summary> /// Represents a method that will handle <see cref="WlanConnectionNotification"/> events. /// </summary> /// <param name="notifyData">The notification data.</param> /// <param name="connNotifyData">The notification data.</param> public delegate void WlanConnectionNotificationEventHandler(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData); /// <summary> /// Represents a method that will handle <see cref="WlanReasonNotification"/> events. /// </summary> /// <param name="notifyData">The notification data.</param> /// <param name="reasonCode">The reason code.</param> public delegate void WlanReasonNotificationEventHandler(Wlan.WlanNotificationData notifyData, Wlan.WlanReasonCode reasonCode); /// <summary> /// Occurs when an event of any kind occurs on a WLAN interface. /// </summary> public event WlanNotificationEventHandler WlanNotification; /// <summary> /// Occurs when a WLAN interface changes connection state. /// </summary> public event WlanConnectionNotificationEventHandler WlanConnectionNotification; /// <summary> /// Occurs when a WLAN operation fails due to some reason. /// </summary> public event WlanReasonNotificationEventHandler WlanReasonNotification; #endregion #region Event queue private bool queueEvents; private AutoResetEvent eventQueueFilled = new AutoResetEvent(false); private Queue<object> eventQueue = new Queue<object>(); private struct WlanConnectionNotificationEventData { public Wlan.WlanNotificationData notifyData; public Wlan.WlanConnectionNotificationData connNotifyData; } private struct WlanReasonNotificationData { public Wlan.WlanNotificationData notifyData; public Wlan.WlanReasonCode reasonCode; } #endregion internal WlanInterface(WlanClient client, Wlan.WlanInterfaceInfo info) { this.client = client; this.info = info; } /// <summary> /// Sets a parameter of the interface whose data type is <see cref="int"/>. /// </summary> /// <param name="opCode">The opcode of the parameter.</param> /// <param name="value">The value to set.</param> private void SetInterfaceInt(Wlan.WlanIntfOpcode opCode, int value) { IntPtr valuePtr = Marshal.AllocHGlobal(sizeof(int)); Marshal.WriteInt32(valuePtr, value); try { Wlan.ThrowIfError( Wlan.WlanSetInterface(client.clientHandle, info.interfaceGuid, opCode, sizeof(int), valuePtr, IntPtr.Zero)); } finally { Marshal.FreeHGlobal(valuePtr); } } /// <summary> /// Gets a parameter of the interface whose data type is <see cref="int"/>. /// </summary> /// <param name="opCode">The opcode of the parameter.</param> /// <returns>The integer value.</returns> private int GetInterfaceInt(Wlan.WlanIntfOpcode opCode) { IntPtr valuePtr; int valueSize; Wlan.WlanOpcodeValueType opcodeValueType; Wlan.ThrowIfError( Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, opCode, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType)); try { return Marshal.ReadInt32(valuePtr); } finally { Wlan.WlanFreeMemory(valuePtr); } } /// <summary> /// Gets or sets a value indicating whether this <see cref="WlanInterface"/> is automatically configured. /// </summary> /// <value><c>true</c> if "autoconf" is enabled; otherwise, <c>false</c>.</value> public bool Autoconf { get { return GetInterfaceInt(Wlan.WlanIntfOpcode.AutoconfEnabled) != 0; } set { SetInterfaceInt(Wlan.WlanIntfOpcode.AutoconfEnabled, value ? 1 : 0); } } /// <summary> /// Gets or sets the BSS type for the indicated interface. /// </summary> /// <value>The type of the BSS.</value> public Wlan.Dot11BssType BssType { get { return (Wlan.Dot11BssType) GetInterfaceInt(Wlan.WlanIntfOpcode.BssType); } set { SetInterfaceInt(Wlan.WlanIntfOpcode.BssType, (int)value); } } /// <summary> /// Gets the state of the interface. /// </summary> /// <value>The state of the interface.</value> public Wlan.WlanInterfaceState InterfaceState { get { return (Wlan.WlanInterfaceState)GetInterfaceInt(Wlan.WlanIntfOpcode.InterfaceState); } } /// <summary> /// Gets the channel. /// </summary> /// <value>The channel.</value> /// <remarks>Not supported on Windows XP SP2.</remarks> public int Channel { get { return GetInterfaceInt(Wlan.WlanIntfOpcode.ChannelNumber); } } /// <summary> /// Gets the RSSI. /// </summary> /// <value>The RSSI.</value> /// <remarks>Not supported on Windows XP SP2.</remarks> public int RSSI { get { return GetInterfaceInt(Wlan.WlanIntfOpcode.RSSI); } } /// <summary> /// Gets the current operation mode. /// </summary> /// <value>The current operation mode.</value> /// <remarks>Not supported on Windows XP SP2.</remarks> public Wlan.Dot11OperationMode CurrentOperationMode { get { return (Wlan.Dot11OperationMode) GetInterfaceInt(Wlan.WlanIntfOpcode.CurrentOperationMode); } } /// <summary> /// Gets the attributes of the current connection. /// </summary> /// <value>The current connection attributes.</value> /// <exception cref="Win32Exception">An exception with code 0x0000139F (The group or resource is not in the correct state to perform the requested operation.) will be thrown if the interface is not connected to a network.</exception> public Wlan.WlanConnectionAttributes CurrentConnection { get { int valueSize; IntPtr valuePtr; Wlan.WlanOpcodeValueType opcodeValueType; Wlan.ThrowIfError( Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, Wlan.WlanIntfOpcode.CurrentConnection, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType)); try { return (Wlan.WlanConnectionAttributes)Marshal.PtrToStructure(valuePtr, typeof(Wlan.WlanConnectionAttributes)); } finally { Wlan.WlanFreeMemory(valuePtr); } } } /// <summary> /// Requests a scan for available networks. /// </summary> /// <remarks> /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event. /// </remarks> public void Scan() { Wlan.ThrowIfError( Wlan.WlanScan(client.clientHandle, info.interfaceGuid, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero)); } /// <summary> /// Converts a pointer to a available networks list (header + entries) to an array of available network entries. /// </summary> /// <param name="bssListPtr">A pointer to an available networks list's header.</param> /// <returns>An array of available network entries.</returns> private Wlan.WlanAvailableNetwork[] ConvertAvailableNetworkListPtr(IntPtr availNetListPtr) { Wlan.WlanAvailableNetworkListHeader availNetListHeader = (Wlan.WlanAvailableNetworkListHeader)Marshal.PtrToStructure(availNetListPtr, typeof(Wlan.WlanAvailableNetworkListHeader)); long availNetListIt = availNetListPtr.ToInt64() + Marshal.SizeOf(typeof(Wlan.WlanAvailableNetworkListHeader)); Wlan.WlanAvailableNetwork[] availNets = new Wlan.WlanAvailableNetwork[availNetListHeader.numberOfItems]; for (int i = 0; i < availNetListHeader.numberOfItems; ++i) { availNets[i] = (Wlan.WlanAvailableNetwork)Marshal.PtrToStructure(new IntPtr(availNetListIt), typeof(Wlan.WlanAvailableNetwork)); availNetListIt += Marshal.SizeOf(typeof(Wlan.WlanAvailableNetwork)); } return availNets; } /// <summary> /// Retrieves the list of available networks. /// </summary> /// <param name="flags">Controls the type of networks returned.</param> /// <returns>A list of the available networks.</returns> public Wlan.WlanAvailableNetwork[] GetAvailableNetworkList(Wlan.WlanGetAvailableNetworkFlags flags) { IntPtr availNetListPtr; Wlan.ThrowIfError( Wlan.WlanGetAvailableNetworkList(client.clientHandle, info.interfaceGuid, flags, IntPtr.Zero, out availNetListPtr)); try { return ConvertAvailableNetworkListPtr(availNetListPtr); } finally { Wlan.WlanFreeMemory(availNetListPtr); } } /// <summary> /// Converts a pointer to a BSS list (header + entries) to an array of BSS entries. /// </summary> /// <param name="bssListPtr">A pointer to a BSS list's header.</param> /// <returns>An array of BSS entries.</returns> private Wlan.WlanBssEntry[] ConvertBssListPtr(IntPtr bssListPtr) { Wlan.WlanBssListHeader bssListHeader = (Wlan.WlanBssListHeader)Marshal.PtrToStructure(bssListPtr, typeof(Wlan.WlanBssListHeader)); long bssListIt = bssListPtr.ToInt64() + Marshal.SizeOf(typeof(Wlan.WlanBssListHeader)); Wlan.WlanBssEntry[] bssEntries = new Wlan.WlanBssEntry[bssListHeader.numberOfItems]; for (int i=0; i<bssListHeader.numberOfItems; ++i) { bssEntries[i] = (Wlan.WlanBssEntry)Marshal.PtrToStructure(new IntPtr(bssListIt), typeof(Wlan.WlanBssEntry)); bssListIt += Marshal.SizeOf(typeof(Wlan.WlanBssEntry)); } return bssEntries; } /// <summary> /// Retrieves the basic service sets (BSS) list of all available networks. /// </summary> public Wlan.WlanBssEntry[] GetNetworkBssList() { IntPtr bssListPtr; Wlan.ThrowIfError( Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, Wlan.Dot11BssType.Any, false, IntPtr.Zero, out bssListPtr)); try { return ConvertBssListPtr(bssListPtr); } finally { Wlan.WlanFreeMemory(bssListPtr); } } /// <summary> /// Retrieves the basic service sets (BSS) list of the specified network. /// </summary> /// <param name="ssid">Specifies the SSID of the network from which the BSS list is requested.</param> /// <param name="bssType">Indicates the BSS type of the network.</param> /// <param name="securityEnabled">Indicates whether security is enabled on the network.</param> public Wlan.WlanBssEntry[] GetNetworkBssList(Wlan.Dot11Ssid ssid, Wlan.Dot11BssType bssType, bool securityEnabled) { IntPtr ssidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid)); Marshal.StructureToPtr(ssid, ssidPtr, false); try { IntPtr bssListPtr; Wlan.ThrowIfError( Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, ssidPtr, bssType, securityEnabled, IntPtr.Zero, out bssListPtr)); try { return ConvertBssListPtr(bssListPtr); } finally { Wlan.WlanFreeMemory(bssListPtr); } } finally { Marshal.FreeHGlobal(ssidPtr); } } /// <summary> /// Connects to a network defined by a connection parameters structure. /// </summary> /// <param name="connectionParams">The connection paramters.</param> protected void Connect(Wlan.WlanConnectionParameters connectionParams) { Wlan.ThrowIfError( Wlan.WlanConnect(client.clientHandle, info.interfaceGuid, ref connectionParams, IntPtr.Zero)); } /// <summary> /// Requests a connection (association) to the specified wireless network. /// </summary> /// <remarks> /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event. /// </remarks> public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile) { Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters(); connectionParams.wlanConnectionMode = connectionMode; connectionParams.profile = profile; connectionParams.dot11BssType = bssType; connectionParams.flags = 0; Connect(connectionParams); } /// <summary> /// Connects (associates) to the specified wireless network, returning either on a success to connect /// or a failure. /// </summary> /// <param name="connectionMode"></param> /// <param name="bssType"></param> /// <param name="profile"></param> /// <param name="connectTimeout"></param> /// <returns></returns> public bool ConnectSynchronously(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile, int connectTimeout) { queueEvents = true; try { Connect(connectionMode, bssType, profile); while (queueEvents && eventQueueFilled.WaitOne(connectTimeout, true)) { lock (eventQueue) { while (eventQueue.Count != 0) { object e = eventQueue.Dequeue(); if (e is WlanConnectionNotificationEventData) { WlanConnectionNotificationEventData wlanConnectionData = (WlanConnectionNotificationEventData)e; // Check if the conditions are good to indicate either success or failure. if (wlanConnectionData.notifyData.notificationSource == Wlan.WlanNotificationSource.ACM) { switch ((Wlan.WlanNotificationCodeAcm)wlanConnectionData.notifyData.notificationCode) { case Wlan.WlanNotificationCodeAcm.ConnectionComplete: if (wlanConnectionData.connNotifyData.profileName == profile) return true; break; } } break; } } } } } finally { queueEvents = false; eventQueue.Clear(); } return false; // timeout expired and no "connection complete" } /// <summary> /// Connects to the specified wireless network. /// </summary> /// <remarks> /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event. /// </remarks> public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, Wlan.Dot11Ssid ssid, Wlan.WlanConnectionFlags flags) { Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters(); connectionParams.wlanConnectionMode = connectionMode; connectionParams.dot11SsidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid)); Marshal.StructureToPtr(ssid, connectionParams.dot11SsidPtr, false); connectionParams.dot11BssType = bssType; connectionParams.flags = flags; Connect(connectionParams); Marshal.DestroyStructure(connectionParams.dot11SsidPtr, ssid.GetType()); Marshal.FreeHGlobal(connectionParams.dot11SsidPtr); } /// <summary> /// Deletes a profile. /// </summary> /// <param name="profileName"> /// The name of the profile to be deleted. Profile names are case-sensitive. /// On Windows XP SP2, the supplied name must match the profile name derived automatically from the SSID of the network. For an infrastructure network profile, the SSID must be supplied for the profile name. For an ad hoc network profile, the supplied name must be the SSID of the ad hoc network followed by <c>-adhoc</c>. /// </param> public void DeleteProfile(string profileName) { Wlan.ThrowIfError( Wlan.WlanDeleteProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero)); } /// <summary> /// Sets the profile. /// </summary> /// <param name="flags">The flags to set on the profile.</param> /// <param name="profileXml">The XML representation of the profile. On Windows XP SP 2, special care should be taken to adhere to its limitations.</param> /// <param name="overwrite">If a profile by the given name already exists, then specifies whether to overwrite it (if <c>true</c>) or return an error (if <c>false</c>).</param> /// <returns>The resulting code indicating a success or the reason why the profile wasn't valid.</returns> public Wlan.WlanReasonCode SetProfile(Wlan.WlanProfileFlags flags, string profileXml, bool overwrite) { Wlan.WlanReasonCode reasonCode; Wlan.ThrowIfError( Wlan.WlanSetProfile(client.clientHandle, info.interfaceGuid, flags, profileXml, null, overwrite, IntPtr.Zero, out reasonCode)); return reasonCode; } /// <summary> /// Gets the profile's XML specification. /// </summary> /// <param name="profileName">The name of the profile.</param> /// <returns>The XML document.</returns> public string GetProfileXml(string profileName) { IntPtr profileXmlPtr; Wlan.WlanProfileFlags flags; Wlan.WlanAccess access; Wlan.ThrowIfError( Wlan.WlanGetProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero, out profileXmlPtr, out flags, out access)); try { return Marshal.PtrToStringUni(profileXmlPtr); } finally { Wlan.WlanFreeMemory(profileXmlPtr); } } /// <summary> /// Gets the information of all profiles on this interface. /// </summary> /// <returns>The profiles information.</returns> public Wlan.WlanProfileInfo[] GetProfiles() { IntPtr profileListPtr; Wlan.ThrowIfError( Wlan.WlanGetProfileList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, out profileListPtr)); try { Wlan.WlanProfileInfoListHeader header = (Wlan.WlanProfileInfoListHeader) Marshal.PtrToStructure(profileListPtr, typeof(Wlan.WlanProfileInfoListHeader)); Wlan.WlanProfileInfo[] profileInfos = new Wlan.WlanProfileInfo[header.numberOfItems]; long profileListIterator = profileListPtr.ToInt64() + Marshal.SizeOf(header); for (int i=0; i<header.numberOfItems; ++i) { Wlan.WlanProfileInfo profileInfo = (Wlan.WlanProfileInfo) Marshal.PtrToStructure(new IntPtr(profileListIterator), typeof(Wlan.WlanProfileInfo)); profileInfos[i] = profileInfo; profileListIterator += Marshal.SizeOf(profileInfo); } return profileInfos; } finally { Wlan.WlanFreeMemory(profileListPtr); } } internal void OnWlanConnection(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData) { if (WlanConnectionNotification != null) WlanConnectionNotification(notifyData, connNotifyData); if (queueEvents) { WlanConnectionNotificationEventData queuedEvent = new WlanConnectionNotificationEventData(); queuedEvent.notifyData = notifyData; queuedEvent.connNotifyData = connNotifyData; EnqueueEvent(queuedEvent); } } internal void OnWlanReason(Wlan.WlanNotificationData notifyData, Wlan.WlanReasonCode reasonCode) { if (WlanReasonNotification != null) WlanReasonNotification(notifyData, reasonCode); if (queueEvents) { WlanReasonNotificationData queuedEvent = new WlanReasonNotificationData(); queuedEvent.notifyData = notifyData; queuedEvent.reasonCode = reasonCode; EnqueueEvent(queuedEvent); } } internal void OnWlanNotification(Wlan.WlanNotificationData notifyData) { if (WlanNotification != null) WlanNotification(notifyData); } /// <summary> /// Enqueues a notification event to be processed serially. /// </summary> private void EnqueueEvent(object queuedEvent) { lock (eventQueue) eventQueue.Enqueue(queuedEvent); eventQueueFilled.Set(); } /// <summary> /// Gets the network interface of this wireless interface. /// </summary> /// <remarks> /// The network interface allows querying of generic network properties such as the interface's IP address. /// </remarks> public NetworkInterface NetworkInterface { get { // Do not cache the NetworkInterface; We need it fresh // each time cause otherwise it caches the IP information. foreach (NetworkInterface netIface in NetworkInterface.GetAllNetworkInterfaces()) { Guid netIfaceGuid = new Guid(netIface.Id); if (netIfaceGuid.Equals(info.interfaceGuid)) { return netIface; } } return null; } } /// <summary> /// The GUID of the interface (same content as the <see cref="System.Net.NetworkInformation.NetworkInterface.Id"/> value). /// </summary> public Guid InterfaceGuid { get { return info.interfaceGuid; } } /// <summary> /// The description of the interface. /// This is a user-immutable string containing the vendor and model name of the adapter. /// </summary> public string InterfaceDescription { get { return info.interfaceDescription; } } /// <summary> /// The friendly name given to the interface by the user (e.g. "Local Area Network Connection"). /// </summary> public string InterfaceName { get { return NetworkInterface.Name; } } } private IntPtr clientHandle; private uint negotiatedVersion; private Wlan.WlanNotificationCallbackDelegate wlanNotificationCallback; private Dictionary<Guid,WlanInterface> ifaces = new Dictionary<Guid,WlanInterface>(); /// <summary> /// Creates a new instance of a Native Wifi service client. /// </summary> public WlanClient() { Wlan.ThrowIfError( Wlan.WlanOpenHandle(Wlan.WLAN_CLIENT_VERSION_XP_SP2, IntPtr.Zero, out negotiatedVersion, out clientHandle)); try { Wlan.WlanNotificationSource prevSrc; wlanNotificationCallback = new Wlan.WlanNotificationCallbackDelegate(OnWlanNotification); Wlan.ThrowIfError( Wlan.WlanRegisterNotification(clientHandle, Wlan.WlanNotificationSource.All, false, wlanNotificationCallback, IntPtr.Zero, IntPtr.Zero, out prevSrc)); } catch { Wlan.WlanCloseHandle(clientHandle, IntPtr.Zero); throw; } } ~WlanClient() { Wlan.WlanCloseHandle(clientHandle, IntPtr.Zero); } private Wlan.WlanConnectionNotificationData? ParseWlanConnectionNotification(ref Wlan.WlanNotificationData notifyData) { int expectedSize = Marshal.SizeOf(typeof(Wlan.WlanConnectionNotificationData)); if (notifyData.dataSize < expectedSize) return null; Wlan.WlanConnectionNotificationData connNotifyData = (Wlan.WlanConnectionNotificationData) Marshal.PtrToStructure(notifyData.dataPtr, typeof(Wlan.WlanConnectionNotificationData)); if (connNotifyData.wlanReasonCode == Wlan.WlanReasonCode.Success) { IntPtr profileXmlPtr = new IntPtr( notifyData.dataPtr.ToInt64() + Marshal.OffsetOf(typeof(Wlan.WlanConnectionNotificationData), "profileXml").ToInt64()); connNotifyData.profileXml = Marshal.PtrToStringUni(profileXmlPtr); } return connNotifyData; } private void OnWlanNotification(ref Wlan.WlanNotificationData notifyData, IntPtr context) { WlanInterface wlanIface = ifaces.ContainsKey(notifyData.interfaceGuid) ? ifaces[notifyData.interfaceGuid] : null; switch(notifyData.notificationSource) { case Wlan.WlanNotificationSource.ACM: switch((Wlan.WlanNotificationCodeAcm)notifyData.notificationCode) { case Wlan.WlanNotificationCodeAcm.ConnectionStart: case Wlan.WlanNotificationCodeAcm.ConnectionComplete: case Wlan.WlanNotificationCodeAcm.ConnectionAttemptFail: case Wlan.WlanNotificationCodeAcm.Disconnecting: case Wlan.WlanNotificationCodeAcm.Disconnected: Wlan.WlanConnectionNotificationData? connNotifyData = ParseWlanConnectionNotification(ref notifyData); if (connNotifyData.HasValue) if (wlanIface != null) wlanIface.OnWlanConnection(notifyData, connNotifyData.Value); break; case Wlan.WlanNotificationCodeAcm.ScanFail: { int expectedSize = Marshal.SizeOf(typeof (Wlan.WlanReasonCode)); if (notifyData.dataSize >= expectedSize) { Wlan.WlanReasonCode reasonCode = (Wlan.WlanReasonCode) Marshal.ReadInt32(notifyData.dataPtr); if (wlanIface != null) wlanIface.OnWlanReason(notifyData, reasonCode); } } break; } break; case Wlan.WlanNotificationSource.MSM: switch((Wlan.WlanNotificationCodeMsm)notifyData.notificationCode) { case Wlan.WlanNotificationCodeMsm.Associating: case Wlan.WlanNotificationCodeMsm.Associated: case Wlan.WlanNotificationCodeMsm.Authenticating: case Wlan.WlanNotificationCodeMsm.Connected: case Wlan.WlanNotificationCodeMsm.RoamingStart: case Wlan.WlanNotificationCodeMsm.RoamingEnd: case Wlan.WlanNotificationCodeMsm.Disassociating: case Wlan.WlanNotificationCodeMsm.Disconnected: case Wlan.WlanNotificationCodeMsm.PeerJoin: case Wlan.WlanNotificationCodeMsm.PeerLeave: case Wlan.WlanNotificationCodeMsm.AdapterRemoval: Wlan.WlanConnectionNotificationData? connNotifyData = ParseWlanConnectionNotification(ref notifyData); if (connNotifyData.HasValue) if (wlanIface != null) wlanIface.OnWlanConnection(notifyData, connNotifyData.Value); break; } break; } if (wlanIface != null) wlanIface.OnWlanNotification(notifyData); } /// <summary> /// Gets the WLAN interfaces. /// </summary> /// <value>The WLAN interfaces.</value> public WlanInterface[] Interfaces { get { IntPtr ifaceList; Wlan.ThrowIfError( Wlan.WlanEnumInterfaces(clientHandle, IntPtr.Zero, out ifaceList)); try { Wlan.WlanInterfaceInfoListHeader header = (Wlan.WlanInterfaceInfoListHeader) Marshal.PtrToStructure(ifaceList, typeof (Wlan.WlanInterfaceInfoListHeader)); Int64 listIterator = ifaceList.ToInt64() + Marshal.SizeOf(header); WlanInterface[] interfaces = new WlanInterface[header.numberOfItems]; List<Guid> currentIfaceGuids = new List<Guid>(); for (int i = 0; i < header.numberOfItems; ++i) { Wlan.WlanInterfaceInfo info = (Wlan.WlanInterfaceInfo) Marshal.PtrToStructure(new IntPtr(listIterator), typeof (Wlan.WlanInterfaceInfo)); listIterator += Marshal.SizeOf(info); WlanInterface wlanIface; currentIfaceGuids.Add(info.interfaceGuid); if (ifaces.ContainsKey(info.interfaceGuid)) wlanIface = ifaces[info.interfaceGuid]; else wlanIface = new WlanInterface(this, info); interfaces[i] = wlanIface; ifaces[info.interfaceGuid] = wlanIface; } // Remove stale interfaces Queue<Guid> deadIfacesGuids = new Queue<Guid>(); foreach (Guid ifaceGuid in ifaces.Keys) { if (!currentIfaceGuids.Contains(ifaceGuid)) deadIfacesGuids.Enqueue(ifaceGuid); } while(deadIfacesGuids.Count != 0) { Guid deadIfaceGuid = deadIfacesGuids.Dequeue(); ifaces.Remove(deadIfaceGuid); } return interfaces; } finally { Wlan.WlanFreeMemory(ifaceList); } } } /// <summary> /// Gets a string that describes a specified reason code. /// </summary> /// <param name="reasonCode">The reason code.</param> /// <returns>The string.</returns> public string GetStringForReasonCode(Wlan.WlanReasonCode reasonCode) { StringBuilder sb = new StringBuilder(1024); // the 1024 size here is arbitrary; the WlanReasonCodeToString docs fail to specify a recommended size Wlan.ThrowIfError( Wlan.WlanReasonCodeToString(reasonCode, sb.Capacity, sb, IntPtr.Zero)); return sb.ToString(); } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Client.Protocol.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Org.Apache.Http.Client.Protocol { /// <summary> /// <para>Context attribute names for client. </para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/ClientContext /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/ClientContext", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IClientContextConstants /* scope: __dot42__ */ { /// <java-name> /// COOKIESPEC_REGISTRY /// </java-name> [Dot42.DexImport("COOKIESPEC_REGISTRY", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIESPEC_REGISTRY = "http.cookiespec-registry"; /// <java-name> /// AUTHSCHEME_REGISTRY /// </java-name> [Dot42.DexImport("AUTHSCHEME_REGISTRY", "Ljava/lang/String;", AccessFlags = 25)] public const string AUTHSCHEME_REGISTRY = "http.authscheme-registry"; /// <java-name> /// COOKIE_STORE /// </java-name> [Dot42.DexImport("COOKIE_STORE", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIE_STORE = "http.cookie-store"; /// <java-name> /// COOKIE_SPEC /// </java-name> [Dot42.DexImport("COOKIE_SPEC", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIE_SPEC = "http.cookie-spec"; /// <java-name> /// COOKIE_ORIGIN /// </java-name> [Dot42.DexImport("COOKIE_ORIGIN", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIE_ORIGIN = "http.cookie-origin"; /// <java-name> /// CREDS_PROVIDER /// </java-name> [Dot42.DexImport("CREDS_PROVIDER", "Ljava/lang/String;", AccessFlags = 25)] public const string CREDS_PROVIDER = "http.auth.credentials-provider"; /// <java-name> /// TARGET_AUTH_STATE /// </java-name> [Dot42.DexImport("TARGET_AUTH_STATE", "Ljava/lang/String;", AccessFlags = 25)] public const string TARGET_AUTH_STATE = "http.auth.target-scope"; /// <java-name> /// PROXY_AUTH_STATE /// </java-name> [Dot42.DexImport("PROXY_AUTH_STATE", "Ljava/lang/String;", AccessFlags = 25)] public const string PROXY_AUTH_STATE = "http.auth.proxy-scope"; /// <java-name> /// AUTH_SCHEME_PREF /// </java-name> [Dot42.DexImport("AUTH_SCHEME_PREF", "Ljava/lang/String;", AccessFlags = 25)] public const string AUTH_SCHEME_PREF = "http.auth.scheme-pref"; /// <java-name> /// USER_TOKEN /// </java-name> [Dot42.DexImport("USER_TOKEN", "Ljava/lang/String;", AccessFlags = 25)] public const string USER_TOKEN = "http.user-token"; } /// <summary> /// <para>Context attribute names for client. </para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/ClientContext /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/ClientContext", AccessFlags = 1537)] public partial interface IClientContext /* scope: __dot42__ */ { } /// <summary> /// <para>Request interceptor that matches cookies available in the current CookieStore to the request being executed and generates corresponding cookierequest headers.</para><para><para></para><para></para><title>Revision:</title><para>673450 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/RequestAddCookies /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/RequestAddCookies", AccessFlags = 33)] public partial class RequestAddCookies : global::Org.Apache.Http.IHttpRequestInterceptor /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public RequestAddCookies() /* MethodBuilder.Create */ { } /// <java-name> /// process /// </java-name> [Dot42.DexImport("process", "(Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)] public virtual void Process(global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Request interceptor that adds default request headers.</para><para><para></para><para></para><title>Revision:</title><para>653041 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/RequestDefaultHeaders /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/RequestDefaultHeaders", AccessFlags = 33)] public partial class RequestDefaultHeaders : global::Org.Apache.Http.IHttpRequestInterceptor /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public RequestDefaultHeaders() /* MethodBuilder.Create */ { } /// <java-name> /// process /// </java-name> [Dot42.DexImport("process", "(Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)] public virtual void Process(global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ { } } /// <summary> /// <para><para></para><para></para><title>Revision:</title><para>673450 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/RequestProxyAuthentication /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/RequestProxyAuthentication", AccessFlags = 33)] public partial class RequestProxyAuthentication : global::Org.Apache.Http.IHttpRequestInterceptor /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public RequestProxyAuthentication() /* MethodBuilder.Create */ { } /// <java-name> /// process /// </java-name> [Dot42.DexImport("process", "(Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)] public virtual void Process(global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Response interceptor that populates the current CookieStore with data contained in response cookies received in the given the HTTP response.</para><para><para></para><para></para><title>Revision:</title><para>673450 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/ResponseProcessCookies /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/ResponseProcessCookies", AccessFlags = 33)] public partial class ResponseProcessCookies : global::Org.Apache.Http.IHttpResponseInterceptor /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public ResponseProcessCookies() /* MethodBuilder.Create */ { } /// <java-name> /// process /// </java-name> [Dot42.DexImport("process", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)] public virtual void Process(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ { } } /// <java-name> /// org/apache/http/client/protocol/ClientContextConfigurer /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/ClientContextConfigurer", AccessFlags = 33)] public partial class ClientContextConfigurer : global::Org.Apache.Http.Client.Protocol.IClientContext /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)] public ClientContextConfigurer(global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ { } /// <java-name> /// setCookieSpecRegistry /// </java-name> [Dot42.DexImport("setCookieSpecRegistry", "(Lorg/apache/http/cookie/CookieSpecRegistry;)V", AccessFlags = 1)] public virtual void SetCookieSpecRegistry(global::Org.Apache.Http.Cookie.CookieSpecRegistry registry) /* MethodBuilder.Create */ { } /// <java-name> /// setAuthSchemeRegistry /// </java-name> [Dot42.DexImport("setAuthSchemeRegistry", "(Lorg/apache/http/auth/AuthSchemeRegistry;)V", AccessFlags = 1)] public virtual void SetAuthSchemeRegistry(global::Org.Apache.Http.Auth.AuthSchemeRegistry registry) /* MethodBuilder.Create */ { } /// <java-name> /// setCookieStore /// </java-name> [Dot42.DexImport("setCookieStore", "(Lorg/apache/http/client/CookieStore;)V", AccessFlags = 1)] public virtual void SetCookieStore(global::Org.Apache.Http.Client.ICookieStore store) /* MethodBuilder.Create */ { } /// <java-name> /// setCredentialsProvider /// </java-name> [Dot42.DexImport("setCredentialsProvider", "(Lorg/apache/http/client/CredentialsProvider;)V", AccessFlags = 1)] public virtual void SetCredentialsProvider(global::Org.Apache.Http.Client.ICredentialsProvider provider) /* MethodBuilder.Create */ { } /// <java-name> /// setAuthSchemePref /// </java-name> [Dot42.DexImport("setAuthSchemePref", "(Ljava/util/List;)V", AccessFlags = 1, Signature = "(Ljava/util/List<Ljava/lang/String;>;)V")] public virtual void SetAuthSchemePref(global::Java.Util.IList<string> list) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ClientContextConfigurer() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para><para></para><para></para><title>Revision:</title><para>673450 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/RequestTargetAuthentication /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/RequestTargetAuthentication", AccessFlags = 33)] public partial class RequestTargetAuthentication : global::Org.Apache.Http.IHttpRequestInterceptor /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public RequestTargetAuthentication() /* MethodBuilder.Create */ { } /// <java-name> /// process /// </java-name> [Dot42.DexImport("process", "(Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)] public virtual void Process(global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ { } } }
//#define REREAD_STATE_AFTER_WRITE_FAILED using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Orleans; using Orleans.Runtime; using Orleans.Storage; using Orleans.TestingHost; using UnitTests.GrainInterfaces; using UnitTests.Grains; using Xunit; using Xunit.Abstractions; using TesterInternal; using TestExtensions; using Orleans.Hosting; using Orleans.Internal; using Microsoft.Extensions.DependencyInjection; // ReSharper disable RedundantAssignment // ReSharper disable UnusedVariable // ReSharper disable InconsistentNaming namespace UnitTests.StorageTests { /// <summary> /// PersistenceGrainTests - Run with only local unit test silo -- no external dependency on Azure storage /// </summary> public class PersistenceGrainTests_Local : OrleansTestingBase, IClassFixture<PersistenceGrainTests_Local.Fixture>, IDisposable { public class Fixture : BaseTestClusterFixture { protected override void ConfigureTestCluster(TestClusterBuilder builder) { builder.Options.InitialSilosCount = 1; builder.AddSiloBuilderConfigurator<SiloConfigurator>(); } private class SiloConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { hostBuilder.AddMemoryGrainStorage("MemoryStore"); hostBuilder.AddTestStorageProvider(MockStorageProviderName1, (sp, name) => ActivatorUtilities.CreateInstance<MockStorageProvider>(sp, name)); hostBuilder.AddTestStorageProvider(MockStorageProviderName2, (sp, name) => ActivatorUtilities.CreateInstance<MockStorageProvider>(sp, name)); hostBuilder.AddTestStorageProvider(MockStorageProviderNameLowerCase, (sp, name) => ActivatorUtilities.CreateInstance<MockStorageProvider>(sp, name)); hostBuilder.AddTestStorageProvider(ErrorInjectorProviderName, (sp, name) => ActivatorUtilities.CreateInstance<ErrorInjectionStorageProvider>(sp)); } } } const string MockStorageProviderName1 = "test1"; const string MockStorageProviderName2 = "test2"; const string MockStorageProviderNameLowerCase = "lowercase"; const string ErrorInjectorProviderName = "ErrorInjector"; private readonly ITestOutputHelper output; protected TestCluster HostedCluster { get; } public PersistenceGrainTests_Local(ITestOutputHelper output, Fixture fixture) { this.output = output; HostedCluster = fixture.HostedCluster; SetErrorInjection(ErrorInjectorProviderName, ErrorInjectionPoint.None); ResetMockStorageProvidersHistory(); } public void Dispose() { SetErrorInjection(ErrorInjectorProviderName, ErrorInjectionPoint.None); } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Silo_StorageProvidersLoaded() { List<SiloHandle> silos = this.HostedCluster.GetActiveSilos().ToList(); foreach (var silo in silos) { var testHooks = this.HostedCluster.Client.GetTestHooks(silo); ICollection<string> providers = await testHooks.GetStorageProviderNames(); Assert.NotNull(providers); // Null provider manager Assert.True(providers.Count > 0, "Some providers loaded"); Assert.True(testHooks.HasStorageProvider(MockStorageProviderName1).Result, $"provider {MockStorageProviderName1} on silo {silo.Name} should be registered"); Assert.True(testHooks.HasStorageProvider(MockStorageProviderName2).Result, $"provider {MockStorageProviderName2} on silo {silo.Name} should be registered"); Assert.True(testHooks.HasStorageProvider(MockStorageProviderNameLowerCase).Result, $"provider {MockStorageProviderNameLowerCase} on silo {silo.Name} should be registered"); Assert.True(testHooks.HasStorageProvider(ErrorInjectorProviderName).Result, $"provider {ErrorInjectorProviderName} on silo {silo.Name} should be registered"); } } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public void Persistence_Silo_StorageProvider_Name_Missing() { List<SiloHandle> silos = this.HostedCluster.GetActiveSilos().ToList(); var silo = silos.First(); const string providerName = "NotPresent"; Assert.False(this.HostedCluster.Client.GetTestHooks(silo).HasStorageProvider(providerName).Result, $"provider {providerName} on silo {silo.Name} should not be registered"); } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_CheckStateInit() { Guid id = Guid.NewGuid(); IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id); bool ok = await grain.CheckStateInit(); Assert.True(ok, "CheckStateInit OK"); } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_CheckStorageProvider() { Guid id = Guid.NewGuid(); IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id); string providerType = await grain.CheckProviderType(); Assert.Equal(typeof(MockStorageProvider).FullName, providerType); // StorageProvider provider type } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_Init() { Guid id = Guid.NewGuid(); IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id); await grain.DoSomething(); //request InitCount on providers on all silos in this cluster IManagementGrain mgmtGrain = this.HostedCluster.GrainFactory.GetGrain<IManagementGrain>(0); object[] replies = await mgmtGrain.SendControlCommandToProvider(typeof(MockStorageProvider).FullName, MockStorageProviderName1, (int)MockStorageProvider.Commands.InitCount, null); Assert.Contains(1, replies); // StorageProvider #Init } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_Activate_StoredValue() { const string providerName = MockStorageProviderName1; string grainType = typeof(PersistenceTestGrain).FullName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(guid); // Store initial value in storage int initialValue = 567; SetStoredValue(providerName, typeof(MockStorageProvider).FullName, grainType, grain, "Field1", initialValue); int readValue = await grain.GetValue(); Assert.Equal(initialValue, readValue); // Read previously stored value } [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Generics")] public async Task Persistence_Grain_Activate_StoredValue_Generic() { const string providerName = MockStorageProviderName1; string grainType = typeof(PersistenceTestGenericGrain<int>).FullName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); var grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGenericGrain<int>>(guid); // Store initial value in storage int initialValue = 567; SetStoredValue(providerName, typeof(MockStorageProvider).FullName, grainType, grain, "Field1", initialValue); int readValue = await grain.GetValue(); Assert.Equal(initialValue, readValue); // Read previously stored value } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_Activate_Error() { const string providerName = ErrorInjectorProviderName; string grainType = typeof(PersistenceProviderErrorGrain).FullName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(guid); // Store initial value in storage int initialValue = 567; SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", initialValue); SetErrorInjection(providerName, ErrorInjectionPoint.BeforeRead); await Assert.ThrowsAsync<StorageProviderInjectedError>(() => grain.GetValue()); } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_Read() { const string providerName = MockStorageProviderName1; Guid id = Guid.NewGuid(); IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id); await grain.DoSomething(); var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_Write() { const string providerName = MockStorageProviderName1; Guid id = Guid.NewGuid(); IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id); await grain.DoWrite(1); var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes Assert.Equal(1, providerState.LastStoredGrainState.Field1); // Store-Field1 await grain.DoWrite(2); providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(2, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes Assert.Equal(2, providerState.LastStoredGrainState.Field1); // Store-Field1 } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_ReRead() { const string providerName = MockStorageProviderName1; string grainType = typeof(PersistenceTestGrain).FullName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(guid); await grain.DoSomething(); var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes SetStoredValue(providerName, typeof(MockStorageProvider).FullName, grainType, grain, "Field1", 42); await grain.DoRead(); providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(2, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2 Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2 Assert.Equal(42, providerState.LastStoredGrainState.Field1); // Store-Field1 } [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("MemoryStore")] public async Task MemoryStore_Read_Write() { Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IMemoryStorageTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IMemoryStorageTestGrain>(guid); int val = await grain.GetValue(); Assert.Equal(0, val); // Initial value await grain.DoWrite(1); val = await grain.GetValue(); Assert.Equal(1, val); // Value after Write-1 await grain.DoWrite(2); val = await grain.GetValue(); Assert.Equal(2, val); // Value after Write-2 val = await grain.DoRead(); Assert.Equal(2, val); // Value after Re-Read } [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("MemoryStore")] public async Task MemoryStore_Delete() { Guid id = Guid.NewGuid(); var grain = this.HostedCluster.GrainFactory.GetGrain<IMemoryStorageTestGrain>(id); await grain.DoWrite(1); await grain.DoDelete(); int val = await grain.GetValue(); // Should this throw instead? Assert.Equal(0, val); // Value after Delete await grain.DoWrite(2); val = await grain.GetValue(); Assert.Equal(2, val); // Value after Delete + New Write } [Fact, TestCategory("Stress"), TestCategory("CorePerf"), TestCategory("Persistence"), TestCategory("MemoryStore")] public async Task MemoryStore_Stress_Read() { const int numIterations = 10000; Stopwatch sw = Stopwatch.StartNew(); Task<int>[] promises = new Task<int>[numIterations]; for (int i = 0; i < numIterations; i++) { IMemoryStorageTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IMemoryStorageTestGrain>(Guid.NewGuid()); int idx = i; // Capture Func<Task<int>> asyncFunc = async () => { await grain.DoWrite(idx); return await grain.DoRead(); }; promises[i] = Task.Run(asyncFunc); } await Task.WhenAll(promises); TimeSpan elapsed = sw.Elapsed; double tps = (numIterations * 2) / elapsed.TotalSeconds; // One Read and one Write per iteration output.WriteLine("{0} Completed Read-Write operations in {1} at {2} TPS", numIterations, elapsed, tps); for (int i = 0; i < numIterations; i++) { int expectedVal = i; Assert.Equal(expectedVal, promises[i].Result); // "Returned value - Read @ #" + i } } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Write() { const string providerName = MockStorageProviderName1; Guid id = Guid.NewGuid(); IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id); await grain.DoWrite(1); var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes Assert.Equal(1, providerState.LastStoredGrainState.Field1); // Store-Field1 await grain.DoWrite(2); providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(2, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes Assert.Equal(2, providerState.LastStoredGrainState.Field1); // Store-Field1 } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Delete() { const string providerName = MockStorageProviderName1; Guid id = Guid.NewGuid(); IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id); await grain.DoWrite(1); var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); int initialReadCount = providerState.ProviderStateForTest.ReadCount; int initialWriteCount = providerState.ProviderStateForTest.WriteCount; int initialDeleteCount = providerState.ProviderStateForTest.DeleteCount; await grain.DoDelete(); providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(initialDeleteCount + 1, providerState.ProviderStateForTest.DeleteCount); // StorageProvider #Deletes Assert.Null(providerState.LastStoredGrainState); // Store-AfterDelete-Empty int val = await grain.GetValue(); // Returns current in-memory null data without re-read. providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); // update state Assert.Equal(0, val); // Value after Delete Assert.Equal(initialReadCount, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads await grain.DoWrite(2); providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); // update state Assert.Equal(initialReadCount, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(initialWriteCount + 1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes Assert.Equal(2, providerState.LastStoredGrainState.Field1); // Store-Field1 } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_Read_Error() { const string providerName = MockStorageProviderName1; Guid id = Guid.NewGuid(); IPersistenceErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceErrorGrain>(id); var val = await grain.GetValue(); var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes try { await grain.DoReadError(true); } catch (ApplicationException) { // Expected error } catch (AggregateException ae) { Exception e = ae.GetBaseException(); if (e is ApplicationException) { // Expected error } else { throw e; } } providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2 Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2 try { await grain.DoReadError(false); } catch (ApplicationException) { // Expected error } catch (AggregateException ae) { Exception e = ae.GetBaseException(); if (e is ApplicationException) { // Expected error } else { throw e; } } providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(2, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2 Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2 } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_Write_Error() { const string providerName = MockStorageProviderName1; Guid id = Guid.NewGuid(); IPersistenceErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceErrorGrain>(id); await grain.DoWrite(1); var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes Assert.Equal(1, providerState.LastStoredGrainState.Field1); // Store-Field1 await grain.DoWrite(2); providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(2, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes Assert.Equal(2, providerState.LastStoredGrainState.Field1); // Store-Field1 try { await grain.DoWriteError(3, true); } catch (ApplicationException) { // Expected error } catch (AggregateException ae) { if (ae.GetBaseException() is ApplicationException) { // Expected error } else { throw; } } providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); // update provider state Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(2, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes Assert.Equal(2, providerState.LastStoredGrainState.Field1); // Store-Field1 try { await grain.DoWriteError(4, false); } catch (ApplicationException) { // Expected error } catch (AggregateException ae) { if (ae.GetBaseException() is ApplicationException) { // Expected error } else { throw; } } providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(3, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes Assert.Equal(4, providerState.LastStoredGrainState.Field1); // Store-Field1 } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_ReRead_Error() { const string providerName = "test1"; string grainType = typeof(PersistenceErrorGrain).FullName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceErrorGrain>(guid); var val = await grain.GetValue(); var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes SetStoredValue(providerName, typeof(MockStorageProvider).FullName, grainType, grain, "Field1", 42); await grain.DoRead(); providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(2, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2 Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2 Assert.Equal(42, providerState.LastStoredGrainState.Field1); // Store-Field1 await grain.DoWrite(43); providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(2, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2 Assert.Equal(1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2 Assert.Equal(43, providerState.LastStoredGrainState.Field1); // Store-Field1 try { await grain.DoReadError(true); } catch (ApplicationException) { // Expected error } catch (AggregateException ae) { if (ae.GetBaseException() is ApplicationException) { // Expected error } else { throw; } } providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(2, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2 Assert.Equal(1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2 Assert.Equal(43, providerState.LastStoredGrainState.Field1); // Store-Field1 try { await grain.DoReadError(false); } catch (ApplicationException) { // Expected error } catch (AggregateException ae) { if (ae.GetBaseException() is ApplicationException) { // Expected error } else { throw; } } providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(3, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2 Assert.Equal(1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2 Assert.Equal(43, providerState.LastStoredGrainState.Field1); // Store-Field1 } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Provider_Error_BeforeRead() { string grainType = typeof(PersistenceProviderErrorGrain).FullName; string providerName = ErrorInjectorProviderName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(guid); var val = await grain.GetValue(); // Activate grain int expectedVal = 42; SetErrorInjection(providerName, ErrorInjectionPoint.None); SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal); val = await grain.DoRead(); Assert.Equal(expectedVal, val); // Returned value SetErrorInjection(providerName, ErrorInjectionPoint.BeforeRead); CheckStorageProviderErrors(grain.DoRead); SetErrorInjection(providerName, ErrorInjectionPoint.None); val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Provider_Error_AfterRead() { string grainType = typeof(PersistenceProviderErrorGrain).FullName; string providerName = ErrorInjectorProviderName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(guid); var val = await grain.GetValue(); // Activate grain int expectedVal = 52; SetErrorInjection(providerName, ErrorInjectionPoint.None); SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal); val = await grain.DoRead(); Assert.Equal(expectedVal, val); // Returned value SetErrorInjection(providerName, ErrorInjectionPoint.AfterRead); CheckStorageProviderErrors(grain.DoRead); val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value int newVal = 53; SetErrorInjection(providerName, ErrorInjectionPoint.None); SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", newVal); val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value await grain.DoRead(); // Force re-read expectedVal = newVal; val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Provider_Error_BeforeWrite() { Guid id = Guid.NewGuid(); string providerName = ErrorInjectorProviderName; IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(id); var val = await grain.GetValue(); int expectedVal = 62; await grain.DoWrite(expectedVal); var providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 const int attemptedVal3 = 63; SetErrorInjection(providerName, ErrorInjectionPoint.BeforeWrite); CheckStorageProviderErrors(() => grain.DoWrite(attemptedVal3)); // Stored value unchanged providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 SetErrorInjection(providerName, ErrorInjectionPoint.None); val = await grain.GetValue(); // Stored value unchanged providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 #if REREAD_STATE_AFTER_WRITE_FAILED Assert.Equal(expectedVal, val); // Last value written successfully #else Assert.Equal(attemptedVal3, val); // Last value attempted to be written is still in memory #endif } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Provider_InconsistentStateException_DeactivatesGrain() { Guid id = Guid.NewGuid(); string providerName = ErrorInjectorProviderName; IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(id); var val = await grain.GetValue(); int expectedVal = 62; var originalActivationId = await grain.GetActivationId(); await grain.DoWrite(expectedVal); var providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 const int attemptedVal3 = 63; SetErrorInjection(providerName, new ErrorInjectionBehavior { ErrorInjectionPoint = ErrorInjectionPoint.BeforeWrite, ExceptionType = typeof(InconsistentStateException) }); CheckStorageProviderErrors(() => grain.DoWrite(attemptedVal3), typeof(InconsistentStateException)); // Stored value unchanged providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 Assert.NotEqual(originalActivationId, await grain.GetActivationId()); SetErrorInjection(providerName, ErrorInjectionPoint.None); val = await grain.GetValue(); // Stored value unchanged providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 // The value should not have changed. Assert.Equal(expectedVal, val); } /// <summary> /// Tests that deactivations caused by an <see cref="InconsistentStateException"/> only affect the grain which /// the exception originated from. /// </summary> /// <returns></returns> [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Provider_InconsistentStateException_DeactivatesOnlyCurrentGrain() { var target = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(Guid.NewGuid()); var proxy = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorProxyGrain>(Guid.NewGuid()); // Record the original activation ids. var targetActivationId = await target.GetActivationId(); var proxyActivationId = await proxy.GetActivationId(); // Cause an inconsistent state exception. this.SetErrorInjection(ErrorInjectorProviderName, new ErrorInjectionBehavior { ErrorInjectionPoint = ErrorInjectionPoint.BeforeWrite, ExceptionType = typeof(InconsistentStateException) }); this.CheckStorageProviderErrors(() => proxy.DoWrite(63, target), typeof(InconsistentStateException)); // The target should have been deactivated by the exception. Assert.NotEqual(targetActivationId, await target.GetActivationId()); // The grain which called the target grain should not have been deactivated. Assert.Equal(proxyActivationId, await proxy.GetActivationId()); } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Provider_Error_AfterWrite() { Guid id = Guid.NewGuid(); string providerName = ErrorInjectorProviderName; IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(id); var val = await grain.GetValue(); int expectedVal = 82; await grain.DoWrite(expectedVal); var providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 const int attemptedVal4 = 83; SetErrorInjection(providerName, ErrorInjectionPoint.AfterWrite); CheckStorageProviderErrors(() => grain.DoWrite(attemptedVal4)); // Stored value has changed expectedVal = attemptedVal4; providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 SetErrorInjection(providerName, ErrorInjectionPoint.None); val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Provider_Error_BeforeReRead() { string grainType = typeof(PersistenceProviderErrorGrain).FullName; string providerName = ErrorInjectorProviderName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(guid); var val = await grain.GetValue(); int expectedVal = 72; SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal); val = await grain.DoRead(); Assert.Equal(expectedVal, val); // Returned value expectedVal = 73; await grain.DoWrite(expectedVal); var providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 SetErrorInjection(providerName, ErrorInjectionPoint.BeforeRead); CheckStorageProviderErrors(grain.DoRead); SetErrorInjection(providerName, ErrorInjectionPoint.None); val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Provider_Error_AfterReRead() { string grainType = typeof(PersistenceProviderErrorGrain).FullName; string providerName = ErrorInjectorProviderName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(guid); var val = await grain.GetValue(); int expectedVal = 92; SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal); val = await grain.DoRead(); Assert.Equal(expectedVal, val); // Returned value expectedVal = 93; await grain.DoWrite(expectedVal); var providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 expectedVal = 94; SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal); SetErrorInjection(providerName, ErrorInjectionPoint.AfterRead); CheckStorageProviderErrors(grain.DoRead); SetErrorInjection(providerName, ErrorInjectionPoint.None); val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Error_Handled_Read() { string grainType = typeof(PersistenceUserHandledErrorGrain).FullName; string providerName = ErrorInjectorProviderName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceUserHandledErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceUserHandledErrorGrain>(guid); var val = await grain.GetValue(); // Activate grain int expectedVal = 42; SetErrorInjection(providerName, ErrorInjectionPoint.None); SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal); val = await grain.DoRead(false); Assert.Equal(expectedVal, val); // Returned value int newVal = expectedVal + 1; SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", newVal); SetErrorInjection(providerName, ErrorInjectionPoint.BeforeRead); val = await grain.DoRead(true); Assert.Equal(expectedVal, val); // Returned value SetErrorInjection(providerName, ErrorInjectionPoint.None); expectedVal = newVal; SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", newVal); val = await grain.DoRead(false); Assert.Equal(expectedVal, val); // Returned value } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Error_Handled_Write() { string grainType = typeof(PersistenceUserHandledErrorGrain).FullName; string providerName = ErrorInjectorProviderName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceUserHandledErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceUserHandledErrorGrain>(guid); var val = await grain.GetValue(); // Activate grain int expectedVal = 42; SetErrorInjection(providerName, ErrorInjectionPoint.None); SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal); val = await grain.DoRead(false); Assert.Equal(expectedVal, val); // Returned value int newVal = expectedVal + 1; SetErrorInjection(providerName, ErrorInjectionPoint.BeforeWrite); await grain.DoWrite(newVal, true); val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value SetErrorInjection(providerName, ErrorInjectionPoint.None); expectedVal = newVal; await grain.DoWrite(newVal, false); val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Error_NotHandled_Write() { string grainType = typeof(PersistenceUserHandledErrorGrain).FullName; string providerName = ErrorInjectorProviderName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceUserHandledErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceUserHandledErrorGrain>(guid); var val = await grain.GetValue(); // Activate grain int expectedVal = 42; SetErrorInjection(providerName, ErrorInjectionPoint.None); SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal); val = await grain.DoRead(false); Assert.Equal(expectedVal, val); // Returned value after read int newVal = expectedVal + 1; SetErrorInjection(providerName, ErrorInjectionPoint.BeforeWrite); CheckStorageProviderErrors(() => grain.DoWrite(newVal, false)); val = await grain.GetValue(); // Stored value unchanged var providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 #if REREAD_STATE_AFTER_WRITE_FAILED Assert.Equal(expectedVal, val); // After failed write: Last value written successfully #else Assert.Equal(newVal, val); // After failed write: Last value attempted to be written is still in memory #endif SetErrorInjection(providerName, ErrorInjectionPoint.None); expectedVal = newVal; await grain.DoWrite(newVal, false); val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value after good write } [Fact, TestCategory("Stress"), TestCategory("CorePerf"), TestCategory("Persistence")] public async Task Persistence_Provider_Loop_Read() { const int numIterations = 100; string grainType = typeof(PersistenceTestGrain).FullName; Task<int>[] promises = new Task<int>[numIterations]; for (int i = 0; i < numIterations; i++) { int expectedVal = i; IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(Guid.NewGuid()); Guid guid = grain.GetPrimaryKey(); string id = guid.ToString("N"); SetStoredValue(MockStorageProviderName1, typeof(MockStorageProvider).FullName, grainType, grain, "Field1", expectedVal); // Update state data behind grain promises[i] = grain.DoRead(); } await Task.WhenAll(promises); for (int i = 0; i < numIterations; i++) { int expectedVal = i; Assert.Equal(expectedVal, promises[i].Result); // "Returned value - Read @ #" + i } } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_BadProvider() { IBadProviderTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IBadProviderTestGrain>(Guid.NewGuid()); var oex = await Assert.ThrowsAsync<BadGrainStorageConfigException>(() => grain.DoSomething()); } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public void OrleansException_BadProvider() { string msg1 = "BadProvider"; string msg2 = "Wrapper"; string msg3 = "Aggregate"; var bpce = new BadProviderConfigException(msg1); var oe = new OrleansException(msg2, bpce); var ae = new AggregateException(msg3, oe); Assert.NotNull(ae.InnerException); // AggregateException.InnerException should not be null Assert.IsAssignableFrom<OrleansException>(ae.InnerException); Exception exc = ae.InnerException; Assert.NotNull(exc.InnerException); // OrleansException.InnerException should not be null Assert.IsAssignableFrom<BadProviderConfigException>(exc.InnerException); exc = ae.GetBaseException(); Assert.NotNull(exc.InnerException); // BaseException.InnerException should not be null Assert.IsAssignableFrom<BadProviderConfigException>(exc.InnerException); Assert.Equal(msg3, ae.Message); // "AggregateException.Message should be '{0}'", msg3 Assert.Equal(msg2, exc.Message); // "OrleansException.Message should be '{0}'", msg2 Assert.Equal(msg1, exc.InnerException.Message); // "InnerException.Message should be '{0}'", msg1 } [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("MemoryStore")] public async Task MemoryStore_UserGrain_Read_Write() { Guid id = Guid.NewGuid(); IUser grain = this.HostedCluster.GrainFactory.GetGrain<IUser>(id); string name = id.ToString(); await grain.SetName(name); string readName = await grain.GetName(); Assert.Equal(name, readName); // Read back previously set name Guid id1 = Guid.NewGuid(); Guid id2 = Guid.NewGuid(); string name1 = id1.ToString(); string name2 = id2.ToString(); IUser friend1 = this.HostedCluster.GrainFactory.GetGrain<IUser>(id1); IUser friend2 = this.HostedCluster.GrainFactory.GetGrain<IUser>(id2); await friend1.SetName(name1); await friend2.SetName(name2); var readName1 = await friend1.GetName(); var readName2 = await friend2.GetName(); Assert.Equal(name1, readName1); // Friend #1 Name Assert.Equal(name2, readName2); // Friend #2 Name await grain.AddFriend(friend1); await grain.AddFriend(friend2); var friends = await grain.GetFriends(); Assert.Equal(2, friends.Count); // Number of friends Assert.Equal(name1, await friends[0].GetName()); // GetFriends - Friend #1 Name Assert.Equal(name2, await friends[1].GetName()); // GetFriends - Friend #2 Name } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_NoState() { const string providerName = MockStorageProviderName1; Guid id = Guid.NewGuid(); IPersistenceNoStateTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceNoStateTestGrain>(id); await grain.DoSomething(); Assert.True(HasStorageProvider(providerName)); } [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Serialization")] public void Serialize_GrainState_DeepCopy() { // NOTE: This test requires Silo to be running & Client init so that grain references can be resolved before serialization. IUser[] grains = new IUser[3]; grains[0] = this.HostedCluster.GrainFactory.GetGrain<IUser>(Guid.NewGuid()); grains[1] = this.HostedCluster.GrainFactory.GetGrain<IUser>(Guid.NewGuid()); grains[2] = this.HostedCluster.GrainFactory.GetGrain<IUser>(Guid.NewGuid()); GrainStateContainingGrainReferences initialState = new GrainStateContainingGrainReferences(); foreach (var g in grains) { initialState.GrainList.Add(g); initialState.GrainDict.Add(g.GetPrimaryKey().ToString(), g); } var copy = (GrainStateContainingGrainReferences)this.HostedCluster.SerializationManager.DeepCopy(initialState); Assert.NotSame(initialState.GrainDict, copy.GrainDict); // Dictionary Assert.NotSame(initialState.GrainList, copy.GrainList); // List } [Fact, TestCategory("Persistence"), TestCategory("Serialization"), TestCategory("CorePerf"), TestCategory("Stress")] public async Task Serialize_GrainState_DeepCopy_Stress() { int num = 100; int loops = num * 100; GrainStateContainingGrainReferences[] states = new GrainStateContainingGrainReferences[num]; for (int i = 0; i < num; i++) { IUser grain = this.HostedCluster.GrainFactory.GetGrain<IUser>(Guid.NewGuid()); states[i] = new GrainStateContainingGrainReferences(); states[i].GrainList.Add(grain); states[i].GrainDict.Add(grain.GetPrimaryKey().ToString(), grain); } List<Task> tasks = new List<Task>(); for (int i = 0; i < loops; i++) { int idx = random.Next(num); tasks.Add(Task.Run(() => { var copy = this.HostedCluster.SerializationManager.DeepCopy(states[idx]); })); tasks.Add(Task.Run(() => { var other = this.HostedCluster.SerializationManager.RoundTripSerializationForTesting(states[idx]); })); } await Task.WhenAll(tasks); //Task copyTask = Task.Run(() => //{ // for (int i = 0; i < loops; i++) // { // int idx = random.Next(num); // var copy = states[idx].DeepCopy(); // } //}); //Task serializeTask = Task.Run(() => //{ // for (int i = 0; i < loops; i++) // { // int idx = random.Next(num); // var other = SerializationManager.RoundTripSerializationForTesting(states[idx]); // } //}); //await Task.WhenAll(copyTask, serializeTask); } [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Scheduler"), TestCategory("Reentrancy")] public async Task ReentrentGrainWithState() { Guid id1 = Guid.NewGuid(); Guid id2 = Guid.NewGuid(); IReentrentGrainWithState grain1 = this.HostedCluster.GrainFactory.GetGrain<IReentrentGrainWithState>(id1); IReentrentGrainWithState grain2 = this.HostedCluster.GrainFactory.GetGrain<IReentrentGrainWithState>(id2); await Task.WhenAll(grain1.Setup(grain2), grain2.Setup(grain1)); Task t11 = grain1.Test1(); Task t12 = grain1.Test2(); Task t21 = grain2.Test1(); Task t22 = grain2.Test2(); await Task.WhenAll(t11, t12, t21, t22); } [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Scheduler"), TestCategory("Reentrancy")] public async Task NonReentrentStressGrainWithoutState() { Guid id1 = Guid.NewGuid(); INonReentrentStressGrainWithoutState grain1 = this.HostedCluster.GrainFactory.GetGrain<INonReentrentStressGrainWithoutState>(id1); await grain1.Test1(); } private const bool DoStart = true; // Task.Delay tests fail (Timeout) unless True [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Scheduler"), TestCategory("Reentrancy")] public async Task ReentrentGrain_Task_Delay() { Guid id1 = Guid.NewGuid(); IReentrentGrainWithState grain1 = this.HostedCluster.GrainFactory.GetGrain<IReentrentGrainWithState>(id1); await grain1.Task_Delay(DoStart); } [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Scheduler"), TestCategory("Reentrancy")] public async Task NonReentrentGrain_Task_Delay() { Guid id1 = Guid.NewGuid(); INonReentrentStressGrainWithoutState grain1 = this.HostedCluster.GrainFactory.GetGrain<INonReentrentStressGrainWithoutState>(id1); await grain1.Task_Delay(DoStart); } [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Scheduler"), TestCategory("Reentrancy")] public async Task StateInheritanceTest() { Guid id1 = Guid.NewGuid(); IStateInheritanceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IStateInheritanceTestGrain>(id1); await grain.SetValue(1); int val = await grain.GetValue(); Assert.Equal(1, val); } // ---------- Utility functions ---------- private void SetStoredValue(string providerName, string providerTypeFullName, string grainType, IGrain grain, string fieldName, int newValue) { IManagementGrain mgmtGrain = this.HostedCluster.GrainFactory.GetGrain<IManagementGrain>(0); // set up SetVal func args var args = new MockStorageProvider.SetValueArgs { Val = newValue, Name = "Field1", GrainType = grainType, GrainReference = (GrainReference) grain, StateType = typeof(PersistenceTestGrainState) }; mgmtGrain.SendControlCommandToProvider(providerTypeFullName, providerName, (int)MockStorageProvider.Commands.SetValue, args).Wait(); } private void SetErrorInjection(string providerName, ErrorInjectionPoint errorInjectionPoint) { SetErrorInjection(providerName, new ErrorInjectionBehavior { ErrorInjectionPoint = errorInjectionPoint }); } private void SetErrorInjection(string providerName, ErrorInjectionBehavior errorInjectionBehavior) { ErrorInjectionStorageProvider.SetErrorInjection(providerName, errorInjectionBehavior, this.HostedCluster.GrainFactory); } private void CheckStorageProviderErrors(Func<Task> taskFunc, Type expectedException = null) { StackTrace at = new StackTrace(); TimeSpan timeout = Debugger.IsAttached ? TimeSpan.FromMinutes(5) : TimeSpan.FromSeconds(15); try { taskFunc().WithTimeout(timeout).GetAwaiter().GetResult(); if (ErrorInjectionStorageProvider.DoInjectErrors) { string msg = "StorageProviderInjectedError exception should have been thrown " + at; output.WriteLine("Assertion failed: {0}", msg); Assert.True(false, msg); } } catch (Exception e) { output.WriteLine("Exception caught: {0}", e); var baseException = e.GetBaseException(); if (baseException is OrleansException && baseException.InnerException != null) { baseException = baseException.InnerException; } Assert.IsAssignableFrom(expectedException ?? typeof(StorageProviderInjectedError), baseException); //if (exc is StorageProviderInjectedError) //{ // //Expected error //} //else //{ // output.WriteLine("Unexpected exception: {0}", exc); // Assert.True(false, exc.ToString()); //} } } private bool HasStorageProvider(string providerName) { foreach (var siloHandle in this.HostedCluster.GetActiveSilos()) { if (this.HostedCluster.Client.GetTestHooks(siloHandle).HasStorageProvider(providerName).Result) { return true; } } return false; } private ProviderState GetStateForStorageProviderInUse(string providerName, string providerTypeFullName, bool okNull = false) { ProviderState providerState = new ProviderState(); IManagementGrain mgmtGrain = this.HostedCluster.GrainFactory.GetGrain<IManagementGrain>(0); object[] replies = mgmtGrain.SendControlCommandToProvider(providerTypeFullName, providerName, (int)MockStorageProvider.Commands.GetProvideState, null).Result; object[] replies2 = mgmtGrain.SendControlCommandToProvider(providerTypeFullName, providerName, (int)MockStorageProvider.Commands.GetLastState, null).Result; for(int i = 0; i < replies.Length; i++) { MockStorageProvider.StateForTest state = (MockStorageProvider.StateForTest)replies[i]; PersistenceTestGrainState grainState = (PersistenceTestGrainState)replies2[i]; if (state.ReadCount > 0) { providerState.ProviderStateForTest = state; providerState.LastStoredGrainState = grainState; return providerState; } } return providerState; } class ProviderState { public MockStorageProvider.StateForTest ProviderStateForTest { get; set; } public PersistenceTestGrainState LastStoredGrainState { get; set; } } private void ResetMockStorageProvidersHistory() { var mockStorageProviders = new[] { MockStorageProviderName1, MockStorageProviderName2, MockStorageProviderNameLowerCase }; foreach (var siloHandle in this.HostedCluster.GetActiveSilos().ToList()) { foreach (var providerName in mockStorageProviders) { if (!this.HostedCluster.Client.GetTestHooks(siloHandle).HasStorageProvider(providerName).Result) continue; IManagementGrain mgmtGrain = this.HostedCluster.GrainFactory.GetGrain<IManagementGrain>(0); object[] replies = mgmtGrain.SendControlCommandToProvider(typeof(MockStorageProvider).FullName, providerName, (int)MockStorageProvider.Commands.ResetHistory, null).Result; } } } } } // ReSharper restore RedundantAssignment // ReSharper restore UnusedVariable // ReSharper restore InconsistentNaming
using System; /// <summary> /// Convert.ToBoolean(Int16) /// Converts the value of the specified 16-bit signed integer to an equivalent Boolean value. /// </summary> public class ConvertToBoolean { public static int Main() { ConvertToBoolean testObj = new ConvertToBoolean(); TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToBoolean(Int16)"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; string errorDesc; Int16 b; bool expectedValue; bool actualValue; b = TestLibrary.Generator.GetInt16(-55); TestLibrary.TestFramework.BeginScenario("PosTest1: Random Int16 value between 0 and Int16.MaxValue."); try { actualValue = Convert.ToBoolean(b); expectedValue = 0 != b; if (actualValue != expectedValue) { errorDesc = "The boolean value of Int16 value " + b + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("001", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe Int16 value is " + b; TestLibrary.TestFramework.LogError("002", errorDesc); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string errorDesc; Int16 b; bool expectedValue; bool actualValue; b = Int16.MaxValue; TestLibrary.TestFramework.BeginScenario("PosTest2: value is Int16.MaxValue."); try { actualValue = Convert.ToBoolean(b); expectedValue = 0 != b; if (actualValue != expectedValue) { errorDesc = "The boolean value of Int16 value " + b + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("003", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe byte value is " + b; TestLibrary.TestFramework.LogError("004", errorDesc); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string errorDesc; Int16 b; bool expectedValue; bool actualValue; b = Int16.MinValue; TestLibrary.TestFramework.BeginScenario("PosTest3: value is Int16.MinValue."); try { actualValue = Convert.ToBoolean(b); expectedValue = 0 != b; if (actualValue != expectedValue) { errorDesc = "The boolean value of Int16 integer " + b + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("005", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe Int16 value is " + b; TestLibrary.TestFramework.LogError("006", errorDesc); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; string errorDesc; Int16 b; bool expectedValue; bool actualValue; b = (Int16)(-1 * TestLibrary.Generator.GetInt16(-55) - 1); TestLibrary.TestFramework.BeginScenario("PosTest4: Random Int16 value between Int16.MinValue and -1."); try { actualValue = Convert.ToBoolean(b); expectedValue = 0 != b; if (actualValue != expectedValue) { errorDesc = "The boolean value of Int16 value " + b + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("007", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe Int16 value is " + b; TestLibrary.TestFramework.LogError("008", errorDesc); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; string errorDesc; Int16 b; bool expectedValue; bool actualValue; b = 0; TestLibrary.TestFramework.BeginScenario("PosTest5: Int16 value is zero."); try { actualValue = Convert.ToBoolean(b); expectedValue = 0 != b; if (actualValue != expectedValue) { errorDesc = "The boolean value of Int16 value " + b + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("009", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe Int16 value is " + b; TestLibrary.TestFramework.LogError("010", errorDesc); retVal = false; } return retVal; } #endregion }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DynamicTests : ExpressionCompilerTestBase { [Fact] public void Local_Simple() { var source = @"class C { static void M() { dynamic d = 1; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (dynamic V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); } [Fact] public void Local_Array() { var source = @"class C { static void M() { dynamic[] d = new dynamic[1]; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (dynamic[] V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); } [Fact] public void Local_Generic() { var source = @"class C { static void M() { System.Collections.Generic.List<dynamic> d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments.Single().TypeKind); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Collections.Generic.List<dynamic> V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); } [Fact] public void LocalConstant_Simple() { var source = @"class C { static void M() { const dynamic d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; comp.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); // We're going to override the true signature (i.e. int32) with one indicating // that the constant is a System.Object. var constantSignatures = new Dictionary<string, byte[]> { { "d", new byte[] { 0x1c } }, }.ToImmutableDictionary(); var runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, new SymReader(pdbBytes, constantSignatures)); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); } [Fact] public void LocalConstant_Array() { var source = @"class C { static void M() { const dynamic[] d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; comp.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); // We're going to override the true signature (i.e. int32) with one indicating // that the constant is a System.Object[]. var constantSignatures = new Dictionary<string, byte[]> { { "d", new byte[] { 0x1d, 0x1c } }, }.ToImmutableDictionary(); var runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, new SymReader(pdbBytes, constantSignatures)); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); } [Fact] public void LocalConstant_Generic() { var source = @"class C { static void M() { const Generic<dynamic> d = null; } static dynamic ForceDynamicAttribute() { return null; } } class Generic<T> { } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; comp.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); // We're going to override the true signature (i.e. int32) with one indicating // that the constant is a Generic<System.Object>. var constantSignatures = new Dictionary<string, byte[]> { { "d", new byte[] { 0x15, 0x12, 0x0c, 0x01, 0x1c } }, }.ToImmutableDictionary(); var runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, new SymReader(pdbBytes, constantSignatures)); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments.Single().TypeKind); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); } [Fact] public void Parameter_Simple() { var source = @"class C { static void M(dynamic d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void Parameter_Array() { var source = @"class C { static void M(dynamic[] d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void Parameter_Generic() { var source = @"class C { static void M(System.Collections.Generic.List<dynamic> d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments.Single().TypeKind); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void DynamicAttribute_NotAvailable() { var source = @"class C { static void M() { dynamic d = 1; } }"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasNoDynamicAttribute(method); } private static void AssertHasDynamicAttribute(IMethodSymbol method) { Assert.Contains( "System.Runtime.CompilerServices.DynamicAttribute", method.GetSynthesizedAttributes(forReturnType: true).Select(a => a.AttributeClass.ToTestDisplayString())); } private static void AssertHasNoDynamicAttribute(IMethodSymbol method) { Assert.DoesNotContain( "System.Runtime.CompilerServices.DynamicAttribute", method.GetSynthesizedAttributes(forReturnType: true).Select(a => a.AttributeClass.ToTestDisplayString())); } [Fact] public void DynamicCall() { var source = @" class C { void M() { dynamic d = this; d.M(); } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var assembly = context.CompileExpression("d.M()", out error, testData); Assert.Null(error); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(TypeKind.Dynamic, methodData.Method.ReturnType.TypeKind); methodData.VerifyIL(@" { // Code size 77 (0x4d) .maxstack 9 .locals init (dynamic V_0) //d IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0037 IL_0007: ldc.i4.0 IL_0008: ldstr ""M"" IL_000d: ldnull IL_000e: ldtoken ""<>x"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.1 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0032: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_003c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0041: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0046: ldloc.0 IL_0047: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004c: ret } "); } [WorkItem(1072296)] [Fact] public void InvokeStaticMemberInLambda() { var source = @" class C { static dynamic x; static void Foo(dynamic y) { System.Action a = () => Foo(x); } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.Foo"); var testData = new CompilationTestData(); string error; context.CompileAssignment("a", "() => Foo(x)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>c.<<>m0>b__0_0").VerifyIL(@" { // Code size 106 (0x6a) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""Foo"" IL_0011: ldnull IL_0012: ldtoken ""<>x"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0055: ldtoken ""<>x"" IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005f: ldsfld ""dynamic C.x"" IL_0064: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0069: ret }"); context = CreateMethodContext(runtime, "C.<>c.<Foo>b__1_0"); testData = new CompilationTestData(); context.CompileExpression("Foo(x)", out error, testData); Assert.Null(error); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL(@" { // Code size 102 (0x66) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0042 IL_0007: ldc.i4.0 IL_0008: ldstr ""Foo"" IL_000d: ldnull IL_000e: ldtoken ""<>x"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.s 33 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: dup IL_002a: ldc.i4.1 IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0051: ldtoken ""<>x"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldsfld ""dynamic C.x"" IL_0060: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0065: ret }"); } [WorkItem(1095613)] [Fact(Skip = "1095613")] public void HoistedLocalsLoseDynamicAttribute() { var source = @" class C { static void M(dynamic x) { dynamic y = 3; System.Func<dynamic> a = () => x + y; } static void Foo(int x) { M(x); } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; context.CompileExpression("Foo(x)", out error, testData); Assert.Null(error); testData.GetMethodData("<>c.<>m0()").VerifyIL(@" { // Code size 166 (0xa6) .maxstack 11 .locals init (System.Func<dynamic> V_0) //a IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken ""System.Func<dynamic>"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldtoken ""<>c"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0021: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0026: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_002b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_0030: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>>.Target"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_003a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_003f: brtrue.s IL_007c IL_0041: ldc.i4.0 IL_0042: ldstr ""Foo"" IL_0047: ldnull IL_0048: ldtoken ""<>c"" IL_004d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0052: ldc.i4.2 IL_0053: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0058: dup IL_0059: ldc.i4.0 IL_005a: ldc.i4.s 33 IL_005c: ldnull IL_005d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0062: stelem.ref IL_0063: dup IL_0064: ldc.i4.1 IL_0065: ldc.i4.0 IL_0066: ldnull IL_0067: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006c: stelem.ref IL_006d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0072: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0077: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_007c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_0081: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_0086: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_008b: ldtoken ""<>c"" IL_0090: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0095: ldsfld ""dynamic C.x"" IL_009a: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_009f: callvirt ""System.Func<dynamic> System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00a4: stloc.0 IL_00a5: ret }"); context.CompileExpression("Foo(y)", out error, testData); Assert.Null(error); testData.GetMethodData("<>c.<>m0()").VerifyIL(@" { // Code size 166 (0xa6) .maxstack 11 .locals init (System.Func<dynamic> V_0) //a IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken ""System.Func<dynamic>"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldtoken ""<>c"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0021: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0026: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_002b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_0030: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>>.Target"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_003a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_003f: brtrue.s IL_007c IL_0041: ldc.i4.0 IL_0042: ldstr ""Foo"" IL_0047: ldnull IL_0048: ldtoken ""<>c"" IL_004d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0052: ldc.i4.2 IL_0053: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0058: dup IL_0059: ldc.i4.0 IL_005a: ldc.i4.s 33 IL_005c: ldnull IL_005d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0062: stelem.ref IL_0063: dup IL_0064: ldc.i4.1 IL_0065: ldc.i4.0 IL_0066: ldnull IL_0067: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006c: stelem.ref IL_006d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0072: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0077: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_007c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_0081: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_0086: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_008b: ldtoken ""<>c"" IL_0090: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0095: ldsfld ""dynamic C.x"" IL_009a: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_009f: callvirt ""System.Func<dynamic> System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00a4: stloc.0 IL_00a5: ret }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Specialized; using Xunit; namespace System.Diagnostics.Tests { [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // In appcontainer, cannot write to perf counters public static class PerformanceCounterCategoryTests { [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_CreatePerformanceCounterCategory_DefaultConstructor() { PerformanceCounterCategory pcc = new PerformanceCounterCategory(); Assert.Equal(".", pcc.MachineName); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_CreatePerformanceCounterCategory_NullTests() { Assert.Throws<ArgumentNullException>(() => new PerformanceCounterCategory(null, ".")); Assert.Throws<ArgumentException>(() => new PerformanceCounterCategory(string.Empty, ".")); Assert.Throws<ArgumentException>(() => new PerformanceCounterCategory("category", string.Empty)); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_SetCategoryName_Valid() { PerformanceCounterCategory pcc = new PerformanceCounterCategory(); pcc.CategoryName = "Processor"; Assert.Equal("Processor", pcc.CategoryName); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_SetCategoryName_Invalid() { PerformanceCounterCategory pcc = new PerformanceCounterCategory(); Assert.Throws<ArgumentNullException>(() => pcc.CategoryName = null); Assert.Throws<ArgumentException>(() => pcc.CategoryName = string.Empty); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_SetMachineName_Invalid() { PerformanceCounterCategory pcc = new PerformanceCounterCategory(); Assert.Throws<ArgumentException>(() => pcc.MachineName = string.Empty); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_SetMachineName_ValidCategoryNameNull() { PerformanceCounterCategory pcc = new PerformanceCounterCategory(); pcc.MachineName = "machineName"; Assert.Equal("machineName", pcc.MachineName); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_SetMachineName_ValidCategoryNameNotNull() { PerformanceCounterCategory pcc = new PerformanceCounterCategory(); pcc.CategoryName = "Processor"; pcc.MachineName = "machineName"; Assert.Equal("machineName", pcc.MachineName); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_GetCounterHelp_Invalid() { PerformanceCounterCategory pcc = new PerformanceCounterCategory(); Assert.Throws<InvalidOperationException>(() => pcc.CategoryHelp); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_CategoryType_MultiInstance() { var name = nameof(PerformanceCounterCategory_CategoryType_MultiInstance) + "_Counter"; var category = Helpers.CreateCategory(name, PerformanceCounterCategoryType.MultiInstance); PerformanceCounterCategory pcc = Helpers.RetryOnAllPlatforms(() => new PerformanceCounterCategory(category)); Assert.Equal(PerformanceCounterCategoryType.MultiInstance, Helpers.RetryOnAllPlatforms(() => pcc.CategoryType)); PerformanceCounterCategory.Delete(category); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_CategoryType_SingleInstance() { var name = nameof(PerformanceCounterCategory_CategoryType_SingleInstance) + "_Counter"; var category = Helpers.CreateCategory(name, PerformanceCounterCategoryType.SingleInstance); PerformanceCounterCategory pcc = Helpers.RetryOnAllPlatforms(() => new PerformanceCounterCategory(category)); Assert.Equal(PerformanceCounterCategoryType.SingleInstance, Helpers.RetryOnAllPlatforms(() => pcc.CategoryType)); PerformanceCounterCategory.Delete(category); } #pragma warning disable 0618 // obsolete warning [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_Create_Obsolete() { var name = nameof(PerformanceCounterCategory_Create_Obsolete) + "_Counter"; var category = name + "_Category"; Helpers.DeleteCategory(category); PerformanceCounterCategory.Create(category, "category help", name, "counter help"); Assert.True(PerformanceCounterCategory.Exists(category)); PerformanceCounterCategory.Delete(category); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_Create_Obsolete_CCD() { var name = nameof(PerformanceCounterCategory_Create_Obsolete_CCD) + "_Counter"; var category = name + "_Category"; CounterCreationData ccd = new CounterCreationData(name, "counter help", PerformanceCounterType.NumberOfItems32); CounterCreationDataCollection ccdc = new CounterCreationDataCollection(); ccdc.Add(ccd); Helpers.DeleteCategory(category); PerformanceCounterCategory.Create(category, "category help", ccdc); Assert.True(PerformanceCounterCategory.Exists(category)); PerformanceCounterCategory.Delete(category); } #pragma warning restore 0618 [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_Create_Invalid() { Assert.Throws<ArgumentNullException>(() => PerformanceCounterCategory.Create(null, "Categoryhelp", PerformanceCounterCategoryType.SingleInstance, "counter name", "counter help")); Assert.Throws<ArgumentNullException>(() => PerformanceCounterCategory.Create("category name", "Categoryhelp", PerformanceCounterCategoryType.SingleInstance, null, "counter help")); Assert.Throws<ArgumentNullException>(() => PerformanceCounterCategory.Create("category name", "Category help", PerformanceCounterCategoryType.SingleInstance, null)); Assert.Throws<InvalidOperationException>(() => PerformanceCounterCategory.Create("Processor", "Category help", PerformanceCounterCategoryType.MultiInstance, "Interrupts/sec", "counter help")); string maxCounter = new string('a', 32769); Assert.Throws<ArgumentException>(() => PerformanceCounterCategory.Create("Category name", "Category help", PerformanceCounterCategoryType.SingleInstance, maxCounter, "counter help")); Assert.Throws<ArgumentException>(() => PerformanceCounterCategory.Create(maxCounter, "Category help", PerformanceCounterCategoryType.SingleInstance, "Counter name", "counter help")); Assert.Throws<ArgumentException>(() => PerformanceCounterCategory.Create("Category name", maxCounter, PerformanceCounterCategoryType.SingleInstance, "Counter name", "counter help")); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_GetCategories() { PerformanceCounterCategory[] categories = PerformanceCounterCategory.GetCategories(); Assert.True(categories.Length > 0); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_GetCategories_StaticInvalid() { Assert.Throws<ArgumentException>(() => PerformanceCounterCategory.GetCategories(string.Empty)); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_CounterExists_InterruptsPerSec() { PerformanceCounterCategory pcc = Helpers.RetryOnAllPlatforms(() => new PerformanceCounterCategory("Processor")); Assert.True(pcc.CounterExists("Interrupts/sec")); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_CounterExists_Invalid() { PerformanceCounterCategory pcc = new PerformanceCounterCategory(); Assert.Throws<ArgumentNullException>(() => pcc.CounterExists(null)); Assert.Throws<InvalidOperationException>(() => pcc.CounterExists("Interrupts/sec")); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_CounterExists_StaticInterruptsPerSec() { Assert.True(PerformanceCounterCategory.CounterExists("Interrupts/sec", "Processor")); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_CounterExists_StaticInvalid() { Assert.Throws<ArgumentNullException>(() => PerformanceCounterCategory.CounterExists(null, "Processor")); Assert.Throws<ArgumentNullException>(() => PerformanceCounterCategory.CounterExists("Interrupts/sec", null)); Assert.Throws<ArgumentException>(() => PerformanceCounterCategory.CounterExists("Interrupts/sec", string.Empty)); Assert.Throws<ArgumentException>(() => PerformanceCounterCategory.CounterExists("Interrupts/sec", "Processor", string.Empty)); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_DeleteCategory_Invalid() { Assert.Throws<InvalidOperationException>(() => PerformanceCounterCategory.Delete("Processor")); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_DeleteCategory() { var name = nameof(PerformanceCounterCategory_DeleteCategory) + "_Counter"; var category = Helpers.CreateCategory(name, PerformanceCounterCategoryType.SingleInstance); PerformanceCounterCategory.Delete(category); Assert.False(PerformanceCounterCategory.Exists(category)); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_Exists_Invalid() { Assert.Throws<ArgumentNullException>(() => PerformanceCounterCategory.Exists(null, ".")); Assert.Throws<ArgumentException>(() => PerformanceCounterCategory.Exists(string.Empty, ".")); Assert.Throws<ArgumentException>(() => PerformanceCounterCategory.Exists("Processor", string.Empty)); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_GetCounters() { var name = nameof(PerformanceCounterCategory_GetCounters) + "_Counter"; var category = Helpers.CreateCategory(name, PerformanceCounterCategoryType.SingleInstance); PerformanceCounterCategory pcc = Helpers.RetryOnAllPlatforms(() => new PerformanceCounterCategory(category)); PerformanceCounter[] counters = pcc.GetCounters(); Assert.True(counters.Length > 0); PerformanceCounterCategory.Delete(category); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_GetCounters_Invalid() { PerformanceCounterCategory pcc = new PerformanceCounterCategory(); Assert.Throws<ArgumentNullException>(() => pcc.GetCounters(null)); Assert.Throws<InvalidOperationException>(() => pcc.GetCounters(string.Empty)); pcc.CategoryName = "Processor"; Assert.Throws<InvalidOperationException>(() => pcc.GetCounters("Not An Instance")); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_GetInstanceNames_Invalid() { PerformanceCounterCategory pcc = new PerformanceCounterCategory(); Assert.Throws<InvalidOperationException>(() => pcc.GetInstanceNames()); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_InstanceExists_Invalid() { PerformanceCounterCategory pcc = new PerformanceCounterCategory(); Assert.Throws<ArgumentNullException>(() => pcc.InstanceExists(null)); Assert.Throws<InvalidOperationException>(() => pcc.InstanceExists("")); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_InstanceExists_Static() { PerformanceCounterCategory pcc = Helpers.RetryOnAllPlatforms(() => new PerformanceCounterCategory("Processor")); string[] instances = pcc.GetInstanceNames(); Assert.True(instances.Length > 0); foreach (string instance in instances) { Assert.True(PerformanceCounterCategory.InstanceExists(instance, "Processor")); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_InstanceExists_StaticInvalid() { Assert.Throws<ArgumentNullException>(() => PerformanceCounterCategory.InstanceExists(null, "Processor", ".")); Assert.Throws<ArgumentNullException>(() => PerformanceCounterCategory.InstanceExists("", null, ".")); Assert.Throws<ArgumentException>(() => PerformanceCounterCategory.InstanceExists("", string.Empty, ".")); Assert.Throws<ArgumentException>(() => PerformanceCounterCategory.InstanceExists("", "Processor", string.Empty)); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_ReadCategory() { PerformanceCounterCategory pcc = Helpers.RetryOnAllPlatforms(() => new PerformanceCounterCategory("Processor")); InstanceDataCollectionCollection idColCol = pcc.ReadCategory(); Assert.NotNull(idColCol); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounterCategory_ReadCategory_Invalid() { PerformanceCounterCategory pcc = new PerformanceCounterCategory(); Assert.Throws<InvalidOperationException>(() => pcc.ReadCategory()); } } }
// Authors: // Rafael Mizrahi <rafim@mainsoft.com> // Erez Lotan <erezl@mainsoft.com> // Oren Gurfinkel <oreng@mainsoft.com> // Ofer Borstein // // Copyright (c) 2004 Mainsoft Co. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Collections; using NUnit.Framework; namespace GHTUtils.Base { public class GHTBase { #region Constructors /// <summary>Constructor /// <param name="Logger">Custom TextWriter to log to</param> /// <param name="LogOnSuccess">False to log only failed TestCases, True to log all</param> /// </summary> protected GHTBase(TextWriter Logger, bool LogOnSuccess) { this._logger = Logger; this._logOnSuccess = LogOnSuccess; this._testName = this.GetType().Name; } /// <summary>Constructor, log to Console /// <param name="LogOnSuccess">False to log only failed TestCases, True to log all</param> /// </summary> protected GHTBase(bool LogOnSuccess):this(Console.Out, LogOnSuccess){} /// <summary>Constructor, log to Console only when Failed /// </summary> protected GHTBase():this(Console.Out, false){} #endregion #region protected methods public void GHTSetLogger(TextWriter Logger) { this._logger = Logger; } /// <summary>Begin Test which containes TestCases /// <param name="testName">Test name, used on logs</param> /// </summary> public virtual void BeginTest(string testName) { //set test name this._testName = testName; //reset the Failure Counter and the TestCase Number UniqueId.ResetCounters(); if(this._logOnSuccess == true) Log(string.Format("*** Starting Test: [{0}] ***", this._testName)); } /// <summary>Begin TestCase /// <param name="Description">TestCase Description, used on logs</param> /// </summary> public void BeginCase(string Description) { //init the new TestCase with Unique TestCase Number and Description _testCase = new UniqueId(Description); if(this._logOnSuccess == true) Log(string.Format("Starting Case: [{0}]", _testCase.ToString())); } /// <summary>Compare two objects (using Object.Equals) /// </summary> protected bool Compare(object a, object b) { //signal that the Compare method has been called if (_testCase == null) { _testCase = new UniqueId(_testName); } this._testCase.CompareInvoked = true; //a string that holds the description of the objects for log string ObjectData; //check if one of the objects is null if (a == null && b != null) { ObjectData = "Object a = null" + ", Object b.ToString() = '" + b.ToString() + "'(" + b.GetType().FullName + ")"; this._testCase.Success = false; //objects are different, TestCase Failed LogCompareResult(ObjectData); return this._testCase.Success; } //check if the other object is null if (a != null && b == null) { ObjectData = "Object a.ToString() = '" + a.ToString() + "'(" + a.GetType().FullName + "), Object b = null"; this._testCase.Success = false; //objects are different, TestCase Failed LogCompareResult(ObjectData); return this._testCase.Success; } //check if both objects are null if ( (a == null && b == null) ) { ObjectData = "Object a = null, Object b = null"; this._testCase.Success = true; //both objects are null, TestCase Succeed LogCompareResult(ObjectData); return this._testCase.Success; } ObjectData = "Object a.ToString() = '" + a.ToString() + "'(" + a.GetType().FullName + "), Object b.ToString = '" + b.ToString() + "'(" + b.GetType().FullName + ")"; //use Object.Equals to compare the objects this._testCase.Success = (a.Equals(b)); LogCompareResult(ObjectData); return this._testCase.Success; } /// <summary>Compare two Object Arrays. /// <param name="a">First array.</param> /// <param name="b">Second array.</param> /// <param name="Sorted">Used to indicate if both arrays are sorted.</param> /// </summary> protected bool Compare(Array a, Array b) { //signal that the Compare method has been called this._testCase.CompareInvoked=true; //a string that holds the description of the objects for log string ObjectData; //check if both objects are null if ( (a == null && b == null) ) { ObjectData = "Array a = null, Array b = null"; this._testCase.Success = true; //both objects are null, TestCase Succeed LogCompareResult(ObjectData); return this._testCase.Success; } //Check if one of the objects is null. //(If both were null, we wouldn't have reached here). if (a == null || b == null) { string aData = (a==null) ? "null" : "'" + a.ToString() + "' (" + a.GetType().FullName + ")"; string bData = (b==null) ? "null" : "'" +b.ToString() + "' (" + b.GetType().FullName + ")"; ObjectData = "Array a = " + aData + ", Array b = " + bData; this._testCase.Success = false; //objects are different, testCase Failed. LogCompareResult(ObjectData); return this._testCase.Success; } //check if both arrays are of the same rank. if (a.Rank != b.Rank) { this._testCase.Success = false; ObjectData = string.Format("Array a.Rank = {0}, Array b.Rank = {1}", a.Rank, b.Rank); LogCompareResult(ObjectData); return this._testCase.Success; } //Do not handle multi dimentional arrays. if (a.Rank != 1) { this._testCase.Success = false; ObjectData = "Multi-dimension array comparison is not supported"; LogCompareResult(ObjectData); return this._testCase.Success; } //Check if both arrays are of the same length. if (a.Length != b.Length) { this._testCase.Success = false; ObjectData = string.Format("Array a.Length = {0}, Array b.Length = {1}", a.Length, b.Length); LogCompareResult(ObjectData); return this._testCase.Success; } ObjectData = "Array a.ToString() = '" + a.ToString() + "'(" + a.GetType().FullName + ") Array b.ToString = '" + b.ToString() + "'(" + b.GetType().FullName + ")"; //Compare elements of the Array. int iLength = a.Length; for (int i=0; i<iLength; i++) { object aValue = a.GetValue(i); object bValue = b.GetValue(i); if (aValue == null && bValue == null) { continue; } if (aValue == null || bValue == null || !aValue.Equals(bValue) ) { string aData = (aValue==null) ? "null" : "'" + aValue.ToString() + "' (" + aValue.GetType().FullName + ")"; string bData = (bValue==null) ? "null" : "'" + bValue.ToString() + "' (" + bValue.GetType().FullName + ")"; ObjectData = string.Format("Array a[{0}] = {1}, Array b[{0}] = {2}", i, aData, bData); this._testCase.Success = false; //objects are different, testCase Failed. LogCompareResult(ObjectData); return this._testCase.Success; } } this._testCase.Success = true; LogCompareResult(ObjectData); return this._testCase.Success; } /// <summary> /// Intentionally fail a testcase, without calling the compare method. /// </summary> /// <param name="message">The reason for the failure.</param> protected void Fail(string message) { this._testCase.CompareInvoked = true; this._testCase.Success = false; string msg = string.Format("TestCase \"{0}\" Failed: [{1}]", _testCase.ToString(), message); if (_failAtTestEnd == null) Assert.Fail(msg); Log(msg); } /// <summary> /// Intentionally cause a testcase to pass, without calling the compare message. /// </summary> /// <param name="message">The reason for passing the test.</param> protected void Pass(string message) { this._testCase.CompareInvoked = true; this._testCase.Success = true; if (this._logOnSuccess) { Log(string.Format("TestCase \"{0}\" Passed: [{1}]", _testCase.ToString(), message)); } } /// <summary> /// Marks this testcase as success, but logs the reason for skipping regardless of _logOnSuccess value. /// </summary> /// <param name="message">The reason for skipping the test.</param> protected void Skip(string message) { this._testCase.CompareInvoked = true; this._testCase.Success = true; Log(string.Format("TestCase \"{0}\" Skipped: [{1}]", _testCase.ToString(), message)); } /// <summary> /// Intentionally fail a testcase when an expected exception is not thrown. /// </summary> /// <param name="exceptionName">The name of the expected exception type.</param> protected void ExpectedExceptionNotCaught(string exceptionName) { this.Fail(string.Format("Expected {0} was not caught.", exceptionName)); } /// <summary> /// Intentionally cause a testcase to pass, when an expected exception is thrown. /// </summary> /// <param name="ex"></param> protected void ExpectedExceptionCaught(Exception ex) { this.Pass(string.Format("Expected {0} was caught.", ex.GetType().FullName)); } /// <summary>End TestCase /// <param name="ex">Exception object if exception occured during the TestCase, null if not</param> /// </summary> protected void EndCase(Exception ex) { //check if BeginCase was called. cannot end an unopen TestCase if(_testCase == null) { throw new Exception("BeginCase was not called"); } else { // if Exception occured during the test - log the error and faile the TestCase. if(ex != null) { _testCase.Success=false; if (_failAtTestEnd == null) throw ex; Log(string.Format("TestCase: \"{0}\" Error: [Failed With Unexpected {1}: \n\t{2}]", _testCase.ToString(), ex.GetType().FullName, ex.Message + "\n" + ex.StackTrace )); } else { //check if Compare was called if (_testCase.CompareInvoked == true) { if(this._logOnSuccess == true) Log(string.Format("Finished Case: [{0}] ", _testCase.ToString())); } else { //if compare was not called, log error message //Log(string.Format("TestCase \"{0}\" Warning: [TestCase didn't invoke the Compare mehtod] ", _testCase.ToString())); } } //Terminate TestCase (set TestCase to null) _testCase = null; } } /// <summary>End Test /// <param name="ex">Exception object if exception occured during the Test, null if not</param> /// </summary> public void EndTest(Exception ex) { if (ex != null) throw ex; else if (UniqueId.FailureCounter != 0) Assert.Fail(String.Format("Test {0} failed in {1} scenarios.", this._testName, UniqueId.FailureCounter)); if(this._logOnSuccess) { Log(string.Format("*** Finished Test: [{0}] ***", this._testName)); } } public int GHTGetExitCode() { return UniqueId.FailureCounter; } /// <summary>logger /// <param name="text">string message to log</param> /// </summary> protected void Log(string text) { _loggerBuffer = _loggerBuffer + "\n" + "GHTBase:Logger - " + text; _logger.WriteLine("GHTBase:Logger - " + text); } //used to log the results from the compare methods private void LogCompareResult(string ObjectData) { if(this._testCase.Success == false) { string msg = string.Format("TeseCase \"{0}\" Error: [Failed while comparing(" + ObjectData + ")] ", _testCase.ToString() ); if (_failAtTestEnd == null) Assert.Fail(msg); Log("Test: " + _testName + " " + msg); } else if(this._logOnSuccess == true) Log(string.Format("TestCase \"{0}\" Passed ", _testCase.ToString())); } protected int TestCaseNumber { get { return _testCase.CaseNumber; } } #endregion #region private fields private TextWriter _logger; public string _loggerBuffer; // a public clone string of the _logger (used in web tests) private string _testName; private UniqueId _testCase; private bool _logOnSuccess; private string _failAtTestEnd = Environment.GetEnvironmentVariable("MONOTEST_FailAtTestEnd"); #endregion } //holds all the info on a TestCase internal class UniqueId { //holds the unique name of the test case //this name must be recieved from the test case itself //when calling BeginCase. //example: BeginCase("MyName") private string _caseName; //maintains the number generated for this test case private static int _caseNumber; //maintains the number of failed test case private static int _FailureCounter; internal static int FailureCounter { get { return _FailureCounter; } } //indicate if the Compare method has been invoked AND containes compare objects message (ToString) private bool _CompareInvoked; internal bool CompareInvoked { get { return _CompareInvoked; } set { _CompareInvoked = value; } } //reset the static counters when a new Test (not TestCase !!) begin internal static void ResetCounters() { _FailureCounter = 0; _caseNumber = 0; } //signal if a TestCase failed, if failed - increment the _FailureCounter private bool _success; internal bool Success { get { return this._success; } set { this._success = value; if (value == false) { _FailureCounter++; } } } //Ctor, Recieve the name for the test case //generate a unique number and apply it to the test case internal UniqueId(string Name) { this._caseName = Name; //this._caseNumber = ++UniqueId._counter; _caseNumber++; } internal int CaseNumber { get { return _caseNumber; } } public override string ToString() { return string.Format("{0} #{1}", this._caseName, _caseNumber); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Security.Authentication; using System.Web; using ASC.Common.Logging; using ASC.Core; using ASC.Core.Billing; using ASC.Core.Users; using ASC.Mail.Data.Contracts; using ASC.Mail.Exceptions; using ASC.Mail.Extensions; using ASC.Specific; using ASC.Web.Core; using DotNetOpenAuth.Messaging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using RestSharp; namespace ASC.Mail.Utils { public class ApiHelper { private const int MAIL_CRM_HISTORY_CATEGORY = -3; private const string ERR_MESSAGE = "Error retrieving response. Check inner details for more info."; private readonly ILog _log; public string Scheme { get; private set; } public UriBuilder BaseUrl { get; private set; } public string Token { get; set; } /// <summary> /// Constructor of class ApiHelper /// </summary> /// <param name="scheme">Uri.UriSchemeHttps or Uri.UriSchemeHttp</param> /// <exception cref="ApiHelperException">Exception happens when scheme is invalid.</exception>> public ApiHelper(string scheme, ILog log = null) { if (!scheme.Equals(Uri.UriSchemeHttps) && !scheme.Equals(Uri.UriSchemeHttp)) throw new ApiHelperException("ApiHelper: url scheme not setup", HttpStatusCode.InternalServerError, ""); _log = log ?? LogManager.GetLogger("ASC.Mail.ApiHelper"); Scheme = scheme; if (!scheme.Equals(Uri.UriSchemeHttps) || !Defines.SslCertificatesErrorPermit) return; ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; } private void Setup() { var tenant = CoreContext.TenantManager.GetCurrentTenant(); var user = SecurityContext.CurrentAccount; _log.DebugFormat("Tenant={0} User='{1}' IsAuthenticated={2} Scheme='{3}' HttpContext is {4}", tenant.TenantId, user.ID, user.IsAuthenticated, Scheme, HttpContext.Current != null ? string.Format("not null and UrlRewriter = {0}, RequestUrl = {1}", HttpContext.Current.Request.GetUrlRewriter(), HttpContext.Current.Request.Url) : "null"); if (!user.IsAuthenticated) throw new AuthenticationException("User not authenticated"); var tempUrl = Defines.ApiPrefix; var ubBase = new UriBuilder { Scheme = Scheme, Host = tenant.GetTenantDomain(false) }; if (!string.IsNullOrEmpty(Defines.ApiVirtualDirPrefix)) tempUrl = string.Format("{0}/{1}", Defines.ApiVirtualDirPrefix, tempUrl); if (!string.IsNullOrEmpty(Defines.ApiHost)) ubBase.Host = Defines.ApiHost; if (!string.IsNullOrEmpty(Defines.ApiPort)) ubBase.Port = int.Parse(Defines.ApiPort); ubBase.Path = tempUrl; BaseUrl = ubBase; Token = SecurityContext.AuthenticateMe(user.ID); } public IRestResponse Execute(RestRequest request) { Setup(); _log.DebugFormat("Execute request url: baseUrl='{0}' resourceUrl='{1}' token='{2}'", BaseUrl.Uri.ToString(), request.Resource, Token); var client = new RestClient { BaseUrl = BaseUrl.Uri }; request.AddHeader("Authorization", Token); var response = client.ExecuteSafe(request); if (response.ErrorException is ApiHelperException) return response; if (response.ErrorException != null) throw new ApplicationException(ERR_MESSAGE, response.ErrorException); return response; } public Defines.TariffType GetTenantTariff(int tenantOverdueDays) { var request = new RestRequest("portal/tariff.json", Method.GET); request.AddHeader("Payment-Info", "false"); var response = Execute(request); if (response.StatusCode == HttpStatusCode.PaymentRequired) return Defines.TariffType.LongDead; if (response.ResponseStatus != ResponseStatus.Completed || (response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.OK)) { throw new ApiHelperException("Get tenant tariff failed.", response.StatusCode, response.Content); } var json = JObject.Parse(response.Content); TariffState state; Enum.TryParse(json["response"]["state"].ToString(), out state); Defines.TariffType result; if (state < TariffState.NotPaid) { result = Defines.TariffType.Active; } else { var dueDate = DateTime.Parse(json["response"]["dueDate"].ToString()); var delayDateString = json["response"]["delayDueDate"].ToString(); var delayDueDate = DateTime.Parse(delayDateString); var maxDateStr = DateTime.MaxValue.CutToSecond().ToString(CultureInfo.InvariantCulture); delayDateString = delayDueDate.CutToSecond().ToString(CultureInfo.InvariantCulture); result = (!delayDateString.Equals(maxDateStr) ? delayDueDate : dueDate) .AddDays(tenantOverdueDays) <= DateTime.UtcNow ? Defines.TariffType.LongDead : Defines.TariffType.Overdue; } return result; } public void RemoveTeamlabMailbox(int mailboxId) { var request = new RestRequest("mailserver/mailboxes/remove/{id}", Method.DELETE); request.AddUrlSegment("id", mailboxId.ToString(CultureInfo.InvariantCulture)); var response = Execute(request); if (response.ResponseStatus != ResponseStatus.Completed || (response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.OK)) { throw new ApiHelperException("Delete teamlab mailbox failed.", response.StatusCode, response.Content); } } public void SendMessage(MailMessageData message, bool isAutoreply = false) { var request = new RestRequest("mail/messages/send.json", Method.PUT); var jObject = new JObject { { "id", message.Id } }; if (!string.IsNullOrEmpty(message.From)) jObject.Add("from", message.From); jObject.Add("to", message.To); if (!string.IsNullOrEmpty(message.Cc)) jObject.Add("cc", message.Cc); if (!string.IsNullOrEmpty(message.Bcc)) jObject.Add("bcc", message.Bcc); jObject.Add("subject", message.Subject); jObject.Add("body", message.HtmlBody); jObject.Add("mimeReplyToId", message.MimeReplyToId); jObject.Add("importance", message.Important); if (message.TagIds != null && message.TagIds.Count != 0) jObject.Add("tags", JsonConvert.SerializeObject(message.TagIds)); if (message.Attachments != null && message.Attachments.Count != 0) jObject.Add("attachments", JsonConvert.SerializeObject(message.Attachments)); if (!string.IsNullOrEmpty(message.CalendarEventIcs)) jObject.Add("calendarIcs", message.CalendarEventIcs); jObject.Add("isAutoreply", isAutoreply); request.AddParameter("application/json; charset=utf-8", jObject, ParameterType.RequestBody); var response = Execute(request); if (response.ResponseStatus == ResponseStatus.Completed && (response.StatusCode == HttpStatusCode.Created || response.StatusCode == HttpStatusCode.OK)) return; if (response.ErrorException is ApiHelperException) throw response.ErrorException; throw new ApiHelperException("Send message to api failed.", response.StatusCode, response.Content); } public List<string> SearchEmails(string term) { var request = new RestRequest("mail/emails/search.json", Method.GET); request.AddParameter("term", term); var response = Execute(request); if (response.ResponseStatus != ResponseStatus.Completed || (response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.OK)) { if (response.ErrorException is ApiHelperException) { throw response.ErrorException; } throw new ApiHelperException("Search Emails failed.", response.StatusCode, response.Content); } var json = JObject.Parse(response.Content); return json["response"].ToObject<List<string>>(); } public List<string> SearchCrmEmails(string term, int maxCount) { var request = new RestRequest("crm/contact/simple/byEmail.json", Method.GET); request.AddParameter("term", term) .AddParameter("maxCount", maxCount.ToString()); var response = Execute(request); var crmEmails = new List<string>(); var json = JObject.Parse(response.Content); var contacts = json["response"] as JArray; if (contacts == null) return crmEmails; foreach (var contact in contacts) { var commonData = contact["contact"]["commonData"] as JArray; if (commonData == null) continue; var emails = commonData.Where(d => int.Parse(d["infoType"].ToString()) == 1).Select(d => (string)d["data"]).ToList(); if (!emails.Any()) continue; var displayName = contact["contact"]["displayName"].ToString(); if (displayName.IndexOf(term, StringComparison.OrdinalIgnoreCase) > -1) { crmEmails.AddRange(emails.Select(e => MailUtil.CreateFullEmail(displayName, e))); } else { crmEmails.AddRange(emails .Where(e => e.IndexOf(term, StringComparison.OrdinalIgnoreCase) > -1) .Select(e => MailUtil.CreateFullEmail(displayName, e))); } } return crmEmails; } public List<string> SearchPeopleEmails(string term, int startIndex, int count) { var request = new RestRequest("people/filter.json?filterValue={FilterValue}&StartIndex={StartIndex}&Count={Count}", Method.GET); request.AddParameter("FilterValue", term, ParameterType.UrlSegment) .AddParameter("StartIndex", startIndex.ToString(), ParameterType.UrlSegment) .AddParameter("Count", count.ToString(), ParameterType.UrlSegment); var response = Execute(request); var peopleEmails = new List<string>(); var json = JObject.Parse(response.Content); var contacts = json["response"] as JArray; if (contacts == null) return peopleEmails; foreach (var contact in contacts) { var displayName = contact["displayName"].ToString(); var emails = new List<string>(); var email = contact["email"].ToString(); if (!string.IsNullOrEmpty(email)) emails.Add(email); var contactData = contact["contacts"] as JArray; if (contactData != null) { emails.AddRange(contactData.Where(d => d["type"].ToString() == "mail").Select(d => (string)d["value"]).ToList()); } if (displayName.IndexOf(term, StringComparison.OrdinalIgnoreCase) > -1) { peopleEmails.AddRange(emails.Select(e => MailUtil.CreateFullEmail(displayName, e))); } else { peopleEmails.AddRange(emails .Where(e => e.IndexOf(term, StringComparison.OrdinalIgnoreCase) > -1) .Select(e => MailUtil.CreateFullEmail(displayName, e))); } } return peopleEmails; } public void AddToCrmHistory(MailMessageData message, CrmContactData entity, IEnumerable<object> fileIds) { var request = new RestRequest("crm/history.json", Method.POST); var contentJson = string.Format("{{ message_id : {0} }}", message.Id); request.AddParameter("content", contentJson) .AddParameter("categoryId", MAIL_CRM_HISTORY_CATEGORY) .AddParameter("created", new ApiDateTime(message.Date)); var crmEntityType = entity.EntityTypeName; if (crmEntityType == CrmContactData.CrmEntityTypeNames.CONTACT) { request.AddParameter("contactId", entity.Id) .AddParameter("entityId", 0); } else { if (crmEntityType != CrmContactData.CrmEntityTypeNames.CASE && crmEntityType != CrmContactData.CrmEntityTypeNames.OPPORTUNITY) throw new ArgumentException(String.Format("Invalid crm entity type: {0}", crmEntityType)); request.AddParameter("contactId", 0) .AddParameter("entityId", entity.Id) .AddParameter("entityType", crmEntityType); } if (fileIds != null) { fileIds.ToList().ForEach( id => request.AddParameter("fileId[]", id)); } var response = Execute(request); if (response.ResponseStatus == ResponseStatus.Completed && (response.StatusCode == HttpStatusCode.Created || response.StatusCode == HttpStatusCode.OK)) return; if (response.ErrorException is ApiHelperException) throw response.ErrorException; throw new ApiHelperException("Add message to crm history failed.", response.StatusCode, response.Content); } public object UploadToCrm(Stream fileStream, string filename, string contentType, CrmContactData entity) { if (entity == null) throw new ArgumentNullException("entity"); var request = new RestRequest("crm/{entityType}/{entityId}/files/upload.json", Method.POST); request.AddUrlSegment("entityType", entity.EntityTypeName) .AddUrlSegment("entityId", entity.Id.ToString()) .AddParameter("storeOriginalFileFlag", false); request.AddFile(filename, fileStream.CopyTo, filename, fileStream.Length, contentType); var response = Execute(request); if (response.ResponseStatus != ResponseStatus.Completed || (response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.OK)) { throw new ApiHelperException("Upload file to crm failed.", response.StatusCode, response.Content); } var json = JObject.Parse(response.Content); var id = json["response"]["id"]; return id; } public object UploadToDocuments(Stream fileStream, string filename, string contentType, string folderId, bool createNewIfExist) { var request = new RestRequest("files/{folderId}/upload.json", Method.POST); request.AddUrlSegment("folderId", folderId) .AddParameter("createNewIfExist", createNewIfExist); request.AddFile(filename, fileStream.CopyTo, filename, fileStream.Length, contentType); var response = Execute(request); if (response.ResponseStatus != ResponseStatus.Completed || (response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.OK)) { throw new ApiHelperException("Upload file to documents failed.", response.StatusCode, response.Content); } var json = JObject.Parse(response.Content); var id = json["response"]["id"]; return id; } //TODO: need refactoring to comman execute method public void SendEmlToSpamTrainer(string serverIp, string serverProtocol, int serverPort, string serverApiVersion, string serverApiToken, string urlEml, bool isSpam) { if (string.IsNullOrEmpty(urlEml)) return; var saLearnApiClient = new RestClient(string.Format("{0}://{1}:{2}/", serverProtocol, serverIp, serverPort)); var saLearnRequest = new RestRequest( string.Format("/api/{0}/spam/training.json?auth_token={1}", serverApiVersion, serverApiToken), Method.POST); saLearnRequest.AddParameter("url", urlEml) .AddParameter("is_spam", isSpam ? 1 : 0); var response = saLearnApiClient.Execute(saLearnRequest); if (response.ResponseStatus != ResponseStatus.Completed || (response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.OK)) { throw new ApiHelperException("Send eml to spam trainer failed.", response.StatusCode, response.Content); } } public void UploadIcsToCalendar(int calendarId, Stream fileStream, string filename, string contentType) { var request = new RestRequest("calendar/import.json", Method.POST); request.AddParameter("calendarId", calendarId); request.AddFile(filename, fileStream.CopyTo, filename, fileStream.Length, contentType); var response = Execute(request); if (response.ResponseStatus != ResponseStatus.Completed || (response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.OK)) { throw new ApiHelperException("Upload ics-file to calendar failed.", response.StatusCode, response.Content); } var json = JObject.Parse(response.Content); int count; if (!int.TryParse(json["response"].ToString(), out count)) { _log.WarnFormat("Upload ics-file to calendar failed. No count number.", BaseUrl.ToString(), response.StatusCode, response.Content); } } public UserInfo CreateEmployee(bool isVisitor, string email, string firstname, string lastname, string password) { var request = new RestRequest("people.json", Method.POST); request.AddParameter("isVisitor", isVisitor) .AddParameter("email", email) .AddParameter("firstname", firstname) .AddParameter("lastname", lastname) .AddParameter("password", password); var response = Execute(request); if (response.ResponseStatus != ResponseStatus.Completed || (response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.OK)) { throw new ApiHelperException("ApiHelper->CreateEmployee() failed.", response.StatusCode, response.Content); } var json = JObject.Parse(response.Content); _log.Debug(json["response"].ToString()); var userInfo = new UserInfo { ID = Guid.Parse(json["response"]["id"].ToString()), Email = json["response"]["email"].ToString(), FirstName = json["response"]["firstName"].ToString(), LastName = json["response"]["lastName"].ToString(), UserName = json["response"]["userName"].ToString(), }; return userInfo; } public JObject GetPortalSettings() { var request = new RestRequest("settings/security.json", Method.GET); var response = Execute(request); if (response.ResponseStatus != ResponseStatus.Completed || (response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.OK)) { throw new ApiHelperException("GetPortalSettings failed.", response.StatusCode, response.Content); } var json = JObject.Parse(response.Content); return json; } public bool IsCalendarModuleAvailable() { var json = GetPortalSettings(); var jWebItem = json["response"].Children<JObject>() .FirstOrDefault( o => o["webItemId"] != null && o["webItemId"].ToString() == WebItemManager.CalendarProductID.ToString()); var isAvailable = jWebItem != null && jWebItem["enabled"] != null && Convert.ToBoolean(jWebItem["enabled"]); return isAvailable; } public bool IsMailModuleAvailable() { var json = GetPortalSettings(); var jWebItem = json["response"].Children<JObject>() .FirstOrDefault( o => o["webItemId"] != null && o["webItemId"].ToString() == WebItemManager.MailProductID.ToString()); var isAvailable = jWebItem != null && jWebItem["enabled"] != null && Convert.ToBoolean(jWebItem["enabled"]); return isAvailable; } public bool IsCrmModuleAvailable() { var json = GetPortalSettings(); var crmId = WebItemManager.CRMProductID.ToString(); var jWebItem = json["response"].Children<JObject>() .FirstOrDefault( o => o["webItemId"] != null && o["webItemId"].ToString() == crmId); var isAvailable = jWebItem != null && jWebItem["enabled"] != null && Convert.ToBoolean(jWebItem["enabled"]); return isAvailable; } } }
using System.Configuration; using DbMigrations.Client.Configuration; using DbMigrations.Client.Infrastructure; namespace DbMigrations.Client.Resources { public class DbQueries { public static DbQueries Get(Config config) { var c = (DbMigrationsConfigurationSection) ConfigurationManager.GetSection("migrationConfig"); if (!string.IsNullOrEmpty(c?.InvariantName)) return FromConfigurationSection(c); if (config.ProviderName.StartsWith("Oracle")) { return Oracle.Instance(config); } if (config.ProviderName.Contains("SqLite")) { return SqLite.Instance(); } if (config.ProviderName.Contains("SqlServerCe")) { return SqlServerCe.Instance(); } return SqlServer.Instance(config); } private static DbQueries FromConfigurationSection(DbMigrationsConfigurationSection config) { if (string.IsNullOrEmpty(config?.InvariantName)) return null; return new DbQueries( config.InvariantName, config.EscapeChar, config.TableName, config.Schema, config.ConfigureTransaction?.Sql ?? string.Empty, config.CreateMigrationTable?.Sql ?? string.Empty, config.CountMigrationTables?.Sql ?? string.Empty, config.DropAllObjects?.Sql ?? string.Empty ); } public DbQueries(string invariantName, string escapeCharacter, string tableName, string schema, string configureTransactionStatement, string createTableTemplate, string countMigrationTablesStatement, string dropAllObjectsStatement) { InvariantName = invariantName; EscapeCharacter = escapeCharacter; TableName = tableName; Schema = schema; ConfigureTransactionStatement = configureTransactionStatement; CreateTableTemplate = createTableTemplate; CountMigrationTablesStatement = countMigrationTablesStatement; DropAllObjectsStatement = dropAllObjectsStatement; } private string InsertTemplate { get; } = "INSERT INTO {TableName} (ScriptName, MD5, ExecutedOn, Content) " + "VALUES ({EscapeCharacter}ScriptName, {EscapeCharacter}MD5, {EscapeCharacter}ExecutedOn, {EscapeCharacter}Content)" ; private string SelectTemplate { get; } = "SELECT ScriptName, MD5, ExecutedOn, Content " + "FROM {TableName} " + "ORDER BY ScriptName ASC"; public string TableName { get; } public string Schema { get; } private string InvariantName { get; } public string EscapeCharacter { get; } public string ConfigureTransactionStatement { get; } private string CreateTableTemplate { get; } public string CountMigrationTablesStatement { get; } public string DropAllObjectsStatement { get; } public string InsertStatement => InsertTemplate.FormatWith(new {TableName, EscapeCharacter}); public string SelectStatement => SelectTemplate.FormatWith(new {TableName}); public string CreateTableStatement => CreateTableTemplate.FormatWith(new {TableName}); public void SaveToConfig(DbMigrationsConfigurationSection config) { config.InvariantName = InvariantName; config.TableName = TableName; config.Schema = Schema; config.EscapeChar = EscapeCharacter; config.CountMigrationTables.Sql = CountMigrationTablesStatement; config.DropAllObjects.Sql = DropAllObjectsStatement; config.ConfigureTransaction.Sql = ConfigureTransactionStatement; config.CreateMigrationTable.Sql = CreateTableTemplate; } #region Implementations private static class SqlServer { public static DbQueries Instance(Config config) { var schema = config.Schema ?? "dbo"; var tableName = $"{schema}.Migrations"; var invariantName = "System.Data.SqlClient"; var escapeCharacter = "@"; var initTransaction = "SET XACT_ABORT ON"; return new DbQueries( invariantName, escapeCharacter, tableName, schema, initTransaction, CreateTableTemplate, CountMigrationTablesStatement, DropAllObjectsStatement); } private static string CountMigrationTablesStatement = "SELECT COUNT(*) \r\n" + "FROM INFORMATION_SCHEMA.TABLES \r\n" + "WHERE TABLE_NAME = @TableName AND TABLE_SCHEMA = @Schema\r\n"; private static string CreateTableTemplate = "CREATE TABLE {TableName} (\r\n" + " ScriptName nvarchar(255) NOT NULL, \r\n" + " MD5 nvarchar(32) NOT NULL, \r\n" + " ExecutedOn datetime NOT NULL,\r\n" + " Content nvarchar(max) NOT NULL\r\n" + " CONSTRAINT PK_Migrations PRIMARY KEY CLUSTERED (ScriptName ASC)\r\n" + " )"; private static string DropAllObjectsStatement = "-- procedures\r\n" + "SELECT \'DROP PROCEDURE [\' + schema_name(schema_id) + \'].[\' + name + \']\' [Statement]\r\n" + "FROM sys.procedures\r\n" + "UNION ALL\r\n" + "-- check constraints\r\n" + "SELECT \'ALTER TABLE [\' + schema_name(schema_id) + \'].[\' + object_name( parent_object_id ) + \'] drop constraint [\' + name + \']\'\r\n" + "FROM sys.check_constraints\r\n" + "UNION ALL\r\n" + "-- views\r\n" + "SELECT \'DROP VIEW [\' + schema_name(schema_id) + \'].[\' + name + \']\'\r\n" + "FROM sys.views\r\n" + "UNION ALL\r\n" + "-- foreign keys\r\n" + "SELECT \'ALTER TABLE [\' + schema_name(schema_id) + \'].[\' + object_name( parent_object_id ) + \'] drop constraint [\' + name + \']\'\r\n" + "FROM sys.foreign_keys\r\n" + "UNION ALL\r\n" + "-- tables\r\n" + "SELECT \'DROP TABLE [\' + schema_name(schema_id) + \'].[\' + name + \']\'\r\n" + "FROM sys.tables\r\n" + "UNION ALL\r\n" + "-- functions\r\n" + "SELECT \'DROP FUNCTION [\' + schema_name(schema_id) + \'].[\' + name + \']\'\r\n" + "FROM sys.objects\r\n" + "WHERE type IN ( \'FN\', \'IF\', \'TF\' )\r\n" + "UNION ALL\r\n" + "-- user defined types\r\n" + "SELECT \'DROP TYPE [\' + schema_name(schema_id) + \'].[\' + name + \']\'\r\n" + "FROM sys.types\r\n" + "WHERE is_user_defined = 1"; } private static class Oracle { public static DbQueries Instance(Config config) { var schema = config.Schema ?? config.UserName; var tableName = $"{schema}.MIGRATIONS"; var invariantName = "Oracle.ManagedDataAccess.Client"; var escapeCharacter = ":"; return new DbQueries( invariantName, escapeCharacter, tableName, schema, string.Empty, CreateTableTemplate, CountMigrationTablesStatement, DropAllObjectsStatement); } private static string CountMigrationTablesStatement = "SELECT COUNT(*) \r\n" + "FROM ALL_TABLES \r\n" + "WHERE UPPER(TABLE_NAME) = :TableName and OWNER = :Schema"; private static string CreateTableTemplate = "CREATE TABLE {TableName} (\r\n" + " ScriptName nvarchar2(255) not null, \r\n" + " MD5 nvarchar2(32) not null, \r\n" + " ExecutedOn date not null, \r\n" + " Content CLOB not null, \r\n" + " CONSTRAINT PK_Migrations PRIMARY KEY (ScriptName)\r\n" + ")"; static string DropAllObjectsStatement = "SELECT 'DROP TABLE '|| TABLE_NAME || ' CASCADE CONSTRAINTS' as Statement \r\n" + "FROM USER_TABLES \r\n" + "UNION ALL \r\n" + "SELECT 'DROP '||OBJECT_TYPE||' '|| OBJECT_NAME as Statement \r\n" + "FROM USER_OBJECTS \r\n" + "WHERE OBJECT_TYPE IN ('VIEW', 'PACKAGE', 'SEQUENCE', 'PROCEDURE', 'FUNCTION' )"; } private static class SqLite { public static DbQueries Instance() { return new DbQueries( "System.Data.SqLite", "@", "Migrations", string.Empty, string.Empty , CreateTableTemplate , CountMigrationTablesStatement , DropAllObjectsStatement); } private static string CountMigrationTablesStatement = "SELECT COUNT(*) \r\n" + "FROM sqlite_master \r\n" + "WHERE type = 'table' AND name = @TableName"; private static string CreateTableTemplate = "CREATE TABLE IF NOT EXISTS {TableName} (\r\n" + " ScriptName nvarchar NOT NULL PRIMARY KEY, \r\n" + " MD5 nvarchar NOT NULL, \r\n" + " ExecutedOn datetime NOT NULL,\r\n" + " Content nvarchar NOT NULL\r\n" + " )"; private static string DropAllObjectsStatement = "SELECT 'DROP TABLE ' || name || ';' AS \"Statement\" \r\n" + "FROM SQLITE_MASTER \r\n" + "WHERE TYPE = 'table';"; } private static class SqlServerCe { public static DbQueries Instance() { var invariantName = "System.Data.SqlServerCe.4.0"; var escapeCharacter = "@"; var tableName = "Migrations"; return new DbQueries( invariantName, escapeCharacter, tableName, string.Empty, string.Empty , CreateTableTemplate , CountMigrationTablesStatement , DropAllObjectsStatement); } private static string CountMigrationTablesStatement = "SELECT COUNT(*) \r\n" + "FROM INFORMATION_SCHEMA.TABLES \r\n" + "WHERE TABLE_NAME = @TableName"; private static string CreateTableTemplate = "CREATE TABLE {TableName} (\r\n" + " ScriptName nvarchar(255) NOT NULL PRIMARY KEY, \r\n" + " MD5 nvarchar(32) NOT NULL, \r\n" + " ExecutedOn datetime NOT NULL,\r\n" + " Content ntext NOT NULL\r\n" + " )"; private static string DropAllObjectsStatement = "-- tables\r\n" + "SELECT \'DROP TABLE [\' + table_name + \']\' as Statement \r\n" + "FROM information_schema.tables"; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: Exposes features of the Garbage Collector through ** the class libraries. This is a class which cannot be ** instantiated. ** ** ===========================================================*/ //This class only static members and doesn't require the serializable keyword. using System; using System.Reflection; using System.Security; using System.Threading; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System { [Serializable] public enum GCCollectionMode { Default = 0, Forced = 1, Optimized = 2 } // !!!!!!!!!!!!!!!!!!!!!!! // make sure you change the def in vm\gc.h // if you change this! [Serializable] internal enum InternalGCCollectionMode { NonBlocking = 0x00000001, Blocking = 0x00000002, Optimized = 0x00000004, Compacting = 0x00000008, } // !!!!!!!!!!!!!!!!!!!!!!! // make sure you change the def in vm\gc.h // if you change this! [Serializable] public enum GCNotificationStatus { Succeeded = 0, Failed = 1, Canceled = 2, Timeout = 3, NotApplicable = 4 } public static class GC { [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int GetGCLatencyMode(); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int SetGCLatencyMode(int newLatencyMode); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern int _StartNoGCRegion(long totalSize, bool lohSizeKnown, long lohSize, bool disallowFullBlockingGC); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern int _EndNoGCRegion(); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int GetLOHCompactionMode(); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void SetLOHCompactionMode(int newLOHCompactionMode); [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int GetGenerationWR(IntPtr handle); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern long GetTotalMemory(); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void _Collect(int generation, int mode); [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int GetMaxGeneration(); [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int _CollectionCount(int generation, int getSpecialGCCount); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern bool IsServerGC(); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern void _AddMemoryPressure(UInt64 bytesAllocated); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern void _RemoveMemoryPressure(UInt64 bytesAllocated); public static void AddMemoryPressure(long bytesAllocated) { if (bytesAllocated <= 0) { throw new ArgumentOutOfRangeException(nameof(bytesAllocated), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } if ((4 == IntPtr.Size) && (bytesAllocated > Int32.MaxValue)) { throw new ArgumentOutOfRangeException("pressure", Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegInt32")); } Contract.EndContractBlock(); _AddMemoryPressure((ulong)bytesAllocated); } public static void RemoveMemoryPressure(long bytesAllocated) { if (bytesAllocated <= 0) { throw new ArgumentOutOfRangeException(nameof(bytesAllocated), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } if ((4 == IntPtr.Size) && (bytesAllocated > Int32.MaxValue)) { throw new ArgumentOutOfRangeException(nameof(bytesAllocated), Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegInt32")); } Contract.EndContractBlock(); _RemoveMemoryPressure((ulong)bytesAllocated); } // Returns the generation that obj is currently in. // [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int GetGeneration(Object obj); // Forces a collection of all generations from 0 through Generation. // public static void Collect(int generation) { Collect(generation, GCCollectionMode.Default); } // Garbage Collect all generations. // public static void Collect() { //-1 says to GC all generations. _Collect(-1, (int)InternalGCCollectionMode.Blocking); } public static void Collect(int generation, GCCollectionMode mode) { Collect(generation, mode, true); } public static void Collect(int generation, GCCollectionMode mode, bool blocking) { Collect(generation, mode, blocking, false); } public static void Collect(int generation, GCCollectionMode mode, bool blocking, bool compacting) { if (generation < 0) { throw new ArgumentOutOfRangeException(nameof(generation), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); } if ((mode < GCCollectionMode.Default) || (mode > GCCollectionMode.Optimized)) { throw new ArgumentOutOfRangeException(nameof(mode), Environment.GetResourceString("ArgumentOutOfRange_Enum")); } Contract.EndContractBlock(); int iInternalModes = 0; if (mode == GCCollectionMode.Optimized) { iInternalModes |= (int)InternalGCCollectionMode.Optimized; } if (compacting) iInternalModes |= (int)InternalGCCollectionMode.Compacting; if (blocking) { iInternalModes |= (int)InternalGCCollectionMode.Blocking; } else if (!compacting) { iInternalModes |= (int)InternalGCCollectionMode.NonBlocking; } _Collect(generation, iInternalModes); } public static int CollectionCount(int generation) { if (generation < 0) { throw new ArgumentOutOfRangeException(nameof(generation), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); } Contract.EndContractBlock(); return _CollectionCount(generation, 0); } // This method DOES NOT DO ANYTHING in and of itself. It's used to // prevent a finalizable object from losing any outstanding references // a touch too early. The JIT is very aggressive about keeping an // object's lifetime to as small a window as possible, to the point // where a 'this' pointer isn't considered live in an instance method // unless you read a value from the instance. So for finalizable // objects that store a handle or pointer and provide a finalizer that // cleans them up, this can cause subtle race conditions with the finalizer // thread. This isn't just about handles - it can happen with just // about any finalizable resource. // // Users should insert a call to this method right after the last line // of their code where their code still needs the object to be kept alive. // The object which reference is passed into this method will not // be eligible for collection until the call to this method happens. // Once the call to this method has happened the object may immediately // become eligible for collection. Here is an example: // // "...all you really need is one object with a Finalize method, and a // second object with a Close/Dispose/Done method. Such as the following // contrived example: // // class Foo { // Stream stream = ...; // protected void Finalize() { stream.Close(); } // void Problem() { stream.MethodThatSpansGCs(); } // static void Main() { new Foo().Problem(); } // } // // // In this code, Foo will be finalized in the middle of // stream.MethodThatSpansGCs, thus closing a stream still in use." // // If we insert a call to GC.KeepAlive(this) at the end of Problem(), then // Foo doesn't get finalized and the stream stays open. [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations public static void KeepAlive(Object obj) { } // Returns the generation in which wo currently resides. // public static int GetGeneration(WeakReference wo) { int result = GetGenerationWR(wo.m_handle); KeepAlive(wo); return result; } // Returns the maximum GC generation. Currently assumes only 1 heap. // public static int MaxGeneration { get { return GetMaxGeneration(); } } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void _WaitForPendingFinalizers(); public static void WaitForPendingFinalizers() { // QCalls can not be exposed from mscorlib directly, need to wrap it. _WaitForPendingFinalizers(); } // Indicates that the system should not call the Finalize() method on // an object that would normally require this call. [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _SuppressFinalize(Object o); public static void SuppressFinalize(Object obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); Contract.EndContractBlock(); _SuppressFinalize(obj); } // Indicates that the system should call the Finalize() method on an object // for which SuppressFinalize has already been called. The other situation // where calling ReRegisterForFinalize is useful is inside a finalizer that // needs to resurrect itself or an object that it references. [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _ReRegisterForFinalize(Object o); public static void ReRegisterForFinalize(Object obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); Contract.EndContractBlock(); _ReRegisterForFinalize(obj); } // Returns the total number of bytes currently in use by live objects in // the GC heap. This does not return the total size of the GC heap, but // only the live objects in the GC heap. // public static long GetTotalMemory(bool forceFullCollection) { long size = GetTotalMemory(); if (!forceFullCollection) return size; // If we force a full collection, we will run the finalizers on all // existing objects and do a collection until the value stabilizes. // The value is "stable" when either the value is within 5% of the // previous call to GetTotalMemory, or if we have been sitting // here for more than x times (we don't want to loop forever here). int reps = 20; // Number of iterations long newSize = size; float diff; do { GC.WaitForPendingFinalizers(); GC.Collect(); size = newSize; newSize = GetTotalMemory(); diff = ((float)(newSize - size)) / size; } while (reps-- > 0 && !(-.05 < diff && diff < .05)); return newSize; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern long _GetAllocatedBytesForCurrentThread(); public static long GetAllocatedBytesForCurrentThread() { return _GetAllocatedBytesForCurrentThread(); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool _RegisterForFullGCNotification(int maxGenerationPercentage, int largeObjectHeapPercentage); [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool _CancelFullGCNotification(); [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int _WaitForFullGCApproach(int millisecondsTimeout); [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int _WaitForFullGCComplete(int millisecondsTimeout); public static void RegisterForFullGCNotification(int maxGenerationThreshold, int largeObjectHeapThreshold) { if ((maxGenerationThreshold <= 0) || (maxGenerationThreshold >= 100)) { throw new ArgumentOutOfRangeException(nameof(maxGenerationThreshold), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"), 1, 99)); } if ((largeObjectHeapThreshold <= 0) || (largeObjectHeapThreshold >= 100)) { throw new ArgumentOutOfRangeException(nameof(largeObjectHeapThreshold), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"), 1, 99)); } if (!_RegisterForFullGCNotification(maxGenerationThreshold, largeObjectHeapThreshold)) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotWithConcurrentGC")); } } public static void CancelFullGCNotification() { if (!_CancelFullGCNotification()) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotWithConcurrentGC")); } } public static GCNotificationStatus WaitForFullGCApproach() { return (GCNotificationStatus)_WaitForFullGCApproach(-1); } public static GCNotificationStatus WaitForFullGCApproach(int millisecondsTimeout) { if (millisecondsTimeout < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); return (GCNotificationStatus)_WaitForFullGCApproach(millisecondsTimeout); } public static GCNotificationStatus WaitForFullGCComplete() { return (GCNotificationStatus)_WaitForFullGCComplete(-1); } public static GCNotificationStatus WaitForFullGCComplete(int millisecondsTimeout) { if (millisecondsTimeout < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); return (GCNotificationStatus)_WaitForFullGCComplete(millisecondsTimeout); } private enum StartNoGCRegionStatus { Succeeded = 0, NotEnoughMemory = 1, AmountTooLarge = 2, AlreadyInProgress = 3 } private enum EndNoGCRegionStatus { Succeeded = 0, NotInProgress = 1, GCInduced = 2, AllocationExceeded = 3 } private static bool StartNoGCRegionWorker(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC) { StartNoGCRegionStatus status = (StartNoGCRegionStatus)_StartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC); if (status == StartNoGCRegionStatus.AmountTooLarge) throw new ArgumentOutOfRangeException(nameof(totalSize), "totalSize is too large. For more information about setting the maximum size, see \"Latency Modes\" in http://go.microsoft.com/fwlink/?LinkId=522706"); else if (status == StartNoGCRegionStatus.AlreadyInProgress) throw new InvalidOperationException("The NoGCRegion mode was already in progress"); else if (status == StartNoGCRegionStatus.NotEnoughMemory) return false; return true; } public static bool TryStartNoGCRegion(long totalSize) { return StartNoGCRegionWorker(totalSize, false, 0, false); } public static bool TryStartNoGCRegion(long totalSize, long lohSize) { return StartNoGCRegionWorker(totalSize, true, lohSize, false); } public static bool TryStartNoGCRegion(long totalSize, bool disallowFullBlockingGC) { return StartNoGCRegionWorker(totalSize, false, 0, disallowFullBlockingGC); } public static bool TryStartNoGCRegion(long totalSize, long lohSize, bool disallowFullBlockingGC) { return StartNoGCRegionWorker(totalSize, true, lohSize, disallowFullBlockingGC); } private static EndNoGCRegionStatus EndNoGCRegionWorker() { EndNoGCRegionStatus status = (EndNoGCRegionStatus)_EndNoGCRegion(); if (status == EndNoGCRegionStatus.NotInProgress) throw new InvalidOperationException("NoGCRegion mode must be set"); else if (status == EndNoGCRegionStatus.GCInduced) throw new InvalidOperationException("Garbage collection was induced in NoGCRegion mode"); else if (status == EndNoGCRegionStatus.AllocationExceeded) throw new InvalidOperationException("Allocated memory exceeds specified memory for NoGCRegion mode"); return EndNoGCRegionStatus.Succeeded; } public static void EndNoGCRegion() { EndNoGCRegionWorker(); } } }
/* * This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson, * the work of Kim Sheffield and the fyiReporting project. * * Prior Copyrights: * _________________________________________________________ * |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others| * | (http://reportfu.org) | * ========================================================= * _________________________________________________________ * |Copyright (C) 2004-2008 fyiReporting Software, LLC | * |For additional information, email info@fyireporting.com | * |or visit the website www.fyiReporting.com. | * ========================================================= * * License: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.ComponentModel; // need this for the properties metadata using System.Drawing.Design; using System.Xml; using System.Globalization; using System.Windows.Forms; using System.Windows.Forms.Design; namespace Reporting.RdlDesign { /// <summary> /// PropertyAction - /// </summary> [TypeConverter(typeof(PropertyBackgroundConverter)), Editor(typeof(PropertyBackgroundUIEditor), typeof(System.Drawing.Design.UITypeEditor))] internal class PropertyBackground : IReportItem { PropertyReportItem pri; string[] _names; string[] _subitems; internal PropertyBackground(PropertyReportItem ri) { pri = ri; _names = null; _subitems = new string[] { "Style", "" }; } internal PropertyBackground(PropertyReportItem ri, params string[] names) { pri = ri; _names = names; // now build the array used to get/set values _subitems = new string[names.Length + 2]; int i = 0; foreach (string s in names) _subitems[i++] = s; _subitems[i++] = "Style"; } internal PropertyReportItem RI { get { return pri; } } internal string[] Names { get { return _names; } } [RefreshProperties(RefreshProperties.Repaint), TypeConverter(typeof(ColorConverter)), DescriptionAttribute("Background color.")] public string Color { get { return GetStyleValue("BackgroundColor", ""); } set { SetStyleValue("BackgroundColor", value); } } [RefreshProperties(RefreshProperties.Repaint), TypeConverter(typeof(ColorConverter)), DescriptionAttribute("End color when gradient type is not None.")] public string EndColor { get { return GetStyleValue("BackgroundGradientEndColor", ""); } set { SetStyleValue("BackgroundGradientEndColor", value); } } [RefreshProperties(RefreshProperties.Repaint), TypeConverter(typeof(GradientTypeConverter)), DescriptionAttribute("Type of background gradient.")] public string GradientType { get { return GetStyleValue("BackgroundGradientType", "None"); } set { SetStyleValue("BackgroundGradientType", value); } } [DescriptionAttribute("Image to place in the background of the report item")] public PropertyBackgroundImage Image { get { return new PropertyBackgroundImage(pri, _names); } } private string GetStyleValue(string l1, string def) { _subitems[_subitems.Length - 1] = l1; return pri.GetWithList(def, _subitems); } private void SetStyleValue(string l1, string val) { _subitems[_subitems.Length - 1] = l1; pri.SetWithList(val, _subitems); } public override string ToString() { return GetStyleValue("BackgroundColor", ""); } #region IReportItem Members public PropertyReportItem GetPRI() { return pri; } #endregion } internal class PropertyBackgroundConverter : ExpandableObjectConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(PropertyBackground)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value is PropertyBackground) { PropertyBackground pf = value as PropertyBackground; return pf.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } internal class PropertyBackgroundUIEditor : UITypeEditor { internal PropertyBackgroundUIEditor() { } public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if ((context == null) || (provider == null)) return base.EditValue(context, provider, value); // Access the Property Browser's UI display service IWindowsFormsEditorService editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (editorService == null) return base.EditValue(context, provider, value); // Create an instance of the UI editor form IReportItem iri = context.Instance as IReportItem; if (iri == null) return base.EditValue(context, provider, value); PropertyReportItem pre = iri.GetPRI(); string[] names; PropertyBackground pb = value as PropertyBackground; if (pb != null) names = pb.Names; else { PropertyBackgroundImage pbi = value as PropertyBackgroundImage; if (pbi == null) return base.EditValue(context, provider, value); names = pbi.Names; } using (SingleCtlDialog scd = new SingleCtlDialog(pre.DesignCtl, pre.Draw, pre.Nodes, SingleCtlTypeEnum.BackgroundCtl, names)) { // Display the UI editor dialog if (editorService.ShowDialog(scd) == DialogResult.OK) { // Return the new property value from the UI editor form return new PropertyBackground(pre); } return base.EditValue(context, provider, value); } } } #region GradientType internal class GradientTypeConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(StaticLists.GradientList); } } #endregion [TypeConverter(typeof(PropertyBackgroundImageConverter)), Editor(typeof(PropertyBackgroundUIEditor), typeof(System.Drawing.Design.UITypeEditor))] internal class PropertyBackgroundImage : IReportItem { PropertyReportItem pri; string[] _names; string[] _subitems; internal PropertyBackgroundImage(PropertyReportItem ri, string[] names) { pri = ri; _names = names; if (names == null) { _subitems = new string[] { "Style", "BackgroundImage", "" }; } else { // now build the array used to get/set values _subitems = new string[names.Length + 3]; int i = 0; foreach (string s in names) _subitems[i++] = s; _subitems[i++] = "Style"; _subitems[i++] = "BackgroundImage"; } } internal string[] Names { get { return _names; } } public override string ToString() { string s = this.Source; string v = ""; if (s.ToLower().Trim() != "none") v = this.Value.Expression; return string.Format("{0} {1}", s, v); } [RefreshProperties(RefreshProperties.Repaint), TypeConverter(typeof(ImageSourceConverter)), DescriptionAttribute("Background Image Source: None, External, Embedded, Database.")] public string Source { get { _subitems[_subitems.Length-1] = "Source"; return pri.GetWithList("None", _subitems); } set { if (value.ToLower().Trim() == "none") { List<string> l = new List<string>(_subitems); l.RemoveAt(l.Count - 1); pri.RemoveWithList(l.ToArray()); } else { _subitems[_subitems.Length - 1] = "Source"; pri.SetWithList(value, _subitems); } } } [RefreshProperties(RefreshProperties.Repaint), DescriptionAttribute("Value depends upon the source of the image.")] public PropertyExpr Value { get { _subitems[_subitems.Length - 1] = "Value"; return new PropertyExpr(pri.GetWithList("", _subitems)); } set { if (this.Source.ToLower().Trim() == "none") throw new ArgumentException("Value isn't relevent when Source=None."); _subitems[_subitems.Length - 1] = "Value"; pri.SetWithList(value.Expression, _subitems); } } [RefreshProperties(RefreshProperties.Repaint), TypeConverter(typeof(ImageMIMETypeConverter)), DescriptionAttribute("When Source is Database MIMEType describes the type of image.")] public string MIMEType { get { _subitems[_subitems.Length - 1] = "MIMEType"; return pri.GetWithList("", _subitems); } set { if (this.Source.ToLower().Trim() != "database") throw new ArgumentException("MIMEType isn't relevent when Source isn't Database."); _subitems[_subitems.Length - 1] = "MIMEType"; pri.SetWithList(value, _subitems); } } [RefreshProperties(RefreshProperties.Repaint), TypeConverter(typeof(ImageRepeatConverter)), DescriptionAttribute("Controls repeating of the background image to fill space.")] public string Repeat { get { _subitems[_subitems.Length - 1] = "BackgroundRepeat"; return pri.GetWithList("Repeat", _subitems); } set { if (this.Source.ToLower().Trim() == "none") throw new ArgumentException("Repeat isn't relevent when Source=None."); _subitems[_subitems.Length - 1] = "BackgroundRepeat"; pri.SetWithList(value, _subitems); } } #region IReportItem Members public PropertyReportItem GetPRI() { return pri; } #endregion } internal class PropertyBackgroundImageConverter : ExpandableObjectConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(PropertyBackgroundImage)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value is PropertyBackgroundImage) { PropertyBackgroundImage pf = value as PropertyBackgroundImage; return pf.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } #region ImageSource internal class ImageSourceConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { if (context.Instance is PropertyImageI) return new StandardValuesCollection(new string[] { "External", "Embedded", "Database"}); else return new StandardValuesCollection(new string[] { "None", "External", "Embedded", "Database"}); } } #endregion #region ImageMIMEType internal class ImageMIMETypeConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(new string[] { "image/bmp", "image/jpeg", "image/gif", "image/png","image/x-png"}); } } #endregion #region ImageRepeat internal class ImageRepeatConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(new string[] { "Repeat", "NoRepeat", "RepeatX", "RepeatY"}); } } #endregion }
using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Text; using System.Threading; using OpenHome.Net.Core; using OpenHome.Net.ControlPoint; namespace OpenHome.Net.ControlPoint.Proxies { public interface ICpProxyAvOpenhomeOrgReceiver1 : ICpProxy, IDisposable { void SyncPlay(); void BeginPlay(CpProxy.CallbackAsyncComplete aCallback); void EndPlay(IntPtr aAsyncHandle); void SyncStop(); void BeginStop(CpProxy.CallbackAsyncComplete aCallback); void EndStop(IntPtr aAsyncHandle); void SyncSetSender(String aUri, String aMetadata); void BeginSetSender(String aUri, String aMetadata, CpProxy.CallbackAsyncComplete aCallback); void EndSetSender(IntPtr aAsyncHandle); void SyncSender(out String aUri, out String aMetadata); void BeginSender(CpProxy.CallbackAsyncComplete aCallback); void EndSender(IntPtr aAsyncHandle, out String aUri, out String aMetadata); void SyncProtocolInfo(out String aValue); void BeginProtocolInfo(CpProxy.CallbackAsyncComplete aCallback); void EndProtocolInfo(IntPtr aAsyncHandle, out String aValue); void SyncTransportState(out String aValue); void BeginTransportState(CpProxy.CallbackAsyncComplete aCallback); void EndTransportState(IntPtr aAsyncHandle, out String aValue); void SetPropertyUriChanged(System.Action aUriChanged); String PropertyUri(); void SetPropertyMetadataChanged(System.Action aMetadataChanged); String PropertyMetadata(); void SetPropertyTransportStateChanged(System.Action aTransportStateChanged); String PropertyTransportState(); void SetPropertyProtocolInfoChanged(System.Action aProtocolInfoChanged); String PropertyProtocolInfo(); } internal class SyncPlayAvOpenhomeOrgReceiver1 : SyncProxyAction { private CpProxyAvOpenhomeOrgReceiver1 iService; public SyncPlayAvOpenhomeOrgReceiver1(CpProxyAvOpenhomeOrgReceiver1 aProxy) { iService = aProxy; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndPlay(aAsyncHandle); } }; internal class SyncStopAvOpenhomeOrgReceiver1 : SyncProxyAction { private CpProxyAvOpenhomeOrgReceiver1 iService; public SyncStopAvOpenhomeOrgReceiver1(CpProxyAvOpenhomeOrgReceiver1 aProxy) { iService = aProxy; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndStop(aAsyncHandle); } }; internal class SyncSetSenderAvOpenhomeOrgReceiver1 : SyncProxyAction { private CpProxyAvOpenhomeOrgReceiver1 iService; public SyncSetSenderAvOpenhomeOrgReceiver1(CpProxyAvOpenhomeOrgReceiver1 aProxy) { iService = aProxy; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndSetSender(aAsyncHandle); } }; internal class SyncSenderAvOpenhomeOrgReceiver1 : SyncProxyAction { private CpProxyAvOpenhomeOrgReceiver1 iService; private String iUri; private String iMetadata; public SyncSenderAvOpenhomeOrgReceiver1(CpProxyAvOpenhomeOrgReceiver1 aProxy) { iService = aProxy; } public String Uri() { return iUri; } public String Metadata() { return iMetadata; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndSender(aAsyncHandle, out iUri, out iMetadata); } }; internal class SyncProtocolInfoAvOpenhomeOrgReceiver1 : SyncProxyAction { private CpProxyAvOpenhomeOrgReceiver1 iService; private String iValue; public SyncProtocolInfoAvOpenhomeOrgReceiver1(CpProxyAvOpenhomeOrgReceiver1 aProxy) { iService = aProxy; } public String Value() { return iValue; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndProtocolInfo(aAsyncHandle, out iValue); } }; internal class SyncTransportStateAvOpenhomeOrgReceiver1 : SyncProxyAction { private CpProxyAvOpenhomeOrgReceiver1 iService; private String iValue; public SyncTransportStateAvOpenhomeOrgReceiver1(CpProxyAvOpenhomeOrgReceiver1 aProxy) { iService = aProxy; } public String Value() { return iValue; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndTransportState(aAsyncHandle, out iValue); } }; /// <summary> /// Proxy for the av.openhome.org:Receiver:1 UPnP service /// </summary> public class CpProxyAvOpenhomeOrgReceiver1 : CpProxy, IDisposable, ICpProxyAvOpenhomeOrgReceiver1 { private OpenHome.Net.Core.Action iActionPlay; private OpenHome.Net.Core.Action iActionStop; private OpenHome.Net.Core.Action iActionSetSender; private OpenHome.Net.Core.Action iActionSender; private OpenHome.Net.Core.Action iActionProtocolInfo; private OpenHome.Net.Core.Action iActionTransportState; private PropertyString iUri; private PropertyString iMetadata; private PropertyString iTransportState; private PropertyString iProtocolInfo; private System.Action iUriChanged; private System.Action iMetadataChanged; private System.Action iTransportStateChanged; private System.Action iProtocolInfoChanged; private Mutex iPropertyLock; /// <summary> /// Constructor /// </summary> /// <remarks>Use CpProxy::[Un]Subscribe() to enable/disable querying of state variable and reporting of their changes.</remarks> /// <param name="aDevice">The device to use</param> public CpProxyAvOpenhomeOrgReceiver1(CpDevice aDevice) : base("av-openhome-org", "Receiver", 1, aDevice) { OpenHome.Net.Core.Parameter param; List<String> allowedValues = new List<String>(); iActionPlay = new OpenHome.Net.Core.Action("Play"); iActionStop = new OpenHome.Net.Core.Action("Stop"); iActionSetSender = new OpenHome.Net.Core.Action("SetSender"); param = new ParameterString("Uri", allowedValues); iActionSetSender.AddInputParameter(param); param = new ParameterString("Metadata", allowedValues); iActionSetSender.AddInputParameter(param); iActionSender = new OpenHome.Net.Core.Action("Sender"); param = new ParameterString("Uri", allowedValues); iActionSender.AddOutputParameter(param); param = new ParameterString("Metadata", allowedValues); iActionSender.AddOutputParameter(param); iActionProtocolInfo = new OpenHome.Net.Core.Action("ProtocolInfo"); param = new ParameterString("Value", allowedValues); iActionProtocolInfo.AddOutputParameter(param); iActionTransportState = new OpenHome.Net.Core.Action("TransportState"); allowedValues.Add("Stopped"); allowedValues.Add("Playing"); allowedValues.Add("Waiting"); allowedValues.Add("Buffering"); param = new ParameterString("Value", allowedValues); iActionTransportState.AddOutputParameter(param); allowedValues.Clear(); iUri = new PropertyString("Uri", UriPropertyChanged); AddProperty(iUri); iMetadata = new PropertyString("Metadata", MetadataPropertyChanged); AddProperty(iMetadata); iTransportState = new PropertyString("TransportState", TransportStatePropertyChanged); AddProperty(iTransportState); iProtocolInfo = new PropertyString("ProtocolInfo", ProtocolInfoPropertyChanged); AddProperty(iProtocolInfo); iPropertyLock = new Mutex(); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> public void SyncPlay() { SyncPlayAvOpenhomeOrgReceiver1 sync = new SyncPlayAvOpenhomeOrgReceiver1(this); BeginPlay(sync.AsyncComplete()); sync.Wait(); sync.ReportError(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndPlay().</remarks> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginPlay(CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionPlay, aCallback); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> public void EndPlay(IntPtr aAsyncHandle) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> public void SyncStop() { SyncStopAvOpenhomeOrgReceiver1 sync = new SyncStopAvOpenhomeOrgReceiver1(this); BeginStop(sync.AsyncComplete()); sync.Wait(); sync.ReportError(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndStop().</remarks> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginStop(CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionStop, aCallback); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> public void EndStop(IntPtr aAsyncHandle) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aUri"></param> /// <param name="aMetadata"></param> public void SyncSetSender(String aUri, String aMetadata) { SyncSetSenderAvOpenhomeOrgReceiver1 sync = new SyncSetSenderAvOpenhomeOrgReceiver1(this); BeginSetSender(aUri, aMetadata, sync.AsyncComplete()); sync.Wait(); sync.ReportError(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndSetSender().</remarks> /// <param name="aUri"></param> /// <param name="aMetadata"></param> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginSetSender(String aUri, String aMetadata, CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionSetSender, aCallback); int inIndex = 0; invocation.AddInput(new ArgumentString((ParameterString)iActionSetSender.InputParameter(inIndex++), aUri)); invocation.AddInput(new ArgumentString((ParameterString)iActionSetSender.InputParameter(inIndex++), aMetadata)); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> public void EndSetSender(IntPtr aAsyncHandle) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aUri"></param> /// <param name="aMetadata"></param> public void SyncSender(out String aUri, out String aMetadata) { SyncSenderAvOpenhomeOrgReceiver1 sync = new SyncSenderAvOpenhomeOrgReceiver1(this); BeginSender(sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aUri = sync.Uri(); aMetadata = sync.Metadata(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndSender().</remarks> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginSender(CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionSender, aCallback); int outIndex = 0; invocation.AddOutput(new ArgumentString((ParameterString)iActionSender.OutputParameter(outIndex++))); invocation.AddOutput(new ArgumentString((ParameterString)iActionSender.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aUri"></param> /// <param name="aMetadata"></param> public void EndSender(IntPtr aAsyncHandle, out String aUri, out String aMetadata) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aUri = Invocation.OutputString(aAsyncHandle, index++); aMetadata = Invocation.OutputString(aAsyncHandle, index++); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aValue"></param> public void SyncProtocolInfo(out String aValue) { SyncProtocolInfoAvOpenhomeOrgReceiver1 sync = new SyncProtocolInfoAvOpenhomeOrgReceiver1(this); BeginProtocolInfo(sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aValue = sync.Value(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndProtocolInfo().</remarks> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginProtocolInfo(CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionProtocolInfo, aCallback); int outIndex = 0; invocation.AddOutput(new ArgumentString((ParameterString)iActionProtocolInfo.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aValue"></param> public void EndProtocolInfo(IntPtr aAsyncHandle, out String aValue) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aValue = Invocation.OutputString(aAsyncHandle, index++); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aValue"></param> public void SyncTransportState(out String aValue) { SyncTransportStateAvOpenhomeOrgReceiver1 sync = new SyncTransportStateAvOpenhomeOrgReceiver1(this); BeginTransportState(sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aValue = sync.Value(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndTransportState().</remarks> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginTransportState(CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionTransportState, aCallback); int outIndex = 0; invocation.AddOutput(new ArgumentString((ParameterString)iActionTransportState.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aValue"></param> public void EndTransportState(IntPtr aAsyncHandle, out String aValue) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aValue = Invocation.OutputString(aAsyncHandle, index++); } /// <summary> /// Set a delegate to be run when the Uri state variable changes. /// </summary> /// <remarks>Callbacks may be run in different threads but callbacks for a /// CpProxyAvOpenhomeOrgReceiver1 instance will not overlap.</remarks> /// <param name="aUriChanged">The delegate to run when the state variable changes</param> public void SetPropertyUriChanged(System.Action aUriChanged) { lock (iPropertyLock) { iUriChanged = aUriChanged; } } private void UriPropertyChanged() { lock (iPropertyLock) { ReportEvent(iUriChanged); } } /// <summary> /// Set a delegate to be run when the Metadata state variable changes. /// </summary> /// <remarks>Callbacks may be run in different threads but callbacks for a /// CpProxyAvOpenhomeOrgReceiver1 instance will not overlap.</remarks> /// <param name="aMetadataChanged">The delegate to run when the state variable changes</param> public void SetPropertyMetadataChanged(System.Action aMetadataChanged) { lock (iPropertyLock) { iMetadataChanged = aMetadataChanged; } } private void MetadataPropertyChanged() { lock (iPropertyLock) { ReportEvent(iMetadataChanged); } } /// <summary> /// Set a delegate to be run when the TransportState state variable changes. /// </summary> /// <remarks>Callbacks may be run in different threads but callbacks for a /// CpProxyAvOpenhomeOrgReceiver1 instance will not overlap.</remarks> /// <param name="aTransportStateChanged">The delegate to run when the state variable changes</param> public void SetPropertyTransportStateChanged(System.Action aTransportStateChanged) { lock (iPropertyLock) { iTransportStateChanged = aTransportStateChanged; } } private void TransportStatePropertyChanged() { lock (iPropertyLock) { ReportEvent(iTransportStateChanged); } } /// <summary> /// Set a delegate to be run when the ProtocolInfo state variable changes. /// </summary> /// <remarks>Callbacks may be run in different threads but callbacks for a /// CpProxyAvOpenhomeOrgReceiver1 instance will not overlap.</remarks> /// <param name="aProtocolInfoChanged">The delegate to run when the state variable changes</param> public void SetPropertyProtocolInfoChanged(System.Action aProtocolInfoChanged) { lock (iPropertyLock) { iProtocolInfoChanged = aProtocolInfoChanged; } } private void ProtocolInfoPropertyChanged() { lock (iPropertyLock) { ReportEvent(iProtocolInfoChanged); } } /// <summary> /// Query the value of the Uri property. /// </summary> /// <remarks>This function is threadsafe and can only be called if Subscribe() has been /// called and a first eventing callback received more recently than any call /// to Unsubscribe().</remarks> /// <returns>Value of the Uri property</returns> public String PropertyUri() { PropertyReadLock(); String val; try { val = iUri.Value(); } finally { PropertyReadUnlock(); } return val; } /// <summary> /// Query the value of the Metadata property. /// </summary> /// <remarks>This function is threadsafe and can only be called if Subscribe() has been /// called and a first eventing callback received more recently than any call /// to Unsubscribe().</remarks> /// <returns>Value of the Metadata property</returns> public String PropertyMetadata() { PropertyReadLock(); String val; try { val = iMetadata.Value(); } finally { PropertyReadUnlock(); } return val; } /// <summary> /// Query the value of the TransportState property. /// </summary> /// <remarks>This function is threadsafe and can only be called if Subscribe() has been /// called and a first eventing callback received more recently than any call /// to Unsubscribe().</remarks> /// <returns>Value of the TransportState property</returns> public String PropertyTransportState() { PropertyReadLock(); String val; try { val = iTransportState.Value(); } finally { PropertyReadUnlock(); } return val; } /// <summary> /// Query the value of the ProtocolInfo property. /// </summary> /// <remarks>This function is threadsafe and can only be called if Subscribe() has been /// called and a first eventing callback received more recently than any call /// to Unsubscribe().</remarks> /// <returns>Value of the ProtocolInfo property</returns> public String PropertyProtocolInfo() { PropertyReadLock(); String val; try { val = iProtocolInfo.Value(); } finally { PropertyReadUnlock(); } return val; } /// <summary> /// Must be called for each class instance. Must be called before Core.Library.Close(). /// </summary> public void Dispose() { lock (this) { if (iHandle == IntPtr.Zero) return; DisposeProxy(); iHandle = IntPtr.Zero; } iActionPlay.Dispose(); iActionStop.Dispose(); iActionSetSender.Dispose(); iActionSender.Dispose(); iActionProtocolInfo.Dispose(); iActionTransportState.Dispose(); iUri.Dispose(); iMetadata.Dispose(); iTransportState.Dispose(); iProtocolInfo.Dispose(); } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using Encog.ML.Data; using Encog.Neural.Networks.Training.Strategy; using Encog.Util.Validate; namespace Encog.Neural.Networks.Training.Propagation.Back { /// <summary> /// This class implements a backpropagation training algorithm for feed forward /// neural networks. It is used in the same manner as any other training class /// that implements the Train interface. /// Backpropagation is a common neural network training algorithm. It works by /// analyzing the error of the output of the neural network. Each neuron in the /// output layer's contribution, according to weight, to this error is /// determined. These weights are then adjusted to minimize this error. This /// process continues working its way backwards through the layers of the neural /// network. /// This implementation of the backpropagation algorithm uses both momentum and a /// learning rate. The learning rate specifies the degree to which the weight /// matrixes will be modified through each iteration. The momentum specifies how /// much the previous learning iteration affects the current. To use no momentum /// at all specify zero. /// One primary problem with backpropagation is that the magnitude of the partial /// derivative is often detrimental to the training of the neural network. The /// other propagation methods of Manhatten and Resilient address this issue in /// different ways. In general, it is suggested that you use the resilient /// propagation technique for most Encog training tasks over back propagation. /// </summary> /// public class Backpropagation : Propagation, IMomentum, ILearningRate { /// <summary> /// The resume key for backpropagation. /// </summary> /// public const String PropertyLastDelta = "LAST_DELTA"; /// <summary> /// The last delta values. /// </summary> /// private double[] _lastDelta; /// <summary> /// The learning rate. /// </summary> /// private double _learningRate; /// <summary> /// The momentum. /// </summary> /// private double _momentum; /// <summary> /// Create a class to train using backpropagation. Use auto learn rate and /// momentum. Use the CPU to train. /// </summary> /// /// <param name="network">The network that is to be trained.</param> /// <param name="training">The training data to be used for backpropagation.</param> public Backpropagation(IContainsFlat network, IMLDataSet training) : this(network, training, 0, 0) { AddStrategy(new SmartLearningRate()); AddStrategy(new SmartMomentum()); } /// <param name="network">The network that is to be trained</param> /// <param name="training">The training set</param> /// <param name="learnRate"></param> /// <param name="momentum"></param> public Backpropagation(IContainsFlat network, IMLDataSet training, double learnRate, double momentum) : base(network, training) { ValidateNetwork.ValidateMethodToData(network, training); _momentum = momentum; _learningRate = learnRate; _lastDelta = new double[Network.Flat.Weights.Length]; } /// <inheritdoc /> public override sealed bool CanContinue { get { return true; } } /// <value>Ther last delta values.</value> public double[] LastDelta { get { return _lastDelta; } } #region ILearningRate Members /// <summary> /// Set the learning rate, this is value is essentially a percent. It is the /// degree to which the gradients are applied to the weight matrix to allow /// learning. /// </summary> public virtual double LearningRate { get { return _learningRate; } set { _learningRate = value; } } #endregion #region IMomentum Members /// <summary> /// Set the momentum for training. This is the degree to which changes from /// which the previous training iteration will affect this training /// iteration. This can be useful to overcome local minima. /// </summary> public virtual double Momentum { get { return _momentum; } set { _momentum = value; } } #endregion /// <summary> /// Determine if the specified continuation object is valid to resume with. /// </summary> /// /// <param name="state">The continuation object to check.</param> /// <returns>True if the specified continuation object is valid for this /// training method and network.</returns> public bool IsValidResume(TrainingContinuation state) { if (!state.Contents.ContainsKey(PropertyLastDelta)) { return false; } if (!state.TrainingType.Equals(GetType().Name)) { return false; } var d = (double[])state.Get(PropertyLastDelta); return d.Length == ((IContainsFlat) Method).Flat.Weights.Length; } /// <summary> /// Pause the training. /// </summary> /// /// <returns>A training continuation object to continue with.</returns> public override sealed TrainingContinuation Pause() { var result = new TrainingContinuation {TrainingType = GetType().Name}; result.Set(PropertyLastDelta, _lastDelta); return result; } /// <summary> /// Resume training. /// </summary> /// /// <param name="state">The training state to return to.</param> public override sealed void Resume(TrainingContinuation state) { if (!IsValidResume(state)) { throw new TrainingError("Invalid training resume data length"); } _lastDelta = (double[])state.Get(PropertyLastDelta); } /// <summary> /// Update a weight. /// </summary> /// /// <param name="gradients">The gradients.</param> /// <param name="lastGradient">The last gradients.</param> /// <param name="index">The index.</param> /// <returns>The weight delta.</returns> public override double UpdateWeight(double[] gradients, double[] lastGradient, int index) { double delta = (gradients[index] * _learningRate) + (_lastDelta[index] * _momentum); _lastDelta[index] = delta; return delta; } /// <summary> /// Not needed for this training type. /// </summary> public override void InitOthers() { } } }
// // The Open Toolkit Library License // // Copyright (c) 2006 - 2010 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. // using System; using System.Collections.Generic; using System.Diagnostics; #if !MINIMAL using Microsoft.Win32; #endif namespace OpenTK.Platform.Windows { internal sealed class WinDisplayDeviceDriver : DisplayDeviceBase { private readonly object display_lock = new object(); public WinDisplayDeviceDriver() { RefreshDisplayDevices(); SystemEvents.DisplaySettingsChanged += HandleDisplaySettingsChanged; } public sealed override bool TryChangeResolution(DisplayDevice device, DisplayResolution resolution) { DeviceMode mode = null; if (resolution != null) { mode = new DeviceMode(); mode.PelsWidth = resolution.Width; mode.PelsHeight = resolution.Height; mode.BitsPerPel = resolution.BitsPerPixel; mode.DisplayFrequency = (int)resolution.RefreshRate; mode.Fields = Constants.DM_BITSPERPEL | Constants.DM_PELSWIDTH | Constants.DM_PELSHEIGHT | Constants.DM_DISPLAYFREQUENCY; } return Constants.DISP_CHANGE_SUCCESSFUL == Functions.ChangeDisplaySettingsEx((string)device.Id, mode, IntPtr.Zero, ChangeDisplaySettingsEnum.Fullscreen, IntPtr.Zero); } public sealed override bool TryRestoreResolution(DisplayDevice device) { return TryChangeResolution(device, null); } public void RefreshDisplayDevices() { lock (display_lock) { // Store an array of the current available DisplayDevice objects. // This is needed to preserve the original resolution. DisplayDevice[] previousDevices = AvailableDevices.ToArray(); AvailableDevices.Clear(); // We save all necessary parameters in temporary variables // and construct the device when every needed detail is available. // The main DisplayDevice constructor adds the newly constructed device // to the list of available devices. DisplayDevice opentk_dev; DisplayResolution opentk_dev_current_res = null; List<DisplayResolution> opentk_dev_available_res = new List<DisplayResolution>(); bool opentk_dev_primary = false; int device_count = 0, mode_count = 0; // Get available video adapters and enumerate all monitors WindowsDisplayDevice dev1 = new WindowsDisplayDevice(); while (Functions.EnumDisplayDevices(null, device_count++, dev1, 0)) { if ((dev1.StateFlags & DisplayDeviceStateFlags.AttachedToDesktop) == DisplayDeviceStateFlags.None) { continue; } DeviceMode monitor_mode = new DeviceMode(); // The second function should only be executed when the first one fails // (e.g. when the monitor is disabled) if (Functions.EnumDisplaySettingsEx(dev1.DeviceName.ToString(), DisplayModeSettingsEnum.CurrentSettings, monitor_mode, 0) || Functions.EnumDisplaySettingsEx(dev1.DeviceName.ToString(), DisplayModeSettingsEnum.RegistrySettings, monitor_mode, 0)) { VerifyMode(dev1, monitor_mode); float scale = GetScale(ref monitor_mode); opentk_dev_current_res = new DisplayResolution( (int)(monitor_mode.Position.X / scale), (int)(monitor_mode.Position.Y / scale), (int)(monitor_mode.PelsWidth / scale), (int)(monitor_mode.PelsHeight / scale), monitor_mode.BitsPerPel, monitor_mode.DisplayFrequency); opentk_dev_primary = (dev1.StateFlags & DisplayDeviceStateFlags.PrimaryDevice) != DisplayDeviceStateFlags.None; } opentk_dev_available_res.Clear(); mode_count = 0; while (Functions.EnumDisplaySettingsEx(dev1.DeviceName.ToString(), mode_count++, monitor_mode, 0)) { VerifyMode(dev1, monitor_mode); float scale = GetScale(ref monitor_mode); DisplayResolution res = new DisplayResolution( (int)(monitor_mode.Position.X / scale), (int)(monitor_mode.Position.Y / scale), (int)(monitor_mode.PelsWidth / scale), (int)(monitor_mode.PelsHeight / scale), monitor_mode.BitsPerPel, monitor_mode.DisplayFrequency); opentk_dev_available_res.Add(res); } // Construct the OpenTK DisplayDevice through the accumulated parameters. // The constructor will automatically add the DisplayDevice to the list // of available devices. #pragma warning disable 612,618 opentk_dev = new DisplayDevice( opentk_dev_current_res, opentk_dev_primary, opentk_dev_available_res, opentk_dev_current_res.Bounds, dev1.DeviceName); #pragma warning restore 612,618 // Set the original resolution if the DisplayDevice was previously available. foreach (DisplayDevice existingDevice in previousDevices) { if ((string)existingDevice.Id == (string)opentk_dev.Id) { opentk_dev.OriginalResolution = existingDevice.OriginalResolution; } } AvailableDevices.Add(opentk_dev); if (opentk_dev_primary) { Primary = opentk_dev; } Debug.Print("DisplayDevice {0} ({1}) supports {2} resolutions.", device_count, opentk_dev.IsPrimary ? "primary" : "secondary", opentk_dev.AvailableResolutions.Count); } } } private float GetScale(ref DeviceMode monitor_mode) { float scale = 1.0f; if ((monitor_mode.Fields & Constants.DM_LOGPIXELS) != 0) { scale = monitor_mode.LogPixels / 96.0f; } return scale; } private static void VerifyMode(WindowsDisplayDevice device, DeviceMode mode) { if (mode.BitsPerPel == 0) { Debug.Print( "[Warning] DisplayDevice '{0}' reported a mode with 0 bpp. Please create a bug report at https://github.com/opentk/opentk/issues", device.DeviceName.ToString()); mode.BitsPerPel = 32; } } private void HandleDisplaySettingsChanged(object sender, EventArgs e) { RefreshDisplayDevices(); } ~WinDisplayDeviceDriver() { SystemEvents.DisplaySettingsChanged -= HandleDisplaySettingsChanged; } } }
//============================================================================= // System : Sandcastle Help File Builder Utilities // File : TocEntryCollection.cs // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 07/02/2010 // Note : Copyright 2006-2010, Eric Woodruff, All rights reserved // Compiler: Microsoft Visual C# // // This file contains a collection class used to hold the table of contents // entries for additional content items. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://SHFB.CodePlex.com. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.3.0.0 09/17/2006 EFW Created the code // 1.5.0.2 07/03/2007 EFW Added support for saving as a site map file // 1.8.0.0 08/11/2008 EFW Modified to support the new project format // 1.9.0.0 06/15/2010 EFW Added support for MS Help Viewer TOC format //============================================================================= using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Xml; namespace SandcastleBuilder.Utils.ConceptualContent { /// <summary> /// This collection class is used to hold the table of contents entries for /// additional content items. /// </summary> public class TocEntryCollection : BindingList<TocEntry>, ITableOfContents { #region Private data members //===================================================================== private FileItem siteMapFile; #endregion #region Properties //===================================================================== /// <summary> /// This read-only property returns the project file item associated /// with the collection. /// </summary> public FileItem FileItem { get { return siteMapFile; } } /// <summary> /// This is used to get the default topic /// </summary> /// <value>It returns the default topic or null if one is not set</value> public TocEntry DefaultTopic { get { foreach(TocEntry t in this) { if(t.IsDefaultTopic) return t; var defaultTopic = t.Children.DefaultTopic; if(defaultTopic != null) return defaultTopic; } return null; } } /// <summary> /// This is used to get the topic at which the API table of contents is /// to be inserted or parented. /// </summary> /// <value>This will return null if no parent location has been set</value> public TocEntry ApiContentInsertionPoint { get { foreach(TocEntry t in this) { if(t.ApiParentMode != ApiParentMode.None) return t; var childInsertionPoint = t.Children.ApiContentInsertionPoint; if(childInsertionPoint != null) return childInsertionPoint; } return null; } } /// <summary> /// This is used to get the parent item that will contain the API table /// of contents. /// </summary> /// <returns>The parent item or null if it is the root collection.</returns> public TocEntry ApiContentParent { get { TocEntry apiParent; foreach(TocEntry t in this) { if(t.Children.Any(c => c.ApiParentMode != ApiParentMode.None)) return t; apiParent = t.Children.ApiContentParent; if(apiParent != null) return apiParent; } return null; } } /// <summary> /// This is used to get the parent collection that contains the item /// where the API table of contents is to be inserted. /// </summary> /// <returns>The parent collection if there is a location defined or /// null if there isn't one.</returns> public TocEntryCollection ApiContentParentCollection { get { TocEntryCollection apiParent; foreach(TocEntry t in this) { if(t.ApiParentMode != ApiParentMode.None) return this; apiParent = t.Children.ApiContentParentCollection; if(apiParent != null) return apiParent; } return null; } } /// <summary> /// This can be used to get a topic by its unique ID (case-insensitive) /// </summary> /// <param name="id">The ID of the item to get.</param> /// <value>Returns the topic with the specified /// <see cref="TocEntry.Id" /> or null if not found.</value> public TocEntry this[string id] { get { TocEntry found; foreach(TocEntry t in this) { if(String.Compare(t.Id, id, StringComparison.OrdinalIgnoreCase) == 0) return t; found = t.Children[id]; if(found != null) return found; } return null; } } #endregion #region Constructors //===================================================================== /// <summary> /// Default constructor /// </summary> /// <overloads>There are two overloads for the constructor</overloads> public TocEntryCollection() { } /// <summary> /// Constructor /// </summary> /// <param name="siteMap">The site map file associated with the /// collection.</param> public TocEntryCollection(FileItem siteMap) { siteMapFile = siteMap; } #endregion #region Sort the collection //===================================================================== /// <summary> /// This is used to sort the collection /// </summary> /// <remarks>All top level items and their children are sorted</remarks> public void Sort() { ((List<TocEntry>)this.Items).Sort((x, y) => Comparer<TocEntry>.Default.Compare(x, y)); foreach(TocEntry te in this) te.Children.Sort(); } #endregion #region ToString methods //===================================================================== /// <summary> /// Convert the table of contents entry and its children to a string /// </summary> /// <returns>The entries in HTML 1.x help format</returns> public override string ToString() { return this.ToString(HelpFileFormat.HtmlHelp1); } /// <summary> /// Convert the table of contents entry and its children to a string /// in the specified help file format. /// </summary> /// <param name="format">The help file format to use</param> /// <returns>The entries in the specified help format</returns> public string ToString(HelpFileFormat format) { StringBuilder sb = new StringBuilder(1024); this.ConvertToString(format, sb); return sb.ToString(); } /// <summary> /// This is used to convert the collection to a string and append it /// to the specified string builder. /// </summary> /// <param name="format">The help file format to use</param> /// <param name="sb">The string builder to which the information is /// appended.</param> internal void ConvertToString(HelpFileFormat format, StringBuilder sb) { foreach(TocEntry te in this) te.ConvertToString(format, sb); } #endregion #region Save as intermediate TOC file for conceptual content builds //===================================================================== /// <summary> /// This is used to save the TOC information to an intermediate TOC /// file used in the conceptual content build. /// </summary> /// <param name="rootContainerId">The ID of the root container topic if used</param> /// <param name="rootOrder">The TOC order for the root container topic if used</param> /// <param name="filename">The filename to use</param> public void SaveToIntermediateTocFile(string rootContainerId, int rootOrder, string filename) { using(StreamWriter sw = new StreamWriter(filename)) { sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); sw.WriteLine("<topics>"); if(!String.IsNullOrEmpty(rootContainerId)) sw.WriteLine("<topic id=\"{0}\" file=\"{0}\" sortOrder=\"{1}\">", rootContainerId, rootOrder); sw.WriteLine(this.ToString(HelpFileFormat.MSHelpViewer)); if(!String.IsNullOrEmpty(rootContainerId)) sw.WriteLine("</topic>"); sw.WriteLine("</topics>"); } } #endregion #region Site map file methods //===================================================================== /// <summary> /// This is used to locate the default topic if one exists /// </summary> /// <returns>The default topic if found or null if not found</returns> /// <remarks>The first entry found is returned. Nodes are searched /// recursively.</remarks> public TocEntry FindDefaultTopic() { TocEntry defaultTopic; foreach(TocEntry t in this) { if(t.IsDefaultTopic) return t; if(t.Children.Count != 0) { defaultTopic = t.Children.FindDefaultTopic(); if(defaultTopic != null) return defaultTopic; } } return null; } /// <summary> /// This will remove excluded nodes from a TOC created off of the /// additional content items in a project. In addition, it merges /// the information from folder entries into the folder nodes. /// </summary> /// <param name="parent">The parent node</param> public void RemoveExcludedNodes(TocEntry parent) { TocEntry current; string source; for(int idx = 0; idx < this.Count; idx++) { current = this[idx]; source = current.SourceFile; if(parent != null && !String.IsNullOrEmpty(source)) { // If the filename matches the folder, copy the info to // the parent folder item. source = source.ToLower(CultureInfo.InvariantCulture); if(Path.GetDirectoryName(source).EndsWith( Path.GetFileNameWithoutExtension(source), StringComparison.Ordinal)) { parent.Title = current.Title; if(current.IncludePage) { parent.SourceFile = current.SourceFile; parent.DestinationFile = current.DestinationFile; parent.IsDefaultTopic = current.IsDefaultTopic; } parent.SortOrder = current.SortOrder; parent.ApiParentMode = current.ApiParentMode; current.IncludePage = false; } } // If not to be included in the TOC, remove it if(!current.IncludePage) { this.Remove(current); idx--; } else if(current.Children.Count != 0) current.Children.RemoveExcludedNodes(current); } } /// <summary> /// This is used to load the table of contents entries from the site /// map file associated with the collection. /// </summary> /// <exception cref="InvalidOperationException">This is thrown if a /// site map has not been associated with the collection.</exception> public void Load() { if(siteMapFile == null) throw new InvalidOperationException("A site map has not " + "been associated with the collection"); XmlDocument siteMap = new XmlDocument(); TocEntry entry; siteMap.Load(siteMapFile.FullPath); foreach(XmlNode site in siteMap.ChildNodes[1].ChildNodes) { entry = new TocEntry(siteMapFile.ProjectElement.Project); entry.LoadSiteMapNode(site); base.Add(entry); } } /// <summary> /// This is used to save the table of contents entries to the site map /// file associated with the collection. /// </summary> /// <exception cref="InvalidOperationException">This is thrown if a /// site map has not been associated with the collection.</exception> public void Save() { if(siteMapFile == null) throw new InvalidOperationException("A site map has not " + "been associated with the collection"); XmlDocument siteMap = new XmlDocument(); siteMap.AppendChild(siteMap.CreateXmlDeclaration("1.0", "utf-8", null)); XmlNode root = siteMap.CreateNode(XmlNodeType.Element, "siteMap", "http://schemas.microsoft.com/AspNet/SiteMap-File-1.0"); siteMap.AppendChild(root); foreach(TocEntry te in this) te.SaveAsSiteMapNode(root); siteMap.Save(siteMapFile.FullPath); } /// <summary> /// Find a TOC entry with the same source filename /// </summary> /// <param name="sourceFilename">The source filename to match</param> /// <returns>The match TOC entry or null if not found</returns> public TocEntry Find(string sourceFilename) { TocEntry match = null; foreach(TocEntry entry in this) { match = entry.ContainsMatch(sourceFilename); if(match != null) break; } return match; } #endregion #region Helper methods //===================================================================== /// <summary> /// Reset the sort order on all items in the collection /// </summary> public void ResetSortOrder() { foreach(TocEntry t in this) t.ResetSortOrder(); } /// <summary> /// This is used by contained items to notify the parent that a child /// list changed and thus the collection should be marked as dirty. /// </summary> /// <param name="changedItem">The item that changed</param> internal void ChildListChanged(TocEntry changedItem) { this.OnListChanged(new ListChangedEventArgs( ListChangedType.ItemChanged, this.IndexOf(changedItem))); } #endregion #region Add all topic files from a folder //===================================================================== /// <summary> /// Add all topics from the specified folder recursively to the /// collection and to the given project file. /// </summary> /// <param name="folder">The folder from which to get the files</param> /// <param name="basePath">The base path to remove from files copied /// from another folder into the project folder. On the first call, /// this should match the <paramref name="folder"/> value.</param> /// <param name="project">The project to which the files are added</param> /// <remarks>Only actual HTML content topic files are added. They must /// have a ".htm?" extension. Folders will be added as sub-topics /// recursively. If a file with the same name as the folder exists, /// it will be associated with the container node. If no such file /// exists, an empty container node is created.</remarks> public void AddTopicsFromFolder(string folder, string basePath, SandcastleProject project) { TocEntry topic, removeTopic; string[] files = Directory.GetFiles(folder, "*.htm?"); string name, newPath, projectPath = Path.GetDirectoryName(project.Filename); if(basePath.Length != 0 && basePath[basePath.Length - 1] != '\\') basePath += "\\"; // Add files foreach(string file in files) { // The file must reside under the project path if(Path.GetDirectoryName(file).StartsWith(projectPath, StringComparison.OrdinalIgnoreCase)) newPath = file; else newPath = Path.Combine(projectPath, file.Substring(basePath.Length)); // Add the file to the project project.AddFileToProject(file, newPath); topic = new TocEntry(project); topic.SourceFile = new FilePath(newPath, project); topic.Title = Path.GetFileNameWithoutExtension(newPath); this.Add(topic); } // Add folders recursively files = Directory.GetDirectories(folder); foreach(string folderName in files) { topic = new TocEntry(project); topic.Title = name = Path.GetFileName(folderName); topic.Children.AddTopicsFromFolder(folderName, basePath, project); // Ignore empty folders if(topic.Children.Count == 0) continue; this.Add(topic); // Look for a file with the same name as the folder removeTopic = null; foreach(TocEntry t in topic.Children) if(Path.GetFileNameWithoutExtension(t.SourceFile) == name) { // If found, remove it as it represents the container // node. topic.Title = name; topic.SourceFile = t.SourceFile; removeTopic = t; break; } if(removeTopic != null) topic.Children.Remove(removeTopic); } } #endregion #region Overrides //===================================================================== /// <summary> /// This is overridden to set the inserted item's parent to this /// collection. /// </summary> /// <inheritdoc /> protected override void InsertItem(int index, TocEntry item) { base.InsertItem(index, item); item.Parent = this; } /// <summary> /// This is overridden to set the inserted item's parent to this /// collection. /// </summary> /// <inheritdoc /> protected override void SetItem(int index, TocEntry item) { base.SetItem(index, item); item.Parent = this; } /// <summary> /// This is overridden to clear the parent on the removed item /// </summary> /// <param name="index">The index of the item to remove</param> protected override void RemoveItem(int index) { TocEntry item = this[index]; item.Parent = null; base.RemoveItem(index); } #endregion #region ITableOfContents implementation //===================================================================== /// <summary> /// This is used to get the site map file associated with the /// collection. /// </summary> public FileItem ContentLayoutFile { get { return siteMapFile; } } /// <summary> /// This is used to merge this TOC with another one /// </summary> /// <param name="toc">The table of contents collection</param> /// <param name="pathProvider">The base path provider</param> public void GenerateTableOfContents(TocEntryCollection toc, IBasePathProvider pathProvider) { foreach(TocEntry t in this) toc.Add(t); } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; namespace Csla { /// <summary> /// Represents a databindable, transactioned view of an object. /// </summary> /// <author>Brian Criswell</author> /// <license>CREATIVE COMMONS - Attribution 2.5 License http://creativecommons.org/ </license> public class ObjectView : IDataErrorInfo, IEditableObject, INotifyPropertyChanged, ICustomTypeDescriptor { #region Fields private ObjectListView _parent; private object _object; #endregion #region Constructor private ObjectView(ObjectListView parent, object obj, int baseIndex, bool isNew) { _parent = parent; _object = obj; _isNew = isNew; _baseIndex = baseIndex; if (_object is INotifyPropertyChanged) { ((INotifyPropertyChanged)_object).PropertyChanged += new PropertyChangedEventHandler(Object_PropertyChanged); } } #endregion #region Methods /// <summary> /// Gets a value. /// </summary> /// <param name="index">The index of the value to retrieve.</param> /// <returns>The value at the index.</returns> protected virtual object GetValue(int index) { if (_parent.ObjectProperties.Count == 0) return _object; return ((ObjectViewPropertyDescriptor)_parent.ObjectProperties[index]).ObjectPropertyDescriptor.GetValue(this.Object); } /// <summary> /// Gets a value. /// </summary> /// <param name="name">The name of the value to retrieve.</param> /// <returns>The value of the name.</returns> protected virtual object GetValue(string name) { if (_parent.ObjectProperties.Count == 0) return _object; return ((ObjectViewPropertyDescriptor)_parent.ObjectProperties[name]).ObjectPropertyDescriptor.GetValue(this.Object); } /// <summary> /// Sets the value at the given index. /// </summary> /// <param name="index">The index of the value to set.</param> /// <param name="value">The value to set.</param> protected virtual void SetValue(int index, object value) { ((ObjectViewPropertyDescriptor)_parent.ObjectProperties[index]).ObjectPropertyDescriptor.SetValue(this.Object, value); } /// <summary> /// Sets the value for the given name. /// </summary> /// <param name="name">The name of the value to set.</param> /// <param name="value">The value to set.</param> protected virtual void SetValue(string name, object value) { ((ObjectViewPropertyDescriptor)_parent.ObjectProperties[name]).ObjectPropertyDescriptor.SetValue(this.Object, value); } #endregion #region Factory Methods internal static ObjectView NewObjectView(ObjectListView parent, object obj, int baseIndex) { return NewObjectView(parent, obj, baseIndex, false); } internal static ObjectView NewObjectView(ObjectListView parent, object obj, int baseIndex, bool isNew) { if (parent.NoProperties) { return new NoPropertyObjectView(parent, obj, baseIndex, isNew); } return new ObjectView(parent, obj, baseIndex, isNew); } #endregion #region Properties /// <summary> /// Gets the parent ObjectListView. /// </summary> protected ObjectListView Parent { get { return _parent; } } /// <summary> /// Gets or sets the corresponding property on the underlying object. /// </summary> /// <param name="index">The index of the property.</param> /// <returns>The value of the property.</returns> public object this[int index] { get { return this.GetValue(index); } set { this.SetValue(index, value); } } /// <summary> /// Gets or sets the corresponding property on the underlying object. /// </summary> /// <param name="name">The name of the property.</param> /// <returns>The value of the property.</returns> public object this[string name] { get { return this.GetValue(name); } set { this.SetValue(name, value); } } /// <summary> /// Gets the underlying object. /// </summary> public object Object { get { return _object; } } #endregion #region Sorting and Filtering private int _baseIndex = -1; /// <summary> /// Gets or sets the index in the source list of the item that this ObjectView represents. /// </summary> internal int BaseIndex { get { return _baseIndex; } set { _baseIndex = value; } } private bool _visible = true; /// <summary> /// Gets or sets whether this ObjectView is visible. /// </summary> internal bool Visible { get { return _visible; } } /// <summary> /// Applies the current filter to the ObjectView. /// </summary> /// <param name="filteredView">The filter to apply.</param> /// <returns>True if the filter is not set or the ObjectView passes the filter; otherwise false.</returns> internal bool ApplyFilter(System.Data.DataView filteredView) { if (filteredView == null || filteredView.RowFilter.Length == 0) { _visible = true; return _visible; } string filter = filteredView.RowFilter; filteredView.RowFilter = string.Empty; System.Data.DataRow row = filteredView.Table.Rows[0]; for (int i = 0; i < this.Parent.ObjectProperties.Count; i++) { string propertyName = this.Parent.ObjectProperties[i].Name; object value = this[propertyName]; if (value == null) { row[propertyName] = DBNull.Value; } else { row[propertyName] = value; } } filteredView.RowFilter = filter; _visible = filteredView.Count > 0; return _visible; } #endregion #region IDataErrorInfo Members string IDataErrorInfo.Error { get { if (_object is IDataErrorInfo) { return ((IDataErrorInfo)_object).Error; } return string.Empty; } } string IDataErrorInfo.this[string columnName] { get { if (_object is IDataErrorInfo) { return ((IDataErrorInfo)_object)[columnName]; } return string.Empty; } } #endregion #region IEditableObject Members private Dictionary<string, object> _cache; /// <summary> /// Gets whether the ObjectView is in edit mode. /// </summary> public bool IsEdit { get { return _isNew || _cache != null; } } private bool _isNew = false; /// <summary> /// Gets whether the ObjectView is the new ObjectView for the ObjectListView /// </summary> public bool IsNew { get { return _isNew; } } /// <summary> /// Puts the ObjectView into edit mode. /// </summary> public void BeginEdit() { if (_cache == null && !_isNew) { _cache = new Dictionary<string, object>(); for (int i = 0; i < _parent.ObjectProperties.Count; i++ ) { string propertyName = _parent.ObjectProperties[i].Name; _cache.Add(propertyName, this[propertyName]); } } } /// <summary> /// Reverts the changes made to this ObjectView. /// </summary> public void CancelEdit() { if (_isNew) { ((IBindingList)_parent).Remove(this); } else if (_cache != null) { foreach (string key in _cache.Keys) { this.SetValue(key, _cache[key]); } _cache = null; this.OnPropertyChanged(string.Empty); } } /// <summary> /// Accepts the changes made to this ObjectView. /// </summary> public void EndEdit() { if (this.IsEdit) { _cache = null; _isNew = false; this.OnPropertyChanged(string.Empty); } } #endregion #region INotifyPropertyChanged Members private void Object_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (!this.IsEdit) { this.OnPropertyChanged(e.PropertyName); } } /// <summary> /// Occurs when the object managed by the ObjectView changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Call this method to raise the PropertyChanged event /// for a specific property. /// </summary> /// <remarks> /// This method may be called by properties in the business /// class to indicate the change in a specific property. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion #region ICustomTypeDescriptor Members AttributeCollection ICustomTypeDescriptor.GetAttributes() { return TypeDescriptor.GetAttributes(this.Parent.IndexedType); } string ICustomTypeDescriptor.GetClassName() { return null; } string ICustomTypeDescriptor.GetComponentName() { return null; } TypeConverter ICustomTypeDescriptor.GetConverter() { return null; } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return null; } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { return null; } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return null; } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return null; } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return null; } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { PropertyDescriptorCollection props = new PropertyDescriptorCollection(null); if (this.Parent.IndexedType != null) { PropertyDescriptorCollection filteredProps = TypeDescriptor.GetProperties(this.Parent.IndexedType, attributes); for (int i = 0; i < filteredProps.Count; i++) { props.Add(new ObjectViewPropertyDescriptor(filteredProps[i])); } } return props; } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return this.Parent.ObjectProperties; } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return this; } #endregion #region DefaultItemObjectView internal class DefaultItemObjectView : ObjectView { Dictionary<string, object> _values; public DefaultItemObjectView(ObjectListView parent) : base(parent, null, -1, false) { _values = new Dictionary<string, object>(parent.ObjectProperties.Count); for (int i = 0; i < parent.ObjectProperties.Count; i++) { _values.Add(parent.ObjectProperties[i].Name, null); } } protected override object GetValue(int index) { return _values[this.Parent.ObjectProperties[index].Name]; } protected override object GetValue(string name) { return _values[name]; } protected override void SetValue(int index, object value) { _values[this.Parent.ObjectProperties[index].Name] = value; } protected override void SetValue(string name, object value) { _values[name] = value; } } #endregion #region NoPropertyObjectView private class NoPropertyObjectView : ObjectView { public NoPropertyObjectView(ObjectListView parent, object obj, int baseIndex, bool isNew) : base(parent, obj, baseIndex, isNew) { } protected override object GetValue(int index) { return _parent.List[this.BaseIndex]; } protected override object GetValue(string name) { return _parent.List[this.BaseIndex]; } protected override void SetValue(int index, object value) { _parent.List[this.BaseIndex] = value; } protected override void SetValue(string name, object value) { _parent.List[this.BaseIndex] = value; } } #endregion #region ObjectViewPropertyDescriptor internal class ObjectViewPropertyDescriptor : PropertyDescriptor { private PropertyDescriptor _descr; public ObjectViewPropertyDescriptor(PropertyDescriptor descr) : base(descr) { _descr = descr; } public override bool CanResetValue(object component) { if (((ObjectView)component).Object != null) { return _descr.CanResetValue(((ObjectView)component).Object); } return false; } public override Type ComponentType { get { return typeof(ObjectView); } } public override object GetValue(object component) { return ((ObjectView)component)[this.Name]; } public override bool IsReadOnly { get { return _descr.IsReadOnly; } } public override Type PropertyType { get { return _descr.PropertyType; } } public override void ResetValue(object component) { if (((ObjectView)component).Object != null) { _descr.ResetValue(((ObjectView)component).Object); } } public override void SetValue(object component, object value) { ((ObjectView)component)[this.Name] = value; } public override bool ShouldSerializeValue(object component) { if (((ObjectView)component).Object != null) { return _descr.ShouldSerializeValue(((ObjectView)component).Object); } return true; } public PropertyDescriptor ObjectPropertyDescriptor { get { return _descr; } } } #endregion } }
using System; using System.Linq; using System.Runtime.InteropServices; using RtMidiPtr = System.IntPtr; using RtMidiInPtr = System.IntPtr; using RtMidiOutPtr = System.IntPtr; using System.Collections.Generic; namespace Commons.Music.Midi.RtMidi { public enum RtMidiApi { Unspecified, MacOsxCore, LinuxAlsa, UnixJack, WindowsMultimediaMidi, WindowsKernelStreaming, RtMidiDummy, } public enum RtMidiErrorType { Warning, DebugWarning, Unspecified, NoDevicesFound, InvalidDevice, MemoryError, InvalidParameter, InvalidUse, DriverError, SystemError, ThreadError, } public unsafe delegate void RtMidiCCallback (double timestamp, byte* message, long size, IntPtr userData); public static class RtMidi { public const string RtMidiLibrary = "rtmidi"; /* Utility API */ [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal int rtmidi_sizeof_rtmidi_api (); /* RtMidi API */ [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal int rtmidi_get_compiled_api (ref IntPtr/* RtMidiApi ** */ apis); // return length for NULL argument. [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal void rtmidi_error (RtMidiErrorType type, string errorString); [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal void rtmidi_open_port (RtMidiPtr device, uint portNumber, string portName); [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal void rtmidi_open_virtual_port (RtMidiPtr device, string portName); [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal void rtmidi_close_port (RtMidiPtr device); [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal int rtmidi_get_port_count (RtMidiPtr device); [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] [return:MarshalAs (UnmanagedType.LPStr)] static extern internal string rtmidi_get_port_name (RtMidiPtr device, uint portNumber); /* RtMidiIn API */ [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal RtMidiInPtr rtmidi_in_create_default (); [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal RtMidiInPtr rtmidi_in_create (RtMidiApi api, string clientName, uint queueSizeLimit); [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal void rtmidi_in_free (RtMidiInPtr device); [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal RtMidiApi rtmidi_in_get_current_api (RtMidiPtr device); [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal void rtmidi_in_set_callback (RtMidiInPtr device, RtMidiCCallback callback, IntPtr userData); [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal void rtmidi_in_cancel_callback (RtMidiInPtr device); [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal void rtmidi_in_ignore_types (RtMidiInPtr device, bool midiSysex, bool midiTime, bool midiSense); [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal double rtmidi_in_get_message (RtMidiInPtr device, /* unsigned char ** */out IntPtr message); /* RtMidiOut API */ [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal RtMidiOutPtr rtmidi_out_create_default (); [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal RtMidiOutPtr rtmidi_out_create (RtMidiApi api, string clientName); [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal void rtmidi_out_free (RtMidiOutPtr device); [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal RtMidiApi rtmidi_out_get_current_api (RtMidiPtr device); [DllImport (RtMidiLibrary, CallingConvention = CallingConvention.Cdecl)] static extern internal int rtmidi_out_send_message (RtMidiOutPtr device, byte [] message, int length); } // Wrapper classes public abstract class RtMidiDevice : IDisposable { // no idea when to use it... public static void Error (RtMidiErrorType errorType, string message) { RtMidi.rtmidi_error (errorType, message); } public static RtMidiApi [] GetAvailableApis () { int enumSize = RtMidi.rtmidi_sizeof_rtmidi_api (); IntPtr ptr = IntPtr.Zero; int size = RtMidi.rtmidi_get_compiled_api (ref ptr); ptr = Marshal.AllocHGlobal (size * enumSize); RtMidi.rtmidi_get_compiled_api (ref ptr); RtMidiApi [] ret = new RtMidiApi [size]; switch (enumSize) { case 1: byte [] bytes = new byte [size]; Marshal.Copy (ptr, bytes, 0, bytes.Length); for (int i = 0; i < bytes.Length; i++) ret [i] = (RtMidiApi) bytes [i]; break; case 2: short [] shorts = new short [size]; Marshal.Copy (ptr, shorts, 0, shorts.Length); for (int i = 0; i < shorts.Length; i++) ret [i] = (RtMidiApi) shorts [i]; break; case 4: int [] ints = new int [size]; Marshal.Copy (ptr, ints, 0, ints.Length); for (int i = 0; i < ints.Length; i++) ret [i] = (RtMidiApi) ints [i]; break; case 8: long [] longs = new long [size]; Marshal.Copy (ptr, longs, 0, longs.Length); for (int i = 0; i < longs.Length; i++) ret [i] = (RtMidiApi) longs [i]; break; default: throw new NotSupportedException ("sizeof RtMidiApi is unexpected: " + enumSize); } return ret; } RtMidiPtr handle; bool is_port_open; protected RtMidiDevice (RtMidiPtr handle) { this.handle = handle; } public RtMidiPtr Handle { get { return handle; } } public int PortCount { get { return (int) RtMidi.rtmidi_get_port_count (handle); } } public void Dispose () { Close (); } public void Close () { if (is_port_open) { is_port_open = false; RtMidi.rtmidi_close_port (handle); } ReleaseDevice (); } public string GetPortName (int portNumber) { return RtMidi.rtmidi_get_port_name (handle, (uint) portNumber); } public void OpenVirtualPort (string portName) { try { RtMidi.rtmidi_open_virtual_port (handle, portName); } finally { is_port_open = true; } } public void OpenPort (int portNumber, string portName) { try { RtMidi.rtmidi_open_port (handle, (uint) portNumber, portName); } finally { is_port_open = true; } } protected abstract void ReleaseDevice (); public abstract RtMidiApi CurrentApi { get; } } public class RtMidiInputDevice : RtMidiDevice { public RtMidiInputDevice () : base (RtMidi.rtmidi_in_create_default ()) { } public RtMidiInputDevice (RtMidiApi api, string clientName, int queueSizeLimit = 100) : base (RtMidi.rtmidi_in_create (api, clientName, (uint) queueSizeLimit)) { } public override RtMidiApi CurrentApi { get { return RtMidi.rtmidi_in_get_current_api (Handle); } } protected override void ReleaseDevice () { RtMidi.rtmidi_in_free (Handle); } public void SetCallback (RtMidiCCallback callback, IntPtr userData) { RtMidi.rtmidi_in_set_callback (Handle, callback, userData); } public void CancelCallback () { RtMidi.rtmidi_in_cancel_callback (Handle); } public void SetIgnoredTypes (bool midiSysex, bool midiTime, bool midiSense) { RtMidi.rtmidi_in_ignore_types (Handle, midiSysex, midiTime, midiSense); } public byte [] GetMessage () { IntPtr ptr; int size = (int) RtMidi.rtmidi_in_get_message (Handle, out ptr); byte [] buf = new byte [size]; Marshal.Copy (ptr, buf, 0, size); return buf; } } public class RtMidiOutputDevice : RtMidiDevice { public RtMidiOutputDevice () : base (RtMidi.rtmidi_out_create_default ()) { } public RtMidiOutputDevice (RtMidiApi api, string clientName) : base (RtMidi.rtmidi_out_create (api, clientName)) { } public override RtMidiApi CurrentApi { get { return RtMidi.rtmidi_out_get_current_api (Handle); } } protected override void ReleaseDevice () { RtMidi.rtmidi_out_free (Handle); } public void SendMessage (byte [] message, int length) { if (message == null) throw new ArgumentNullException ("message"); // While it could emit message parsing error, it still returns 0...! RtMidi.rtmidi_out_send_message (Handle, message, length); } } // Utility classes public static class MidiDeviceManager { static readonly RtMidiOutputDevice manager_output = new RtMidiOutputDevice (); static readonly RtMidiInputDevice manager_input = new RtMidiInputDevice (); // OK, it is not really a device count. But RTMIDI is designed to have bad names enough // to enumerate APIs as DEVICEs. public static int DeviceCount { get { return manager_input.PortCount + manager_output.PortCount; } } public static int DefaultInputDeviceID { get { return 0; } } public static int DefaultOutputDeviceID { get { return manager_input.PortCount; } } public static IEnumerable<MidiDeviceInfo> AllDevices { get { for (int i = 0; i < DeviceCount; i++) yield return GetDeviceInfo (i); } } public static MidiDeviceInfo GetDeviceInfo (int id) { return id < manager_input.PortCount ? new MidiDeviceInfo (manager_input, id, id, true) : new MidiDeviceInfo (manager_output, id, id - manager_input.PortCount, false); } public static RtMidiInputDevice OpenInput (int deviceID) { var dev = new RtMidiInputDevice (); dev.OpenPort (deviceID, GetDeviceInfo (deviceID).Name); return dev; } public static RtMidiOutputDevice OpenOutput (int deviceID) { var dev = new RtMidiOutputDevice (); dev.OpenPort (deviceID - manager_input.PortCount, GetDeviceInfo (deviceID).Name); return dev; } } public class MidiDeviceInfo { readonly RtMidiDevice manager; readonly int id; readonly int port; readonly bool is_input; internal MidiDeviceInfo (RtMidiDevice manager, int id, int port, bool isInput) { this.manager = manager; this.id = id; this.port = port; is_input = isInput; } public int ID { get { return id; } } public int Port { get { return port; } } public string Interface { get { return manager.CurrentApi.ToString (); } } public string Name { get { return manager.GetPortName (port); } } public bool IsInput { get { return is_input; } } public bool IsOutput { get { return !is_input; } } public override string ToString () { return String.Format ("{0} - {1} ({2})", Interface, Name, IsInput ? (IsOutput ? "I/O" : "Input") : (IsOutput ? "Output" : "N/A")); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.Extensions.Logging; using Decorator.Models; using Decorator.Models.AccountViewModels; using Decorator.Services; namespace Decorator.Controllers { [Authorize] public class AccountController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ILogger _logger; public AccountController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender, ISmsSender smsSender, ILoggerFactory loggerFactory) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<AccountController>(); } // // GET: /Account/Login [HttpGet] [AllowAnonymous] public IActionResult Login(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } // // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { _logger.LogInformation(1, "User logged in."); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); } if (result.IsLockedOut) { _logger.LogWarning(2, "User account locked out."); return View("Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/Register [HttpGet] [AllowAnonymous] public IActionResult Register(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Confirm your account", // $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>"); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User created a new account with password."); return RedirectToLocal(returnUrl); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } // // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> LogOff() { await _signInManager.SignOutAsync(); _logger.LogInformation(4, "User logged out."); return RedirectToAction(nameof(HomeController.Index), "Home"); } // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public IActionResult ExternalLogin(string provider, string returnUrl = null) { // Request a redirect to the external login provider. var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); return Challenge(properties, provider); } // // GET: /Account/ExternalLoginCallback [HttpGet] [AllowAnonymous] public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) { if (remoteError != null) { ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}"); return View(nameof(Login)); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return RedirectToAction(nameof(Login)); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false); if (result.Succeeded) { _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl }); } if (result.IsLockedOut) { return View("Lockout"); } else { // If the user does not have an account, then ask the user to create an account. ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = info.LoginProvider; var email = info.Principal.FindFirstValue(ClaimTypes.Email); return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email }); } } // // POST: /Account/ExternalLoginConfirmation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewData["ReturnUrl"] = returnUrl; return View(model); } // GET: /Account/ConfirmEmail [HttpGet] [AllowAnonymous] public async Task<IActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return View("Error"); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return View("Error"); } var result = await _userManager.ConfirmEmailAsync(user, code); return View(result.Succeeded ? "ConfirmEmail" : "Error"); } // // GET: /Account/ForgotPassword [HttpGet] [AllowAnonymous] public IActionResult ForgotPassword() { return View(); } // // POST: /Account/ForgotPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(model.Email); if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { // Don't reveal that the user does not exist or is not confirmed return View("ForgotPasswordConfirmation"); } // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GeneratePasswordResetTokenAsync(user); //var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Reset Password", // $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>"); //return View("ForgotPasswordConfirmation"); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ForgotPasswordConfirmation [HttpGet] [AllowAnonymous] public IActionResult ForgotPasswordConfirmation() { return View(); } // // GET: /Account/ResetPassword [HttpGet] [AllowAnonymous] public IActionResult ResetPassword(string code = null) { return code == null ? View("Error") : View(); } // // POST: /Account/ResetPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.FindByNameAsync(model.Email); if (user == null) { // Don't reveal that the user does not exist return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); } var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password); if (result.Succeeded) { return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); } AddErrors(result); return View(); } // // GET: /Account/ResetPasswordConfirmation [HttpGet] [AllowAnonymous] public IActionResult ResetPasswordConfirmation() { return View(); } // // GET: /Account/SendCode [HttpGet] [AllowAnonymous] public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false) { var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user); var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/SendCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> SendCode(SendCodeViewModel model) { if (!ModelState.IsValid) { return View(); } var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } // Generate the token and send it var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider); if (string.IsNullOrWhiteSpace(code)) { return View("Error"); } var message = "Your security code is: " + code; if (model.SelectedProvider == "Email") { await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message); } else if (model.SelectedProvider == "Phone") { await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message); } return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); } // // GET: /Account/VerifyCode [HttpGet] [AllowAnonymous] public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null) { // Require that the user has already logged in via username/password or external login var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/VerifyCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model) { if (!ModelState.IsValid) { return View(model); } // The following code protects for brute force attacks against the two factor codes. // If a user enters incorrect codes for a specified amount of time then the user account // will be locked out for a specified amount of time. var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser); if (result.Succeeded) { return RedirectToLocal(model.ReturnUrl); } if (result.IsLockedOut) { _logger.LogWarning(7, "User account locked out."); return View("Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid code."); return View(model); } } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } private Task<ApplicationUser> GetCurrentUserAsync() { return _userManager.GetUserAsync(HttpContext.User); } private IActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction(nameof(HomeController.Index), "Home"); } } #endregion } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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 Gallio.Common.Text; using Gallio.Runtime.ConsoleSupport; using Gallio.Runtime.ProgressMonitoring; using Gallio.Properties; namespace Gallio.Runtime.ProgressMonitoring { /// <summary> /// A console progress monitor presenter displays a simple tally of the amount of work /// to be done on the main task as a bar chart. /// </summary> /// <remarks> /// <para> /// The progress monitor responds to cancelation events at the console. /// </para> /// </remarks> public class RichConsoleProgressMonitorPresenter : BaseProgressMonitorPresenter { private readonly IRichConsole console; private int newlinesWritten; private bool bannerPrinted; private int width; private bool footerInitialized; /// <summary> /// Creates a console presenter for a progress monitor. /// </summary> /// <param name="console">The console.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="console"/> is null.</exception> public RichConsoleProgressMonitorPresenter(IRichConsole console) { if (console == null) throw new ArgumentNullException("console"); this.console = console; } /// <inheritdoc /> protected override void Initialize() { ProgressMonitor.TaskFinished += HandleTaskFinished; ProgressMonitor.Changed += HandleChanged; console.Cancel += HandleConsoleCancel; } private void HandleTaskFinished(object sender, EventArgs e) { console.Cancel -= HandleConsoleCancel; if (ProgressMonitor.IsCanceled) console.IsCanceled = false; } private void HandleConsoleCancel(object sender, EventArgs e) { ProgressMonitor.Cancel(); } private void HandleChanged(object sender, EventArgs e) { lock (console.SyncRoot) { ShowTaskBeginningBanner(); // Don't try to show real-time progress if output is redirected. // It can't work because we can't erase previously written text. if (console.IsRedirected) return; if (ProgressMonitor.IsDone) { footerInitialized = false; console.SetFooter(null, null); } else if (!footerInitialized) { footerInitialized = true; console.SetFooter(ShowFooter, HideFooter); } else if (console.FooterVisible) { RedrawFooter(true); } } } private void ShowTaskBeginningBanner() { // Just print the task name once. if (!bannerPrinted) { width = console.Width; console.ForegroundColor = ConsoleColor.White; console.WriteLine(StringUtils.TruncateWithEllipsis(ProgressMonitor.TaskName, width - 1)); console.ResetColor(); bannerPrinted = true; } } private void ShowFooter() { RedrawFooter(false); } private void HideFooter() { if (newlinesWritten > 0) { console.CursorTop -= newlinesWritten; for (int i = 0; i < newlinesWritten; i++) EraseLine(); console.CursorTop -= newlinesWritten; newlinesWritten = 0; } } private void RedrawFooter(bool inplace) { // Scroll enough new lines into view for the text we might want to write. // This helps to reduce flickering of the progress monitor. // We should still do much better than this if we improve the console API // to handle scrolling of independent regions. int oldNewlinesWritten = newlinesWritten; if (inplace) { console.CursorTop -= newlinesWritten - 1; } else { for (int i = 0; i < 5; i++) console.WriteLine(); console.CursorTop -= 4; } newlinesWritten = 1; // Write the progress monitor. console.ForegroundColor = ConsoleColor.White; console.Write(StringUtils.TruncateWithEllipsis(Sanitize(ProgressMonitor.TaskName), width - 20).PadRight(width - 19)); if (!ProgressMonitor.IsDone && !double.IsNaN(ProgressMonitor.TotalWorkUnits)) { console.ForegroundColor = ConsoleColor.Yellow; console.Write('['); console.ForegroundColor = ConsoleColor.DarkYellow; console.Write(new string('=', (int)Math.Round(ProgressMonitor.CompletedWorkUnits * 10 / ProgressMonitor.TotalWorkUnits)).PadRight(10)); console.ForegroundColor = ConsoleColor.Yellow; console.Write(@"] "); console.Write(Math.Floor(ProgressMonitor.CompletedWorkUnits * 100 / ProgressMonitor.TotalWorkUnits).ToString()); console.Write('%'); NewLine(inplace); string sanitizedSubTaskName = Sanitize(ProgressMonitor.LeafSubTaskName); if (sanitizedSubTaskName.Length != 0) { console.ForegroundColor = ConsoleColor.Gray; console.Write(@" "); console.Write(StringUtils.TruncateWithEllipsis(sanitizedSubTaskName, width - 3)); NewLine(inplace); } string sanitizedStatus = Sanitize(ProgressMonitor.Leaf.Status); if (sanitizedStatus.Length != 0) { console.ForegroundColor = ConsoleColor.DarkGreen; console.Write(@" "); console.Write(StringUtils.TruncateWithEllipsis(sanitizedStatus, width - 3)); NewLine(inplace); } } else NewLine(inplace); if (ProgressMonitor.IsCanceled) { console.ForegroundColor = ConsoleColor.Red; console.Write(@" "); console.Write(ProgressMonitor.IsDone ? Resources.ConsoleProgressMonitor_CanceledBanner : Resources.ConsoleProgressMonitor_CancelingBanner); NewLine(inplace); } console.ResetColor(); // Clear out the remaining dirty lines in place. if (inplace && oldNewlinesWritten > newlinesWritten) { int dirtyLines = oldNewlinesWritten - newlinesWritten; for (int i = 0; i < dirtyLines; i++) EraseLine(); console.CursorTop -= dirtyLines; } } private void NewLine(bool inplace) { newlinesWritten += 1; if (inplace) console.Write(new string(' ', width - console.CursorLeft)); else console.WriteLine(); } private void EraseLine() { console.CursorLeft = 0; console.Write(new string(' ', width)); } /// <summary> /// It can happen that we'll receive all kinds of weird input because /// task names and status messages can be derived from user-data. /// </summary> /// <remarks> /// <para> /// Make sure it doesn't corrupt the display integrity. /// </para> /// </remarks> private static string Sanitize(string str) { return str.Replace('\n', ' ').Replace("\r", @""); } } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using Moq.Behaviors; using Moq.Properties; namespace Moq { internal sealed partial class MethodCall : SetupWithOutParameterSupport { private LimitInvocationCount limitInvocationCount; private Behavior callback; private Behavior raiseEvent; private Behavior returnOrThrow; private Behavior afterReturnCallback; private Condition condition; private string failMessage; private string declarationSite; public MethodCall(Expression originalExpression, Mock mock, Condition condition, InvocationShape expectation) : base(originalExpression, mock, expectation) { this.condition = condition; if ((mock.Switches & Switches.CollectDiagnosticFileInfoForSetups) != 0) { this.declarationSite = GetUserCodeCallSite(); } } public string FailMessage { get => this.failMessage; } public override Condition Condition => this.condition; private static string GetUserCodeCallSite() { try { var thisMethod = MethodBase.GetCurrentMethod(); var mockAssembly = Assembly.GetExecutingAssembly(); var frame = new StackTrace(true) .GetFrames() .SkipWhile(f => f.GetMethod() != thisMethod) .SkipWhile(f => f.GetMethod().DeclaringType == null || f.GetMethod().DeclaringType.Assembly == mockAssembly) .FirstOrDefault(); var member = frame?.GetMethod(); if (member != null) { var declaredAt = new StringBuilder(); declaredAt.AppendNameOf(member.DeclaringType).Append('.').AppendNameOf(member, false); var fileName = Path.GetFileName(frame.GetFileName()); if (fileName != null) { declaredAt.Append(" in ").Append(fileName); var lineNumber = frame.GetFileLineNumber(); if (lineNumber != 0) { declaredAt.Append(": line ").Append(lineNumber); } } return declaredAt.ToString(); } } catch { // Must NEVER fail, as this is a nice-to-have feature only. } return null; } protected override void ExecuteCore(Invocation invocation) { this.limitInvocationCount?.Execute(invocation); this.callback?.Execute(invocation); this.raiseEvent?.Execute(invocation); if (this.returnOrThrow != null) { this.returnOrThrow.Execute(invocation); } else if (invocation.Method.ReturnType != typeof(void)) { if (this.Mock.Behavior == MockBehavior.Strict) { throw MockException.ReturnValueRequired(invocation); } else { new ReturnBaseOrDefaultValue(this.Mock).Execute(invocation); } } this.afterReturnCallback?.Execute(invocation); } public override bool TryGetReturnValue(out object returnValue) { if (this.returnOrThrow is ReturnValue rv) { returnValue = rv.Value; return true; } else { returnValue = default; return false; } } public void SetCallBaseBehavior() { if (this.Mock.MockedType.IsDelegateType()) { throw new NotSupportedException(Resources.CallBaseCannotBeUsedWithDelegateMocks); } this.returnOrThrow = ReturnBase.Instance; } public void SetCallbackBehavior(Delegate callback) { if (callback == null) { throw new ArgumentNullException(nameof(callback)); } ref Behavior behavior = ref (this.returnOrThrow == null) ? ref this.callback : ref this.afterReturnCallback; if (callback is Action callbackWithoutArguments) { behavior = new Callback(_ => callbackWithoutArguments()); } else if (callback.GetType() == typeof(Action<IInvocation>)) { // NOTE: Do NOT rewrite the above condition as `callback is Action<IInvocation>`, // because this will also yield true if `callback` is a `Action<object>` and thus // break existing uses of `(object arg) => ...` callbacks! behavior = new Callback((Action<IInvocation>)callback); } else { var expectedParamTypes = this.Method.GetParameterTypes(); if (!callback.CompareParameterTypesTo(expectedParamTypes)) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Resources.InvalidCallbackParameterMismatch, this.Method.GetParameterTypeList(), callback.GetMethodInfo().GetParameterTypeList())); } if (callback.GetMethodInfo().ReturnType != typeof(void)) { throw new ArgumentException(Resources.InvalidCallbackNotADelegateWithReturnTypeVoid, nameof(callback)); } behavior = new Callback(invocation => callback.InvokePreserveStack(invocation.Arguments)); } } public void SetFailMessage(string failMessage) { this.failMessage = failMessage; } public void SetRaiseEventBehavior<TMock>(Action<TMock> eventExpression, Delegate func) where TMock : class { Guard.NotNull(eventExpression, nameof(eventExpression)); var expression = ExpressionReconstructor.Instance.ReconstructExpression(eventExpression, this.Mock.ConstructorArguments); // TODO: validate that expression is for event subscription or unsubscription this.raiseEvent = new RaiseEvent(this.Mock, expression, func, null); } public void SetRaiseEventBehavior<TMock>(Action<TMock> eventExpression, params object[] args) where TMock : class { Guard.NotNull(eventExpression, nameof(eventExpression)); var expression = ExpressionReconstructor.Instance.ReconstructExpression(eventExpression, this.Mock.ConstructorArguments); // TODO: validate that expression is for event subscription or unsubscription this.raiseEvent = new RaiseEvent(this.Mock, expression, null, args); } public void SetReturnValueBehavior(object value) { Debug.Assert(this.Method.ReturnType != typeof(void)); Debug.Assert(this.returnOrThrow == null); this.returnOrThrow = new ReturnValue(value); } public void SetReturnComputedValueBehavior(Delegate valueFactory) { Debug.Assert(this.Method.ReturnType != typeof(void)); Debug.Assert(this.returnOrThrow == null); if (valueFactory == null) { // A `null` reference (instead of a valid delegate) is interpreted as the actual return value. // This is necessary because the compiler might have picked the unexpected overload for calls // like `Returns(null)`, or the user might have picked an overload like `Returns<T>(null)`, // and instead of in `Returns(TResult)`, we ended up in `Returns(Delegate)` or `Returns(Func)`, // which likely isn't what the user intended. // So here we do what we would've done in `Returns(TResult)`: this.returnOrThrow = new ReturnValue(this.Method.ReturnType.GetDefaultValue()); } else if (this.Method.ReturnType == typeof(Delegate)) { // If `TResult` is `Delegate`, that is someone is setting up the return value of a method // that returns a `Delegate`, then we have arrived here because C# picked the wrong overload: // We don't want to invoke the passed delegate to get a return value; the passed delegate // already is the return value. this.returnOrThrow = new ReturnValue(valueFactory); } else if (IsInvocationFunc(valueFactory)) { this.returnOrThrow = new ReturnComputedValue(invocation => valueFactory.DynamicInvoke(invocation)); } else { ValidateCallback(valueFactory); if (valueFactory.CompareParameterTypesTo(Type.EmptyTypes)) { // we need this for the user to be able to use parameterless methods this.returnOrThrow = new ReturnComputedValue(invocation => valueFactory.InvokePreserveStack()); } else { this.returnOrThrow = new ReturnComputedValue(invocation => valueFactory.InvokePreserveStack(invocation.Arguments)); } } bool IsInvocationFunc(Delegate callback) { var type = callback.GetType(); if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Func<,>)) { var typeArguments = type.GetGenericArguments(); return typeArguments[0] == typeof(IInvocation) && (typeArguments[1] == typeof(object) || this.Method.ReturnType.IsAssignableFrom(typeArguments[1])); } return false; } void ValidateCallback(Delegate callback) { var callbackMethod = callback.GetMethodInfo(); // validate number of parameters: var numberOfActualParameters = callbackMethod.GetParameters().Length; if (callbackMethod.IsStatic) { if (callbackMethod.IsExtensionMethod() || callback.Target != null) { numberOfActualParameters--; } } if (numberOfActualParameters > 0) { var numberOfExpectedParameters = this.Method.GetParameters().Length; if (numberOfActualParameters != numberOfExpectedParameters) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Resources.InvalidCallbackParameterCountMismatch, numberOfExpectedParameters, numberOfActualParameters)); } } // validate return type: var actualReturnType = callbackMethod.ReturnType; if (actualReturnType == typeof(void)) { throw new ArgumentException(Resources.InvalidReturnsCallbackNotADelegateWithReturnType); } var expectedReturnType = this.Method.ReturnType; if (!expectedReturnType.IsAssignableFrom(actualReturnType)) { // TODO: If the return type is a matcher, does the callback's return type need to be matched against it? if (typeof(ITypeMatcher).IsAssignableFrom(expectedReturnType) == false) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Resources.InvalidCallbackReturnTypeMismatch, expectedReturnType, actualReturnType)); } } } } public void SetThrowExceptionBehavior(Exception exception) { this.returnOrThrow = new ThrowException(exception); } protected override void ResetCore() { this.limitInvocationCount?.Reset(); } public void AtMost(int count) { this.limitInvocationCount = new LimitInvocationCount(this, count); } public override string ToString() { var message = new StringBuilder(); if (this.failMessage != null) { message.Append(this.failMessage).Append(": "); } message.Append(base.ToString()); if (this.declarationSite != null) { message.Append(" (").Append(this.declarationSite).Append(')'); } return message.ToString().Trim(); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Reflection; using NBot.Core.Attributes; using NBot.Core.Brains; using NBot.Core.Help; using NBot.Core.Logging; using NBot.Core.MessageFilters; using NBot.Core.Routes; using ServiceStack; namespace NBot.Core { public class RobotBuilder { private readonly RobotConfiguration _configuration; private readonly List<MessageHandlerRegistration> _messageHandlerRegistrations = new List<MessageHandlerRegistration>(); private readonly List<Func<RobotConfiguration, IMessageFilter>> _messagFilterRegistrations = new List<Func<RobotConfiguration, IMessageFilter>>(); private readonly Dictionary<string, Func<RobotConfiguration, IAdapter>> _adapterRegistrations = new Dictionary<string, Func<RobotConfiguration, IAdapter>>(); private readonly Dictionary<string, HelpInformation> _helpers = new Dictionary<string, HelpInformation>(); public RobotBuilder(string name = "nbot", string alias = "nbot", string environment = "debug") { _configuration = new RobotConfiguration(name, alias, environment); LoadSettings(); } public RobotBuilder AddSetting<T>(string key, T value) { _configuration.Settings[key] = value; return this; } public RobotBuilder UseBrain(IBrain brain) { _configuration.Brain = brain; return this; } public RobotBuilder UseBrain(Func<Dictionary<string, object>, IBrain> brainActivation) { return UseBrain(brainActivation(_configuration.Settings)); } public RobotBuilder UseLog(INBotLog log) { _configuration.Log = log; return this; } public RobotBuilder UseLog(Func<Dictionary<string, object>, INBotLog> logActivation) { return UseLog(logActivation(_configuration.Settings)); } public RobotBuilder RegisterAdapter(string channel, IAdapter adapter) { _adapterRegistrations[channel] = configuration => adapter; return this; } public RobotBuilder RegisterAdapter(string channel, Func<RobotConfiguration, IAdapter> adapterRegistration) { _adapterRegistrations[channel] = adapterRegistration; return this; } public RobotBuilder RegisterMessageHandler(IMessageHandler messageHandler, params string[] allowedRooms) { return RegisterMessageHandler(configuration => messageHandler, allowedRooms); } public RobotBuilder RegisterMessageHandler(Func<RobotConfiguration, IMessageHandler> registrationFunction, params string[] allowedRooms) { _messageHandlerRegistrations.Add(new MessageHandlerRegistration(registrationFunction, allowedRooms)); return this; } public RobotBuilder RegisterMessageFilter(IMessageFilter messageFilter) { return RegisterMessageFilter(configuration => messageFilter); } public RobotBuilder RegisterMessageFilter(Func<RobotConfiguration, IMessageFilter> registration) { _messagFilterRegistrations.Add(registration); return this; } public Robot Build() { var result = new Robot(_configuration.Name, _configuration.Alias, _configuration.Environment, _configuration.Settings, _configuration.Brain, _configuration.Log); var filters = BuildFilters(); var routes = BuildRoutes().Union(BuildRoute(new Help.Help(_helpers.Values), null)).ToList(); var adapters = BuildAdapters(filters.ToList()); result.Initalize(routes, adapters); return result; } public void Run() { Build().Run(); } private IEnumerable<IMessageFilter> BuildFilters() { return _messagFilterRegistrations.Select(messagFilterRegistration => messagFilterRegistration(_configuration)); } private Dictionary<string, IAdapter> BuildAdapters(List<IMessageFilter> filters) { var result = new Dictionary<string, IAdapter>(); foreach (var channel in _adapterRegistrations.Keys) { var adapter = _adapterRegistrations[channel](_configuration); if (result.ContainsKey(channel)) throw new ApplicationException("There is already an adapter registered on that channel."); var filteredAdapter = new MessageFilterAdapter(adapter, filters); result.Add(channel, filteredAdapter); } return result; } private IEnumerable<IRoute> BuildRoutes() { return from messageHandlerRegistration in _messageHandlerRegistrations let handler = messageHandlerRegistration.RegistrationFunction(_configuration) let allowedRooms = messageHandlerRegistration.AllowedRooms from route in BuildRoute(handler, allowedRooms) select route; } private IEnumerable<IRoute> BuildRoute(IMessageHandler handler, string[] allowedRooms) { UpdateHelpInformation(handler); Type handlerType = handler.GetType(); foreach (MethodInfo endpoint in handlerType.GetMethods(BindingFlags.Public | BindingFlags.Instance)) { object[] messageAttributes = endpoint.GetCustomAttributes(typeof(HandleMessageAttribute), true); foreach (HandleMessageAttribute messageAttribute in messageAttributes) { IRoute route = messageAttribute.CreateRoute(handler, endpoint); yield return allowedRooms == null || !allowedRooms.Any() ? route : new RoomSecurityRoute(route, allowedRooms); } } } private void LoadSettings() { foreach (var key in ConfigurationManager.AppSettings.AllKeys) { var keyTaxonomy = key.Split(new[] { ':', '/' }, StringSplitOptions.RemoveEmptyEntries); if (keyTaxonomy.Length == 2 && keyTaxonomy[0].ToLower() == "nbot") { AddSetting(keyTaxonomy[1], ConfigurationManager.AppSettings[key]); } } } private void UpdateHelpInformation(IMessageHandler handler) { Type type = handler.GetType(); foreach (MethodInfo methodInfo in type.GetMethods(BindingFlags.Instance | BindingFlags.Public)) { object[] helpAttributes = methodInfo.GetCustomAttributes(typeof(HelpAttribute), true); if (!_helpers.ContainsKey(type.Name)) { var helper = new HelpInformation { Plugin = type.Name, Commands = new List<Command>() }; _helpers.Add(type.Name, helper); } foreach (HelpAttribute helpAttribute in helpAttributes) { _helpers[type.Name].Commands.Add(new Command(helpAttribute.Syntax.FormatWith(_configuration.Name, _configuration.Alias), helpAttribute.Description.FormatWith(_configuration.Name, _configuration.Alias), helpAttribute.Example.FormatWith(_configuration.Name, _configuration.Alias))); } } } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; namespace Rainbow.Content.Charts { //********************************************************************* // // BarGraph Class // // This class uses GDI+ to render Bar Chart. // //********************************************************************* /// <summary> /// One of the Graphing classes from the reporting asp.net starter kit /// on www.asp.net - http://www.asp.net/Default.aspx?tabindex=9&amp;tabID=47 /// Made very minor changes to the code to use with monitoring module. /// Imported by Paul Yarrow, paul@paulyarrow.com /// </summary> public class BarGraph : Chart { private const float _graphLegendSpacer = 15F; private const int _labelFontSize = 7; private const int _legendFontSize = 9; private const float _legendRectangleSize = 10F; private const float _spacer = 5F; // Overall related members private Color _backColor; private string _fontFamily; private string _longestTickValue = string.Empty; // Used to calculate max value width private float _maxTickValueWidth; // Used to calculate left offset of bar graph private float _totalHeight; private float _totalWidth; // Graph related members private float _barWidth; private float _bottomBuffer; // Space from bottom to x axis private bool _displayBarData; private Color _fontColor; private float _graphHeight; private float _graphWidth; private float _maxValue = 0.0f; // = final tick value * tick count private float _scaleFactor; // = _maxValue / _graphHeight private float _spaceBtwBars; // For now same as _barWidth private float _topBuffer; // Space from top to the top of y axis private float _xOrigin; // x position where graph starts drawing private float _yOrigin; // y position where graph starts drawing private string _yLabel; private int _yTickCount; private float _yTickValue; // Value for each tick = _maxValue/_yTickCount // Legend related members private bool _displayLegend; private float _legendWidth; private string _longestLabel = string.Empty; // Used to calculate legend width private float _maxLabelWidth = 0.0f; /// <summary> /// Gets or sets the font family. /// </summary> /// <value>The font family.</value> public string FontFamily { get { return _fontFamily; } set { _fontFamily = value; } } /// <summary> /// Sets the color of the background. /// </summary> /// <value>The color of the background.</value> public Color BackgroundColor { set { _backColor = value; } } /// <summary> /// Sets the bottom buffer. /// </summary> /// <value>The bottom buffer.</value> public int BottomBuffer { set { _bottomBuffer = Convert.ToSingle(value); } } /// <summary> /// Sets the color of the font. /// </summary> /// <value>The color of the font.</value> public Color FontColor { set { _fontColor = value; } } /// <summary> /// Gets or sets the height. /// </summary> /// <value>The height.</value> public int Height { get { return Convert.ToInt32(_totalHeight); } set { _totalHeight = Convert.ToSingle(value); } } /// <summary> /// Gets or sets the width. /// </summary> /// <value>The width.</value> public int Width { get { return Convert.ToInt32(_totalWidth); } set { _totalWidth = Convert.ToSingle(value); } } /// <summary> /// Gets or sets a value indicating whether [show legend]. /// </summary> /// <value><c>true</c> if [show legend]; otherwise, <c>false</c>.</value> public bool ShowLegend { get { return _displayLegend; } set { _displayLegend = value; } } /// <summary> /// Gets or sets a value indicating whether [show data]. /// </summary> /// <value><c>true</c> if [show data]; otherwise, <c>false</c>.</value> public bool ShowData { get { return _displayBarData; } set { _displayBarData = value; } } /// <summary> /// Sets the top buffer. /// </summary> /// <value>The top buffer.</value> public int TopBuffer { set { _topBuffer = Convert.ToSingle(value); } } /// <summary> /// Gets or sets the vertical label. /// </summary> /// <value>The vertical label.</value> public string VerticalLabel { get { return _yLabel; } set { _yLabel = value; } } /// <summary> /// Gets or sets the vertical tick count. /// </summary> /// <value>The vertical tick count.</value> public int VerticalTickCount { get { return _yTickCount; } set { _yTickCount = value; } } /// <summary> /// Initializes a new instance of the <see cref="T:BarGraph"/> class. /// </summary> public BarGraph() { AssignDefaultSettings(); } /// <summary> /// Initializes a new instance of the <see cref="T:BarGraph"/> class. /// </summary> /// <param name="bgColor">Color of the bg.</param> public BarGraph(Color bgColor) { AssignDefaultSettings(); BackgroundColor = bgColor; } //********************************************************************* // // This method collects all data points and calculate all the necessary dimensions // to draw the bar graph. It is the method called before invoking the Draw() method. // labels is the x values. // values is the y values. // //********************************************************************* /// <summary> /// Collects the data points. /// </summary> /// <param name="labels">The labels.</param> /// <param name="values">The values.</param> public void CollectDataPoints(string[] labels, string[] values) { if (labels.Length == values.Length) { for (int i = 0; i < labels.Length; i++) { float temp = Convert.ToSingle(values[i]); string shortLbl = MakeShortLabel(labels[i]); // For now put 0.0 for start position and sweep size DataPoints.Add(new ChartItem(shortLbl, labels[i], temp, 0.0f, 0.0f, GetColor(i))); // Find max value from data; this is only temporary _maxValue if (_maxValue < temp) _maxValue = temp; // Find the longest description if (_displayLegend) { string currentLbl = labels[i] + " (" + shortLbl + ")"; float currentWidth = CalculateImgFontWidth(currentLbl, _legendFontSize, FontFamily); if (_maxLabelWidth < currentWidth) { _longestLabel = currentLbl; _maxLabelWidth = currentWidth; } } } CalculateTickAndMax(); CalculateGraphDimension(); CalculateBarWidth(DataPoints.Count, _graphWidth); CalculateSweepValues(); } else throw new Exception("X data count is different from Y data count"); } //********************************************************************* // // Same as above; called when user doesn't care about the x values // //********************************************************************* /// <summary> /// Collects the data points. /// </summary> /// <param name="values">The values.</param> public void CollectDataPoints(string[] values) { string[] labels = values; CollectDataPoints(labels, values); } //********************************************************************* // // This method returns a bar graph bitmap to the calling function. It is called after // all dimensions and data points are calculated. // //********************************************************************* /// <summary> /// Draws this instance. /// </summary> /// <returns></returns> public override Bitmap Draw() { int height = Convert.ToInt32(_totalHeight); int width = Convert.ToInt32(_totalWidth); Bitmap bmp = new Bitmap(width, height); using (Graphics graph = Graphics.FromImage(bmp)) { graph.CompositingQuality = CompositingQuality.HighQuality; graph.SmoothingMode = SmoothingMode.AntiAlias; // Set the background: need to draw one pixel larger than the bitmap to cover all area graph.FillRectangle(new SolidBrush(_backColor), -1, -1, bmp.Width + 1, bmp.Height + 1); DrawVerticalLabelArea(graph); DrawBars(graph); DrawXLabelArea(graph); if (_displayLegend) DrawLegend(graph); } return bmp; } //********************************************************************* // // This method draws all the bars for the graph. // //********************************************************************* /// <summary> /// Draws the bars. /// </summary> /// <param name="graph">The graph.</param> private void DrawBars(Graphics graph) { SolidBrush brsFont = null; Font valFont = null; StringFormat sfFormat = null; try { brsFont = new SolidBrush(_fontColor); valFont = new Font(_fontFamily, _labelFontSize); sfFormat = new StringFormat(); sfFormat.Alignment = StringAlignment.Center; int i = 0; // Draw bars and the value above each bar foreach (ChartItem item in DataPoints) { using (SolidBrush barBrush = new SolidBrush(item.ItemColor)) { float itemY = _yOrigin + _graphHeight - item.SweepSize; // When drawing, all position is relative to (_xOrigin, _yOrigin) graph.FillRectangle(barBrush, _xOrigin + item.StartPos, itemY, _barWidth, item.SweepSize); // Draw data value if (_displayBarData) { float startX = _xOrigin + (i*(_barWidth + _spaceBtwBars)); // This draws the value on center of the bar float startY = itemY - 2f - valFont.Height; // Positioned on top of each bar by 2 pixels RectangleF recVal = new RectangleF(startX, startY, _barWidth + _spaceBtwBars, valFont.Height); graph.DrawString(item.Value.ToString("#,###.##"), valFont, brsFont, recVal, sfFormat); } i++; } } } finally { if (brsFont != null) brsFont.Dispose(); if (valFont != null) valFont.Dispose(); if (sfFormat != null) sfFormat.Dispose(); } } //********************************************************************* // // This method draws the y label, tick marks, tick values, and the y axis. // //********************************************************************* /// <summary> /// Draws the vertical label area. /// </summary> /// <param name="graph">The graph.</param> private void DrawVerticalLabelArea(Graphics graph) { Font lblFont = null; SolidBrush brs = null; StringFormat lblFormat = null; Pen pen = null; StringFormat sfVLabel = null; try { lblFont = new Font(_fontFamily, _labelFontSize); brs = new SolidBrush(_fontColor); lblFormat = new StringFormat(); pen = new Pen(_fontColor); sfVLabel = new StringFormat(); lblFormat.Alignment = StringAlignment.Near; // Draw vertical label at the top of y-axis and place it in the middle top of y-axis RectangleF recVLabel = new RectangleF(0f, _yOrigin - 2*_spacer - lblFont.Height, _xOrigin*2, lblFont.Height); sfVLabel.Alignment = StringAlignment.Center; graph.DrawString(_yLabel, lblFont, brs, recVLabel, sfVLabel); // Draw all tick values and tick marks for (int i = 0; i < _yTickCount; i++) { float currentY = _topBuffer + (i*_yTickValue/_scaleFactor); // Position for tick mark float labelY = currentY - lblFont.Height/2; // Place label in the middle of tick RectangleF lblRec = new RectangleF(_spacer, labelY, _maxTickValueWidth, lblFont.Height); float currentTick = _maxValue - i*_yTickValue; // Calculate tick value from top to bottom graph.DrawString(currentTick.ToString("#,###.##"), lblFont, brs, lblRec, lblFormat); // Draw tick value graph.DrawLine(pen, _xOrigin, currentY, _xOrigin - 4.0f, currentY); // Draw tick mark } // Draw y axis graph.DrawLine(pen, _xOrigin, _yOrigin, _xOrigin, _yOrigin + _graphHeight); } finally { if (lblFont != null) lblFont.Dispose(); if (brs != null) brs.Dispose(); if (lblFormat != null) lblFormat.Dispose(); if (pen != null) pen.Dispose(); if (sfVLabel != null) sfVLabel.Dispose(); } } //********************************************************************* // // This method draws x axis and all x labels // //********************************************************************* /// <summary> /// Draws the X label area. /// </summary> /// <param name="graph">The graph.</param> private void DrawXLabelArea(Graphics graph) { Font lblFont = null; SolidBrush brs = null; StringFormat lblFormat = null; Pen pen = null; try { lblFont = new Font(_fontFamily, _labelFontSize); brs = new SolidBrush(_fontColor); lblFormat = new StringFormat(); pen = new Pen(_fontColor); lblFormat.Alignment = StringAlignment.Center; // Draw x axis graph.DrawLine(pen, _xOrigin, _yOrigin + _graphHeight, _xOrigin + _graphWidth, _yOrigin + _graphHeight); float currentX; float currentY = _yOrigin + _graphHeight + 2.0f; // All x labels are drawn 2 pixels below x-axis float labelWidth = _barWidth + _spaceBtwBars; // Fits exactly below the bar int i = 0; // Draw x labels foreach (ChartItem item in DataPoints) { currentX = _xOrigin + (i*labelWidth); RectangleF recLbl = new RectangleF(currentX, currentY, labelWidth, lblFont.Height); string lblString = _displayLegend ? item.Label : item.Description; // Decide what to show: short or long graph.DrawString(lblString, lblFont, brs, recLbl, lblFormat); i++; } } finally { if (lblFont != null) lblFont.Dispose(); if (brs != null) brs.Dispose(); if (lblFormat != null) lblFormat.Dispose(); if (pen != null) pen.Dispose(); } } //********************************************************************* // // This method determines where to place the legend box. // It draws the legend border, legend description, and legend color code. // //********************************************************************* /// <summary> /// Draws the legend. /// </summary> /// <param name="graph">The graph.</param> private void DrawLegend(Graphics graph) { Font lblFont = null; SolidBrush brs = null; StringFormat lblFormat = null; Pen pen = null; try { lblFont = new Font(_fontFamily, _legendFontSize); brs = new SolidBrush(_fontColor); lblFormat = new StringFormat(); pen = new Pen(_fontColor); lblFormat.Alignment = StringAlignment.Near; // Calculate Legend drawing start point float startX = _xOrigin + _graphWidth + _graphLegendSpacer; float startY = _yOrigin; float xColorCode = startX + _spacer; float xLegendText = xColorCode + _legendRectangleSize + _spacer; float legendHeight = 0.0f; for (int i = 0; i < DataPoints.Count; i++) { ChartItem point = DataPoints[i]; string text = point.Description + " (" + point.Label + ")"; float currentY = startY + _spacer + (i*(lblFont.Height + _spacer)); legendHeight += lblFont.Height + _spacer; // Draw legend description graph.DrawString(text, lblFont, brs, xLegendText, currentY, lblFormat); // Draw color code graph.FillRectangle(new SolidBrush(DataPoints[i].ItemColor), xColorCode, currentY + 3f, _legendRectangleSize, _legendRectangleSize); } // Draw legend border graph.DrawRectangle(pen, startX, startY, _legendWidth, legendHeight + _spacer); } finally { if (lblFont != null) lblFont.Dispose(); if (brs != null) brs.Dispose(); if (lblFormat != null) lblFormat.Dispose(); if (pen != null) pen.Dispose(); } } //********************************************************************* // // This method calculates all measurement aspects of the bar graph from the given data points // //********************************************************************* /// <summary> /// Calculates the graph dimension. /// </summary> private void CalculateGraphDimension() { FindLongestTickValue(); // Need to add another character for spacing; this is not used for drawing, just for calculation _longestTickValue += "0"; _maxTickValueWidth = CalculateImgFontWidth(_longestTickValue, _labelFontSize, FontFamily); float leftOffset = _spacer + _maxTickValueWidth; float rtOffset = 0.0f; if (_displayLegend) { _legendWidth = _spacer + _legendRectangleSize + _spacer + _maxLabelWidth + _spacer; rtOffset = _graphLegendSpacer + _legendWidth + _spacer; } else rtOffset = _spacer; // Make graph in the middle _graphHeight = _totalHeight - _topBuffer - _bottomBuffer; // Buffer spaces are used to print labels _graphWidth = _totalWidth - leftOffset - rtOffset; _xOrigin = leftOffset; _yOrigin = _topBuffer; // Once the correct _maxValue is determined, then calculate _scaleFactor _scaleFactor = _maxValue/_graphHeight; } //********************************************************************* // // This method determines the longest tick value from the given data points. // The result is needed to calculate the correct graph dimension. // //********************************************************************* /// <summary> /// Finds the longest tick value. /// </summary> private void FindLongestTickValue() { float currentTick; string tickString; for (int i = 0; i < _yTickCount; i++) { currentTick = _maxValue - i*_yTickValue; tickString = currentTick.ToString("#,###.##"); if (_longestTickValue.Length < tickString.Length) _longestTickValue = tickString; } } //********************************************************************* // // This method calculates the image width in pixel for a given text // //********************************************************************* /// <summary> /// Calculates the width of the img font. /// </summary> /// <param name="text">The text.</param> /// <param name="size">The size.</param> /// <param name="family">The family.</param> /// <returns></returns> private float CalculateImgFontWidth(string text, int size, string family) { Bitmap bmp = null; Graphics graph = null; Font font = null; try { font = new Font(family, size); // Calculate the size of the string. bmp = new Bitmap(1, 1, PixelFormat.Format32bppArgb); graph = Graphics.FromImage(bmp); SizeF oSize = graph.MeasureString(text, font); return oSize.Width; } finally { if (graph != null) graph.Dispose(); if (bmp != null) bmp.Dispose(); if (font != null) font.Dispose(); } } //********************************************************************* // // This method creates abbreviation from long description; used for making legend // //********************************************************************* /// <summary> /// Makes the short label. /// </summary> /// <param name="text">The text.</param> /// <returns></returns> private string MakeShortLabel(string text) { string label = text; if (text.Length > 2) { int midPostition = Convert.ToInt32(Math.Floor((double) text.Length/2)); label = text.Substring(0, 1) + text.Substring(midPostition, 1) + text.Substring(text.Length - 1, 1); } return label; } //********************************************************************* // // This method calculates the max value and each tick mark value for the bar graph. // //********************************************************************* /// <summary> /// Calculates the tick and max. /// </summary> private void CalculateTickAndMax() { float tempMax = 0.0f; // Give graph some head room first about 10% of current max _maxValue *= 1.1f; if (_maxValue != 0.0f) { // Find a rounded value nearest to the current max value // Calculate this max first to give enough space to draw value on each bar double exp = Convert.ToDouble(Math.Floor(Math.Log10(_maxValue))); tempMax = Convert.ToSingle(Math.Ceiling(_maxValue/Math.Pow(10, exp))*Math.Pow(10, exp)); } else tempMax = 1.0f; // Once max value is calculated, tick value can be determined; tick value should be a whole number _yTickValue = tempMax/_yTickCount; double expTick = Convert.ToDouble(Math.Floor(Math.Log10(_yTickValue))); _yTickValue = Convert.ToSingle(Math.Ceiling(_yTickValue/Math.Pow(10, expTick))*Math.Pow(10, expTick)); // Re-calculate the max value with the new tick value _maxValue = _yTickValue*_yTickCount; } //********************************************************************* // // This method calculates the height for each bar in the graph // //********************************************************************* private void CalculateSweepValues() { // Called when all values and scale factor are known // All values calculated here are relative from (_xOrigin, _yOrigin) int i = 0; foreach (ChartItem item in DataPoints) { // This implementation does not support negative value if (item.Value >= 0) item.SweepSize = item.Value/_scaleFactor; // (_spaceBtwBars/2) makes half white space for the first bar item.StartPos = (_spaceBtwBars/2) + i*(_barWidth + _spaceBtwBars); i++; } } //********************************************************************* // // This method calculates the width for each bar in the graph // //********************************************************************* /// <summary> /// Calculates the width of the bar. /// </summary> /// <param name="dataCount">The data count.</param> /// <param name="barGraphWidth">Width of the bar graph.</param> private void CalculateBarWidth(int dataCount, float barGraphWidth) { // White space between each bar is the same as bar width itself _barWidth = barGraphWidth/(dataCount*2); // Each bar has 1 white space _spaceBtwBars = _barWidth; } //********************************************************************* // // This method assigns default value to the bar graph properties and is only // called from BarGraph constructors // //********************************************************************* /// <summary> /// Assigns the default settings. /// </summary> private void AssignDefaultSettings() { // default values _totalWidth = 700f; _totalHeight = 450f; _fontFamily = "Verdana"; _backColor = Color.White; _fontColor = Color.Black; _topBuffer = 30f; _bottomBuffer = 30f; _yTickCount = 2; _displayLegend = false; _displayBarData = false; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management; using Microsoft.WindowsAzure.Management.Models; namespace Microsoft.WindowsAzure.Management { /// <summary> /// You can use management certificates, which are also known as /// subscription certificates, to authenticate clients attempting to /// connect to resources associated with your Windows Azure subscription. /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154124.aspx for /// more information) /// </summary> internal partial class ManagementCertificateOperations : IServiceOperations<ManagementClient>, IManagementCertificateOperations { /// <summary> /// Initializes a new instance of the ManagementCertificateOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ManagementCertificateOperations(ManagementClient client) { this._client = client; } private ManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.ManagementClient. /// </summary> public ManagementClient Client { get { return this._client; } } /// <summary> /// The Add Management Certificate operation adds a certificate to the /// list of management certificates. Management certificates, which /// are also known as subscription certificates, authenticate clients /// attempting to connect to resources associated with your Windows /// Azure subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154123.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Parameters supplied to the Create Management Certificate operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<OperationResponse> CreateAsync(ManagementCertificateCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/certificates"; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement subscriptionCertificateElement = new XElement(XName.Get("SubscriptionCertificate", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(subscriptionCertificateElement); if (parameters.PublicKey != null) { XElement subscriptionCertificatePublicKeyElement = new XElement(XName.Get("SubscriptionCertificatePublicKey", "http://schemas.microsoft.com/windowsazure")); subscriptionCertificatePublicKeyElement.Value = Convert.ToBase64String(parameters.PublicKey); subscriptionCertificateElement.Add(subscriptionCertificatePublicKeyElement); } if (parameters.Thumbprint != null) { XElement subscriptionCertificateThumbprintElement = new XElement(XName.Get("SubscriptionCertificateThumbprint", "http://schemas.microsoft.com/windowsazure")); subscriptionCertificateThumbprintElement.Value = parameters.Thumbprint; subscriptionCertificateElement.Add(subscriptionCertificateThumbprintElement); } if (parameters.Data != null) { XElement subscriptionCertificateDataElement = new XElement(XName.Get("SubscriptionCertificateData", "http://schemas.microsoft.com/windowsazure")); subscriptionCertificateDataElement.Value = Convert.ToBase64String(parameters.Data); subscriptionCertificateElement.Add(subscriptionCertificateDataElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Delete Management Certificate operation deletes a certificate /// from the list of management certificates. Management certificates, /// which are also known as subscription certificates, authenticate /// clients attempting to connect to resources associated with your /// Windows Azure subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154127.aspx /// for more information) /// </summary> /// <param name='thumbprint'> /// the thumbprint value of the certificate to delete. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<OperationResponse> DeleteAsync(string thumbprint, CancellationToken cancellationToken) { // Validate if (thumbprint == null) { throw new ArgumentNullException("thumbprint"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("thumbprint", thumbprint); Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/certificates/" + thumbprint; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NotFound) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Get Management Certificate operation retrieves information /// about the management certificate with the specified thumbprint. /// Management certificates, which are also known as subscription /// certificates, authenticate clients attempting to connect to /// resources associated with your Windows Azure subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154131.aspx /// for more information) /// </summary> /// <param name='thumbprint'> /// The thumbprint value of the certificate to retrieve information /// about. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Management Certificate operation response. /// </returns> public async Task<ManagementCertificateGetResponse> GetAsync(string thumbprint, CancellationToken cancellationToken) { // Validate if (thumbprint == null) { throw new ArgumentNullException("thumbprint"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("thumbprint", thumbprint); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/certificates/" + thumbprint; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ManagementCertificateGetResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ManagementCertificateGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement subscriptionCertificateElement = responseDoc.Element(XName.Get("SubscriptionCertificate", "http://schemas.microsoft.com/windowsazure")); if (subscriptionCertificateElement != null) { XElement subscriptionCertificatePublicKeyElement = subscriptionCertificateElement.Element(XName.Get("SubscriptionCertificatePublicKey", "http://schemas.microsoft.com/windowsazure")); if (subscriptionCertificatePublicKeyElement != null) { byte[] subscriptionCertificatePublicKeyInstance = Convert.FromBase64String(subscriptionCertificatePublicKeyElement.Value); result.PublicKey = subscriptionCertificatePublicKeyInstance; } XElement subscriptionCertificateThumbprintElement = subscriptionCertificateElement.Element(XName.Get("SubscriptionCertificateThumbprint", "http://schemas.microsoft.com/windowsazure")); if (subscriptionCertificateThumbprintElement != null) { string subscriptionCertificateThumbprintInstance = subscriptionCertificateThumbprintElement.Value; result.Thumbprint = subscriptionCertificateThumbprintInstance; } XElement subscriptionCertificateDataElement = subscriptionCertificateElement.Element(XName.Get("SubscriptionCertificateData", "http://schemas.microsoft.com/windowsazure")); if (subscriptionCertificateDataElement != null) { byte[] subscriptionCertificateDataInstance = Convert.FromBase64String(subscriptionCertificateDataElement.Value); result.Data = subscriptionCertificateDataInstance; } XElement createdElement = subscriptionCertificateElement.Element(XName.Get("Created", "http://schemas.microsoft.com/windowsazure")); if (createdElement != null) { DateTime createdInstance = DateTime.Parse(createdElement.Value, CultureInfo.InvariantCulture); result.Created = createdInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The List Management Certificates operation lists and returns basic /// information about all of the management certificates associated /// with the specified subscription. Management certificates, which /// are also known as subscription certificates, authenticate clients /// attempting to connect to resources associated with your Windows /// Azure subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Management Certificates operation response. /// </returns> public async Task<ManagementCertificateListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/certificates"; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ManagementCertificateListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ManagementCertificateListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement subscriptionCertificatesSequenceElement = responseDoc.Element(XName.Get("SubscriptionCertificates", "http://schemas.microsoft.com/windowsazure")); if (subscriptionCertificatesSequenceElement != null) { foreach (XElement subscriptionCertificatesElement in subscriptionCertificatesSequenceElement.Elements(XName.Get("SubscriptionCertificate", "http://schemas.microsoft.com/windowsazure"))) { ManagementCertificateListResponse.SubscriptionCertificate subscriptionCertificateInstance = new ManagementCertificateListResponse.SubscriptionCertificate(); result.SubscriptionCertificates.Add(subscriptionCertificateInstance); XElement subscriptionCertificatePublicKeyElement = subscriptionCertificatesElement.Element(XName.Get("SubscriptionCertificatePublicKey", "http://schemas.microsoft.com/windowsazure")); if (subscriptionCertificatePublicKeyElement != null) { byte[] subscriptionCertificatePublicKeyInstance = Convert.FromBase64String(subscriptionCertificatePublicKeyElement.Value); subscriptionCertificateInstance.PublicKey = subscriptionCertificatePublicKeyInstance; } XElement subscriptionCertificateThumbprintElement = subscriptionCertificatesElement.Element(XName.Get("SubscriptionCertificateThumbprint", "http://schemas.microsoft.com/windowsazure")); if (subscriptionCertificateThumbprintElement != null) { string subscriptionCertificateThumbprintInstance = subscriptionCertificateThumbprintElement.Value; subscriptionCertificateInstance.Thumbprint = subscriptionCertificateThumbprintInstance; } XElement subscriptionCertificateDataElement = subscriptionCertificatesElement.Element(XName.Get("SubscriptionCertificateData", "http://schemas.microsoft.com/windowsazure")); if (subscriptionCertificateDataElement != null) { byte[] subscriptionCertificateDataInstance = Convert.FromBase64String(subscriptionCertificateDataElement.Value); subscriptionCertificateInstance.Data = subscriptionCertificateDataInstance; } XElement createdElement = subscriptionCertificatesElement.Element(XName.Get("Created", "http://schemas.microsoft.com/windowsazure")); if (createdElement != null) { DateTime createdInstance = DateTime.Parse(createdElement.Value, CultureInfo.InvariantCulture); subscriptionCertificateInstance.Created = createdInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace DocuSign.eSign.Model { /// <summary> /// Contains address information. /// </summary> [DataContract] public partial class AddressInformation : IEquatable<AddressInformation>, IValidatableObject { public AddressInformation() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="AddressInformation" /> class. /// </summary> /// <param name="City">The city associated with the address..</param> /// <param name="Country">Specifies the country associated with the address..</param> /// <param name="Fax">A Fax number associated with the address if one is available..</param> /// <param name="Phone">A phone number associated with the address..</param> /// <param name="State">The state or province associated with the address..</param> /// <param name="Street1">The first line of the address..</param> /// <param name="Street2">The second line of the address (optional)..</param> /// <param name="Zip">The zip or postal code associated with the address..</param> public AddressInformation(string City = default(string), string Country = default(string), string Fax = default(string), string Phone = default(string), string State = default(string), string Street1 = default(string), string Street2 = default(string), string Zip = default(string)) { this.City = City; this.Country = Country; this.Fax = Fax; this.Phone = Phone; this.State = State; this.Street1 = Street1; this.Street2 = Street2; this.Zip = Zip; } /// <summary> /// The city associated with the address. /// </summary> /// <value>The city associated with the address.</value> [DataMember(Name="city", EmitDefaultValue=false)] public string City { get; set; } /// <summary> /// Specifies the country associated with the address. /// </summary> /// <value>Specifies the country associated with the address.</value> [DataMember(Name="country", EmitDefaultValue=false)] public string Country { get; set; } /// <summary> /// A Fax number associated with the address if one is available. /// </summary> /// <value>A Fax number associated with the address if one is available.</value> [DataMember(Name="fax", EmitDefaultValue=false)] public string Fax { get; set; } /// <summary> /// A phone number associated with the address. /// </summary> /// <value>A phone number associated with the address.</value> [DataMember(Name="phone", EmitDefaultValue=false)] public string Phone { get; set; } /// <summary> /// The state or province associated with the address. /// </summary> /// <value>The state or province associated with the address.</value> [DataMember(Name="state", EmitDefaultValue=false)] public string State { get; set; } /// <summary> /// The first line of the address. /// </summary> /// <value>The first line of the address.</value> [DataMember(Name="street1", EmitDefaultValue=false)] public string Street1 { get; set; } /// <summary> /// The second line of the address (optional). /// </summary> /// <value>The second line of the address (optional).</value> [DataMember(Name="street2", EmitDefaultValue=false)] public string Street2 { get; set; } /// <summary> /// The zip or postal code associated with the address. /// </summary> /// <value>The zip or postal code associated with the address.</value> [DataMember(Name="zip", EmitDefaultValue=false)] public string Zip { 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 AddressInformation {\n"); sb.Append(" City: ").Append(City).Append("\n"); sb.Append(" Country: ").Append(Country).Append("\n"); sb.Append(" Fax: ").Append(Fax).Append("\n"); sb.Append(" Phone: ").Append(Phone).Append("\n"); sb.Append(" State: ").Append(State).Append("\n"); sb.Append(" Street1: ").Append(Street1).Append("\n"); sb.Append(" Street2: ").Append(Street2).Append("\n"); sb.Append(" Zip: ").Append(Zip).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 AddressInformation); } /// <summary> /// Returns true if AddressInformation instances are equal /// </summary> /// <param name="other">Instance of AddressInformation to be compared</param> /// <returns>Boolean</returns> public bool Equals(AddressInformation other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.City == other.City || this.City != null && this.City.Equals(other.City) ) && ( this.Country == other.Country || this.Country != null && this.Country.Equals(other.Country) ) && ( this.Fax == other.Fax || this.Fax != null && this.Fax.Equals(other.Fax) ) && ( this.Phone == other.Phone || this.Phone != null && this.Phone.Equals(other.Phone) ) && ( this.State == other.State || this.State != null && this.State.Equals(other.State) ) && ( this.Street1 == other.Street1 || this.Street1 != null && this.Street1.Equals(other.Street1) ) && ( this.Street2 == other.Street2 || this.Street2 != null && this.Street2.Equals(other.Street2) ) && ( this.Zip == other.Zip || this.Zip != null && this.Zip.Equals(other.Zip) ); } /// <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.City != null) hash = hash * 59 + this.City.GetHashCode(); if (this.Country != null) hash = hash * 59 + this.Country.GetHashCode(); if (this.Fax != null) hash = hash * 59 + this.Fax.GetHashCode(); if (this.Phone != null) hash = hash * 59 + this.Phone.GetHashCode(); if (this.State != null) hash = hash * 59 + this.State.GetHashCode(); if (this.Street1 != null) hash = hash * 59 + this.Street1.GetHashCode(); if (this.Street2 != null) hash = hash * 59 + this.Street2.GetHashCode(); if (this.Zip != null) hash = hash * 59 + this.Zip.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using TelemData = System.Collections.Generic.KeyValuePair<string, object>; using Xunit; namespace System.Diagnostics.Tests { /// <summary> /// Tests for DiagnosticSource and DiagnosticListener /// </summary> public class DiagnosticSourceTest { /// <summary> /// Trivial example of passing an integer /// </summary> [Fact] public void IntPayload() { using (DiagnosticListener listener = new DiagnosticListener("TestingIntPayload")) { DiagnosticSource source = listener; var result = new List<KeyValuePair<string, object>>(); var observer = new ObserverToList<TelemData>(result); using (listener.Subscribe(new ObserverToList<TelemData>(result))) { listener.Write("IntPayload", 5); Assert.Equal(1, result.Count); Assert.Equal("IntPayload", result[0].Key); Assert.Equal(5, result[0].Value); } // unsubscribe // Make sure that after unsubscribing, we don't get more events. source.Write("IntPayload", 5); Assert.Equal(1, result.Count); } } /// <summary> /// slightly less trivial of passing a structure with a couple of fields /// </summary> [Fact] public void StructPayload() { using (DiagnosticListener listener = new DiagnosticListener("TestingStructPayload")) { DiagnosticSource source = listener; var result = new List<KeyValuePair<string, object>>(); using (listener.Subscribe(new ObserverToList<TelemData>(result))) { source.Write("StructPayload", new Payload() { Name = "Hi", Id = 67 }); Assert.Equal(1, result.Count); Assert.Equal("StructPayload", result[0].Key); var payload = (Payload)result[0].Value; Assert.Equal(67, payload.Id); Assert.Equal("Hi", payload.Name); } source.Write("StructPayload", new Payload() { Name = "Hi", Id = 67 }); Assert.Equal(1, result.Count); } } /// <summary> /// Tests the IObserver OnCompleted callback. /// </summary> [Fact] public void Completed() { var result = new List<KeyValuePair<string, object>>(); var observer = new ObserverToList<TelemData>(result); var listener = new DiagnosticListener("TestingCompleted"); var subscription = listener.Subscribe(observer); listener.Write("IntPayload", 5); Assert.Equal(1, result.Count); Assert.Equal("IntPayload", result[0].Key); Assert.Equal(5, result[0].Value); Assert.False(observer.Completed); // The listener dies listener.Dispose(); Assert.True(observer.Completed); // confirm that we can unsubscribe without crashing subscription.Dispose(); // If we resubscribe after dispose, but it does not do anything. subscription = listener.Subscribe(observer); listener.Write("IntPayload", 5); Assert.Equal(1, result.Count); } /// <summary> /// Simple tests for the IsEnabled method. /// </summary> [Fact] public void BasicIsEnabled() { using (DiagnosticListener listener = new DiagnosticListener("TestingBasicIsEnabled")) { DiagnosticSource source = listener; var result = new List<KeyValuePair<string, object>>(); bool seenUninteresting = false; bool seenStructPayload = false; Predicate<string> predicate = delegate (string name) { if (name == "Uninteresting") seenUninteresting = true; if (name == "StructPayload") seenStructPayload = true; return name == "StructPayload"; }; // Assert.False(listener.IsEnabled()); Since other things might turn on all DiagnosticSources, we can't ever test that it is not enabled. using (listener.Subscribe(new ObserverToList<TelemData>(result), predicate)) { Assert.False(source.IsEnabled("Uninteresting")); Assert.False(source.IsEnabled("Uninteresting", "arg1", "arg2")); Assert.True(source.IsEnabled("StructPayload")); Assert.True(source.IsEnabled("StructPayload", "arg1", "arg2")); Assert.True(seenUninteresting); Assert.True(seenStructPayload); Assert.True(listener.IsEnabled()); } } } /// <summary> /// Simple tests for the IsEnabled method. /// </summary> [Fact] public void IsEnabledMultipleArgs() { using (DiagnosticListener listener = new DiagnosticListener("TestingIsEnabledMultipleArgs")) { DiagnosticSource source = listener; var result = new List<KeyValuePair<string, object>>(); Func<string, object, object, bool> isEnabled = (name, arg1, arg2) => { if (arg1 != null) return (bool) arg1; if (arg2 != null) return (bool) arg2; return true; }; using (listener.Subscribe(new ObserverToList<TelemData>(result), isEnabled)) { Assert.True(source.IsEnabled("event")); Assert.True(source.IsEnabled("event", null, null)); Assert.True(source.IsEnabled("event", null, true)); Assert.False(source.IsEnabled("event", false, false)); Assert.False(source.IsEnabled("event", false, null)); Assert.False(source.IsEnabled("event", null, false)); } } } /// <summary> /// Test if it works when you have two subscribers active simultaneously /// </summary> [Fact] public void MultiSubscriber() { using (DiagnosticListener listener = new DiagnosticListener("TestingMultiSubscriber")) { DiagnosticSource source = listener; var subscriber1Result = new List<KeyValuePair<string, object>>(); Predicate<string> subscriber1Predicate = name => (name == "DataForSubscriber1"); var subscriber1Observer = new ObserverToList<TelemData>(subscriber1Result); var subscriber2Result = new List<KeyValuePair<string, object>>(); Predicate<string> subscriber2Predicate = name => (name == "DataForSubscriber2"); var subscriber2Observer = new ObserverToList<TelemData>(subscriber2Result); // Get two subscribers going. using (var subscription1 = listener.Subscribe(subscriber1Observer, subscriber1Predicate)) { using (var subscription2 = listener.Subscribe(subscriber2Observer, subscriber2Predicate)) { // Things that neither subscribe to get filtered out. if (listener.IsEnabled("DataToFilterOut")) listener.Write("DataToFilterOut", -1); Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // If a Source does not use the IsEnabled, then every subscriber gets it. subscriber1Result.Clear(); subscriber2Result.Clear(); listener.Write("UnfilteredData", 3); Assert.Equal(1, subscriber1Result.Count); Assert.Equal("UnfilteredData", subscriber1Result[0].Key); Assert.Equal(3, (int)subscriber1Result[0].Value); Assert.Equal(1, subscriber2Result.Count); Assert.Equal("UnfilteredData", subscriber2Result[0].Key); Assert.Equal(3, (int)subscriber2Result[0].Value); /****************************************************/ // Filters not filter out everything, they are just a performance optimization. // Here you actually get more than you want even though you use a filter subscriber1Result.Clear(); subscriber2Result.Clear(); if (listener.IsEnabled("DataForSubscriber1")) listener.Write("DataForSubscriber1", 1); Assert.Equal(1, subscriber1Result.Count); Assert.Equal("DataForSubscriber1", subscriber1Result[0].Key); Assert.Equal(1, (int)subscriber1Result[0].Value); // Subscriber 2 happens to get it Assert.Equal(1, subscriber2Result.Count); Assert.Equal("DataForSubscriber1", subscriber2Result[0].Key); Assert.Equal(1, (int)subscriber2Result[0].Value); /****************************************************/ subscriber1Result.Clear(); subscriber2Result.Clear(); if (listener.IsEnabled("DataForSubscriber2")) listener.Write("DataForSubscriber2", 2); // Subscriber 1 happens to get it Assert.Equal(1, subscriber1Result.Count); Assert.Equal("DataForSubscriber2", subscriber1Result[0].Key); Assert.Equal(2, (int)subscriber1Result[0].Value); Assert.Equal(1, subscriber2Result.Count); Assert.Equal("DataForSubscriber2", subscriber2Result[0].Key); Assert.Equal(2, (int)subscriber2Result[0].Value); } // subscriber2 drops out /*********************************************************************/ /* Only Subscriber 1 is left */ /*********************************************************************/ // Things that neither subscribe to get filtered out. subscriber1Result.Clear(); subscriber2Result.Clear(); if (listener.IsEnabled("DataToFilterOut")) listener.Write("DataToFilterOut", -1); Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // If a Source does not use the IsEnabled, then every subscriber gets it. subscriber1Result.Clear(); listener.Write("UnfilteredData", 3); Assert.Equal(1, subscriber1Result.Count); Assert.Equal("UnfilteredData", subscriber1Result[0].Key); Assert.Equal(3, (int)subscriber1Result[0].Value); // Subscriber 2 has dropped out. Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // Filters not filter out everything, they are just a performance optimization. // Here you actually get more than you want even though you use a filter subscriber1Result.Clear(); if (listener.IsEnabled("DataForSubscriber1")) listener.Write("DataForSubscriber1", 1); Assert.Equal(1, subscriber1Result.Count); Assert.Equal("DataForSubscriber1", subscriber1Result[0].Key); Assert.Equal(1, (int)subscriber1Result[0].Value); // Subscriber 2 has dropped out. Assert.Equal(0, subscriber2Result.Count); /****************************************************/ subscriber1Result.Clear(); if (listener.IsEnabled("DataForSubscriber2")) listener.Write("DataForSubscriber2", 2); // Subscriber 1 filters Assert.Equal(0, subscriber1Result.Count); // Subscriber 2 has dropped out Assert.Equal(0, subscriber2Result.Count); } // subscriber1 drops out /*********************************************************************/ /* No Subscribers are left */ /*********************************************************************/ // Things that neither subscribe to get filtered out. subscriber1Result.Clear(); subscriber2Result.Clear(); if (listener.IsEnabled("DataToFilterOut")) listener.Write("DataToFilterOut", -1); Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // If a Source does not use the IsEnabled, then every subscriber gets it. listener.Write("UnfilteredData", 3); // No one subscribing Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // Filters not filter out everything, they are just a performance optimization. // Here you actually get more than you want even though you use a filter if (listener.IsEnabled("DataForSubscriber1")) listener.Write("DataForSubscriber1", 1); // No one subscribing Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ if (listener.IsEnabled("DataForSubscriber2")) listener.Write("DataForSubscriber2", 2); // No one subscribing Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); } } /// <summary> /// Stresses the Subscription routine by having many threads subscribe and /// unsubscribe concurrently /// </summary> [Fact] public void MultiSubscriberStress() { using (DiagnosticListener listener = new DiagnosticListener("MultiSubscriberStressTest")) { DiagnosticSource source = listener; var random = new Random(); // Beat on the default listener by subscribing and unsubscribing on many threads simultaneously. var factory = new TaskFactory(); // To the whole stress test 10 times. This keeps the task array size needed down while still // having lots of concurrency. for (int j = 0; j < 20; j++) { // Spawn off lots of concurrent activity var tasks = new Task[1000]; for (int i = 0; i < tasks.Length; i++) { tasks[i] = factory.StartNew(delegate (object taskData) { int taskNum = (int)taskData; var taskName = "Task" + taskNum; var result = new List<KeyValuePair<string, object>>(); Predicate<string> predicate = (name) => name == taskName; Predicate<KeyValuePair<string, object>> filter = (keyValue) => keyValue.Key == taskName; // set up the observer to only see events set with the task name as the name. var observer = new ObserverToList<TelemData>(result, filter, taskName); using (listener.Subscribe(observer, predicate)) { source.Write(taskName, taskNum); Assert.Equal(1, result.Count); Assert.Equal(taskName, result[0].Key); Assert.Equal(taskNum, result[0].Value); // Spin a bit randomly. This mixes of the lifetimes of the subscriptions and makes it // more stressful var cnt = random.Next(10, 100) * 1000; while (0 < --cnt) GC.KeepAlive(""); } // Unsubscribe // Send the notification again, to see if it now does NOT come through (count remains unchanged). source.Write(taskName, -1); Assert.Equal(1, result.Count); }, i); } Task.WaitAll(tasks); } } } /// <summary> /// Tests if as we create new DiagnosticListerns, we get callbacks for them /// </summary> [Fact] public void AllListenersAddRemove() { using (DiagnosticListener listener = new DiagnosticListener("TestListen0")) { DiagnosticSource source = listener; // This callback will return the listener that happens on the callback DiagnosticListener returnedListener = null; Action<DiagnosticListener> onNewListener = delegate (DiagnosticListener listen) { // Other tests can be running concurrently with this test, which will make // this callback fire for those listeners as well. We only care about // the Listeners we generate here so ignore any that d if (!listen.Name.StartsWith("TestListen")) return; Assert.Null(returnedListener); Assert.NotNull(listen); returnedListener = listen; }; // Subscribe, which delivers catch-up event for the Default listener using (var allListenerSubscription = DiagnosticListener.AllListeners.Subscribe(MakeObserver(onNewListener))) { Assert.Equal(listener, returnedListener); returnedListener = null; } // Now we unsubscribe // Create an dispose a listener, but we won't get a callback for it. using (new DiagnosticListener("TestListen")) { } Assert.Null(returnedListener); // No callback was made // Resubscribe using (var allListenerSubscription = DiagnosticListener.AllListeners.Subscribe(MakeObserver(onNewListener))) { Assert.Equal(listener, returnedListener); returnedListener = null; // add two new subscribers using (var listener1 = new DiagnosticListener("TestListen1")) { Assert.Equal(listener1.Name, "TestListen1"); Assert.Equal(listener1, returnedListener); returnedListener = null; using (var listener2 = new DiagnosticListener("TestListen2")) { Assert.Equal(listener2.Name, "TestListen2"); Assert.Equal(listener2, returnedListener); returnedListener = null; } // Dispose of listener2 } // Dispose of listener1 } // Unsubscribe // Check that we are back to just the DefaultListener. using (var allListenerSubscription = DiagnosticListener.AllListeners.Subscribe(MakeObserver(onNewListener))) { Assert.Equal(listener, returnedListener); returnedListener = null; } // cleanup } } /// <summary> /// Tests that the 'catchupList' of active listeners is accurate even as we /// add and remove DiagnosticListeners randomly. /// </summary> [Fact] public void AllListenersCheckCatchupList() { var expected = new List<DiagnosticListener>(); var list = GetActiveListenersWithPrefix("TestListener"); Assert.Equal(list, expected); for (int i = 0; i < 50; i++) { expected.Insert(0, (new DiagnosticListener("TestListener" + i))); list = GetActiveListenersWithPrefix("TestListener"); Assert.Equal(list, expected); } // Remove the element randomly. var random = new Random(0); while (0 < expected.Count) { var toRemoveIdx = random.Next(0, expected.Count - 1); // Always leave the Default listener. var toRemoveListener = expected[toRemoveIdx]; toRemoveListener.Dispose(); // Kill it (which removes it from the list) expected.RemoveAt(toRemoveIdx); list = GetActiveListenersWithPrefix("TestListener"); Assert.Equal(list.Count, expected.Count); Assert.Equal(list, expected); } } /// <summary> /// Stresses the AllListeners by having many threads be adding and removing. /// </summary> [OuterLoop] [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotArm64Process))] // [ActiveIssue(35539)] [InlineData(100, 100)] // run multiple times to stress it further [InlineData(100, 100)] [InlineData(100, 100)] [InlineData(100, 100)] [InlineData(100, 100)] public void AllSubscriberStress(int numThreads, int numListenersPerThread) { // No listeners have been created yet Assert.Equal(0, GetActiveListenersWithPrefix(nameof(AllSubscriberStress)).Count); // Run lots of threads to add/remove listeners Task.WaitAll(Enumerable.Range(0, numThreads).Select(i => Task.Factory.StartNew(delegate { // Create a set of DiagnosticListeners, which add themselves to the AllListeners list. var listeners = new List<DiagnosticListener>(numListenersPerThread); for (int j = 0; j < numListenersPerThread; j++) { var listener = new DiagnosticListener($"{nameof(AllSubscriberStress)}_Task {i} TestListener{j}"); listeners.Add(listener); } // They are all in the list. List<DiagnosticListener> list = GetActiveListenersWithPrefix(nameof(AllSubscriberStress)); Assert.All(listeners, listener => Assert.Contains(listener, list)); // Dispose them all, first the even then the odd, just to mix it up and be more stressful. for (int j = 0; j < listeners.Count; j += 2) // even listeners[j].Dispose(); for (int j = 1; j < listeners.Count; j += 2) // odd listeners[j].Dispose(); // None should be left in the list list = GetActiveListenersWithPrefix(nameof(AllSubscriberStress)); Assert.All(listeners, listener => Assert.DoesNotContain(listener, list)); }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray()); // None of the created listeners should remain Assert.Equal(0, GetActiveListenersWithPrefix(nameof(AllSubscriberStress)).Count); } [Fact] public void DoubleDisposeOfListener() { var listener = new DiagnosticListener("TestingDoubleDisposeOfListener"); int completionCount = 0; IDisposable subscription = listener.Subscribe(MakeObserver<KeyValuePair<string, object>>(_ => { }, () => completionCount++)); listener.Dispose(); listener.Dispose(); subscription.Dispose(); subscription.Dispose(); Assert.Equal(1, completionCount); } [Fact] public void ListenerToString() { string name = Guid.NewGuid().ToString(); using (var listener = new DiagnosticListener(name)) { Assert.Equal(name, listener.ToString()); } } [Fact] public void DisposeAllListenerSubscriptionInSameOrderSubscribed() { int count1 = 0, count2 = 0, count3 = 0; IDisposable sub1 = DiagnosticListener.AllListeners.Subscribe(MakeObserver<DiagnosticListener>(onCompleted: () => count1++)); IDisposable sub2 = DiagnosticListener.AllListeners.Subscribe(MakeObserver<DiagnosticListener>(onCompleted: () => count2++)); IDisposable sub3 = DiagnosticListener.AllListeners.Subscribe(MakeObserver<DiagnosticListener>(onCompleted: () => count3++)); Assert.Equal(0, count1); Assert.Equal(0, count2); Assert.Equal(0, count3); sub1.Dispose(); Assert.Equal(1, count1); Assert.Equal(0, count2); Assert.Equal(0, count3); sub1.Dispose(); // dispose again just to make sure nothing bad happens sub2.Dispose(); Assert.Equal(1, count1); Assert.Equal(1, count2); Assert.Equal(0, count3); sub2.Dispose(); sub3.Dispose(); Assert.Equal(1, count1); Assert.Equal(1, count2); Assert.Equal(1, count3); sub3.Dispose(); } [Fact] public void SubscribeWithNullPredicate() { using (DiagnosticListener listener = new DiagnosticListener("TestingSubscribeWithNullPredicate")) { Predicate<string> predicate = null; using (listener.Subscribe(new ObserverToList<TelemData>(new List<KeyValuePair<string, object>>()), predicate)) { Assert.True(listener.IsEnabled("event")); Assert.True(listener.IsEnabled("event", null)); Assert.True(listener.IsEnabled("event", "arg1")); Assert.True(listener.IsEnabled("event", "arg1", "arg2")); } } using (DiagnosticListener listener = new DiagnosticListener("TestingSubscribeWithNullPredicate")) { DiagnosticSource source = listener; Func<string, object, object, bool> predicate = null; using (listener.Subscribe(new ObserverToList<TelemData>(new List<KeyValuePair<string, object>>()), predicate)) { Assert.True(source.IsEnabled("event")); Assert.True(source.IsEnabled("event", null)); Assert.True(source.IsEnabled("event", "arg1")); Assert.True(source.IsEnabled("event", "arg1", "arg2")); } } } [Fact] public void ActivityImportExport() { using (DiagnosticListener listener = new DiagnosticListener("TestingBasicIsEnabled")) { DiagnosticSource source = listener; var result = new List<KeyValuePair<string, object>>(); bool seenPredicate = false; Func<string, object, object, bool> predicate = delegate (string name, object obj1, object obj2) { seenPredicate = true; return true; }; Activity importerActivity = new Activity("activityImporter"); object importer = "MyImporterObject"; bool seenActivityImport = false; Action<Activity, object> activityImport = delegate (Activity activity, object payload) { Assert.Equal(activity.GetHashCode(), importerActivity.GetHashCode()); Assert.Equal(importer, payload); seenActivityImport = true; }; Activity exporterActivity = new Activity("activityExporter"); object exporter = "MyExporterObject"; bool seenActivityExport = false; Action<Activity, object> activityExport = delegate (Activity activity, object payload) { Assert.Equal(activity.GetHashCode(), exporterActivity.GetHashCode()); Assert.Equal(exporter, payload); seenActivityExport = true; }; // Use the Subscribe that allows you to hook the OnActivityImport and OnActivityExport calls. using (listener.Subscribe(new ObserverToList<TelemData>(result), predicate, activityImport, activityExport)) { if (listener.IsEnabled("IntPayload")) listener.Write("IntPayload", 5); Assert.True(seenPredicate); Assert.Equal(1, result.Count); Assert.Equal("IntPayload", result[0].Key); Assert.Equal(5, result[0].Value); listener.OnActivityImport(importerActivity, importer); Assert.True(seenActivityImport); listener.OnActivityExport(exporterActivity, exporter); Assert.True(seenActivityExport); } } } #region Helpers /// <summary> /// Returns the list of active diagnostic listeners. /// </summary> /// <returns></returns> private static List<DiagnosticListener> GetActiveListenersWithPrefix(string prefix) { var ret = new List<DiagnosticListener>(); Action<DiagnosticListener> onNewListener = delegate (DiagnosticListener listen) { if (listen.Name.StartsWith(prefix)) ret.Add(listen); }; // Subscribe, which gives you the list using (var allListenerSubscription = DiagnosticListener.AllListeners.Subscribe(MakeObserver(onNewListener))) { } // Unsubscribe to remove side effects. return ret; } /// <summary> /// Used to make an observer out of an action delegate. /// </summary> public static IObserver<T> MakeObserver<T>( Action<T> onNext = null, Action onCompleted = null) { return new Observer<T>(onNext, onCompleted); } /// <summary> /// Used in the implementation of MakeObserver. /// </summary> /// <typeparam name="T"></typeparam> private class Observer<T> : IObserver<T> { public Observer(Action<T> onNext, Action onCompleted) { _onNext = onNext ?? new Action<T>(_ => { }); _onCompleted = onCompleted ?? new Action(() => { }); } public void OnCompleted() { _onCompleted(); } public void OnError(Exception error) { } public void OnNext(T value) { _onNext(value); } private Action<T> _onNext; private Action _onCompleted; } #endregion } // Takes an IObserver and returns a List<T> that are the elements observed. // Will assert on error and 'Completed' is set if the 'OnCompleted' callback // is issued. internal class ObserverToList<T> : IObserver<T> { public ObserverToList(List<T> output, Predicate<T> filter = null, string name = null) { _output = output; _output.Clear(); _filter = filter; _name = name; } public bool Completed { get; private set; } #region private public void OnCompleted() { Completed = true; } public void OnError(Exception error) { Assert.True(false, "Error happened on IObserver"); } public void OnNext(T value) { Assert.False(Completed); if (_filter == null || _filter(value)) _output.Add(value); } private List<T> _output; private Predicate<T> _filter; private string _name; // for debugging #endregion } /// <summary> /// Trivial class used for payloads. (Usually anonymous types are used. /// </summary> internal class Payload { public string Name { get; set; } public int Id { get; set; } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* This version has been heavily modified from it's original version by InWorldz,LLC * Beth Reischl - 3/25/2010 */ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Net.Sockets; using System.Reflection; using OpenMetaverse; using TransactionInfoBlock = OpenMetaverse.Packets.MoneyBalanceReplyPacket.TransactionInfoBlock; using log4net; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Communications.Cache; using OpenSim.Region.CoreModules.Avatar.Dialog; using OpenSim.Data.SimpleDB; namespace OpenSim.Region.CoreModules.Avatar.Currency { public class AvatarCurrency : IMoneyModule, IRegionModule { // // Log module // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // // Module vars // private Dictionary<ulong, Scene> m_scenel = new Dictionary<ulong, Scene>(); private ConnectionFactory _connFactory; public static UUID DEFAULT_CURRENCY_ACCOUNT_ID = new UUID("efbfe4e6-95c2-4af3-9d27-25a35c2fd575"); /// <summary> /// Setup of the base vars that will be pulled from the ini file /// </summary> /// public UUID CurrencyAccountID = DEFAULT_CURRENCY_ACCOUNT_ID; private float EnergyEfficiency = 0f; //private ObjectPaid handlerOnObjectPaid; private int ObjectCapacity = OpenSim.Framework.RegionInfo.DEFAULT_REGION_PRIM_LIMIT; private int ObjectCount = 0; private int PriceEnergyUnit = 0; private int PriceGroupCreate = 0; private int PriceObjectClaim = 0; private float PriceObjectRent = 0f; private float PriceObjectScaleFactor = 0f; private int PriceParcelClaim = 0; private float PriceParcelClaimFactor = 0f; private int PriceParcelRent = 0; private int PricePublicObjectDecay = 0; private int PricePublicObjectDelete = 0; private int PriceRentLight = 0; private int PriceUpload = 0; private int TeleportMinPrice = 0; private int MinDebugMoney = Int32.MinValue; private string CurrencySymbol = "I'z$"; private float TeleportPriceExponent = 0f; #region AvatarCurrency Members public event ObjectPaid OnObjectPaid; public void Initialize(Scene scene, IConfigSource config) { IConfig economyConfig = config.Configs["Economy"]; string connstr = economyConfig.GetString("EconomyConnString", String.Empty); if (connstr.Length <= 0) // EconomyConnString not found or blank, try the connection string this code previously used. { m_log.Info("[CURRENCY] EconomyConnString not found in INI file section [Economy]. Falling back to legacy usage of ProfileConnString in [Profile]."); IConfig profileConfig = config.Configs["Profile"]; connstr = profileConfig.GetString("ProfileConnString", String.Empty); } _connFactory = new ConnectionFactory("MySQL", connstr); m_log.Info("[CURRENCY] InWorldz Currency Module is activated"); const int DEFAULT_PRICE_ENERGY_UNIT = 100; const int DEFAULT_PRICE_OBJECT_CLAIM = 10; const int DEFAULT_PRICE_PUBLIC_OBJECT_DECAY = 4; const int DEFAULT_PRICE_PUBLIC_OBJECT_DELETE = 4; const int DEFAULT_PRICE_PARCEL_CLAIM = 1; const float DEFAULT_PRICE_PARCEL_CLAIM_FACTOR = 1f; const int DEFAULT_PRICE_UPLOAD = 0; const int DEFAULT_PRICE_RENT_LIGHT = 5; const int DEFAULT_TELEPORT_MIN_PRICE = 2; const float DEFAULT_TELEPORT_PRICE_EXPONENT = 2f; const int DEFAULT_ENERGY_EFFICIENCY = 1; const int DEFAULT_PRICE_OBJECT_RENT = 1; const int DEFAULT_PRICE_OBJECT_SCALE_FACTOR = 10; const int DEFAULT_PRICE_PARCEL_RENT = 1; const int DEFAULT_PRICE_GROUP_CREATE = -1; if (economyConfig != null) { ObjectCapacity = economyConfig.GetInt("ObjectCapacity", OpenSim.Framework.RegionInfo.DEFAULT_REGION_PRIM_LIMIT); PriceEnergyUnit = economyConfig.GetInt("PriceEnergyUnit", DEFAULT_PRICE_ENERGY_UNIT); PriceObjectClaim = economyConfig.GetInt("PriceObjectClaim", DEFAULT_PRICE_OBJECT_CLAIM); PricePublicObjectDecay = economyConfig.GetInt("PricePublicObjectDecay", DEFAULT_PRICE_PUBLIC_OBJECT_DECAY); PricePublicObjectDelete = economyConfig.GetInt("PricePublicObjectDelete", DEFAULT_PRICE_PUBLIC_OBJECT_DELETE); PriceParcelClaim = economyConfig.GetInt("PriceParcelClaim", DEFAULT_PRICE_PARCEL_CLAIM); PriceParcelClaimFactor = economyConfig.GetFloat("PriceParcelClaimFactor", DEFAULT_PRICE_PARCEL_CLAIM_FACTOR); PriceUpload = economyConfig.GetInt("PriceUpload", DEFAULT_PRICE_UPLOAD); PriceRentLight = economyConfig.GetInt("PriceRentLight", DEFAULT_PRICE_RENT_LIGHT); TeleportMinPrice = economyConfig.GetInt("TeleportMinPrice", DEFAULT_TELEPORT_MIN_PRICE); TeleportPriceExponent = economyConfig.GetFloat("TeleportPriceExponent", DEFAULT_TELEPORT_PRICE_EXPONENT); EnergyEfficiency = economyConfig.GetFloat("EnergyEfficiency", DEFAULT_ENERGY_EFFICIENCY); PriceObjectRent = economyConfig.GetFloat("PriceObjectRent", DEFAULT_PRICE_OBJECT_RENT); PriceObjectScaleFactor = economyConfig.GetFloat("PriceObjectScaleFactor", DEFAULT_PRICE_OBJECT_SCALE_FACTOR); PriceParcelRent = economyConfig.GetInt("PriceParcelRent", DEFAULT_PRICE_PARCEL_RENT); PriceGroupCreate = economyConfig.GetInt("PriceGroupCreate", DEFAULT_PRICE_GROUP_CREATE); CurrencySymbol = economyConfig.GetString("CurrencySymbol", CurrencySymbol); string option = economyConfig.GetString("CurrencyAccount", DEFAULT_CURRENCY_ACCOUNT_ID.ToString()).Trim(); if (!UUID.TryParse(option, out CurrencyAccountID)) { CurrencyAccountID = DEFAULT_CURRENCY_ACCOUNT_ID; } // easy way for all accounts on debug servers to have some cash to test Buy operations and transfers MinDebugMoney = economyConfig.GetInt("MinDebugMoney", Int32.MinValue); if (MinDebugMoney != Int32.MinValue) m_log.InfoFormat("[CURRENCY] MinDebugMoney activated at: {0}", MinDebugMoney); } else { ObjectCapacity = OpenSim.Framework.RegionInfo.DEFAULT_REGION_PRIM_LIMIT; PriceEnergyUnit = DEFAULT_PRICE_ENERGY_UNIT; PriceObjectClaim = DEFAULT_PRICE_OBJECT_CLAIM; PricePublicObjectDecay = DEFAULT_PRICE_PUBLIC_OBJECT_DECAY; PricePublicObjectDelete = DEFAULT_PRICE_PUBLIC_OBJECT_DELETE; PriceParcelClaim = DEFAULT_PRICE_PARCEL_CLAIM; PriceParcelClaimFactor = DEFAULT_PRICE_PARCEL_CLAIM_FACTOR; PriceUpload = DEFAULT_PRICE_UPLOAD; PriceRentLight = DEFAULT_PRICE_RENT_LIGHT; TeleportMinPrice = DEFAULT_TELEPORT_MIN_PRICE; TeleportPriceExponent = DEFAULT_TELEPORT_PRICE_EXPONENT; EnergyEfficiency = DEFAULT_ENERGY_EFFICIENCY; PriceObjectRent = DEFAULT_PRICE_OBJECT_RENT; PriceObjectScaleFactor = DEFAULT_PRICE_OBJECT_SCALE_FACTOR; PriceParcelRent = DEFAULT_PRICE_PARCEL_RENT; PriceGroupCreate = DEFAULT_PRICE_GROUP_CREATE; MinDebugMoney = Int32.MinValue; } scene.RegisterModuleInterface<IMoneyModule>(this); IHttpServer httpServer = scene.CommsManager.HttpServer; if (m_scenel.ContainsKey(scene.RegionInfo.RegionHandle)) { m_scenel[scene.RegionInfo.RegionHandle] = scene; } else { m_scenel.Add(scene.RegionInfo.RegionHandle, scene); } scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnMoneyTransfer += MoneyTransferAction; scene.EventManager.OnClassifiedPayment += ClassifiedPayment; scene.EventManager.OnValidateLandBuy += ValidateLandBuy; scene.EventManager.OnLandBuy += processLandBuy; /* scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel; scene.EventManager.OnMakeChildAgent += MakeChildAgent; scene.EventManager.OnClientClosed += ClientLoggedOut; */ } public string GetCurrencySymbol() { return CurrencySymbol; } public bool UploadChargeApplies(AssetType type) { if (PriceUpload <= 0) return false; return (type == AssetType.Texture) || (type == AssetType.Sound) || (type == AssetType.ImageTGA) || (type == AssetType.TextureTGA) || (type == AssetType.Animation); } public bool UploadCovered(UUID agentID) { return AmountCovered(agentID, PriceUpload); } public void ApplyUploadCharge(UUID agentID) { if (PriceUpload > 0) ApplyCharge(agentID, (int)MoneyTransactionType.UploadCharge, PriceUpload, "upload"); } public int MeshUploadCharge(int meshCount, int textureCount) { return (meshCount * PriceUpload) + (textureCount * PriceUpload); } public bool MeshUploadCovered(UUID agentID, int meshCount, int textureCount) { int amount = MeshUploadCharge(meshCount, textureCount); return AmountCovered(agentID, amount); } public void ApplyMeshUploadCharge(UUID agentID, int meshCount, int textureCount) { int transAmount = MeshUploadCharge(meshCount, textureCount); if (transAmount <= 0) return; string transDesc = "mesh upload"; int transCode = (int)MoneyTransactionType.UploadCharge; UUID transID = ApplyCharge(agentID, transCode, transAmount, transDesc); // The viewer notifies the user for most upload transactions, except for mesh uploads. // So if there's a client, notify them now. IClientAPI client = LocateClientObject(agentID); if (client != null) { TransactionInfoBlock transInfo = new TransactionInfoBlock(); transInfo.Amount = transAmount; transInfo.TransactionType = transCode; transInfo.SourceID = agentID; transInfo.DestID = UUID.Zero; transInfo.IsSourceGroup = false; transInfo.IsDestGroup = false; transInfo.ItemDescription = Util.StringToBytes256(transDesc); string message; if (String.IsNullOrEmpty(transDesc)) message = "You paid " + CurrencySymbol + transAmount.ToString() + "."; else message = "You paid " + CurrencySymbol + transAmount.ToString() + " for " + transDesc + "."; SendMoneyBalanceTransaction(client, transID, true, message, transInfo); } } public bool GroupCreationCovered(UUID agentID) { m_log.Debug("[MONEY]: In Group Creating, of GroupCreationCovered."); return AmountCovered(agentID, PriceGroupCreate); } public void ApplyGroupCreationCharge(UUID agentID) { if (PriceGroupCreate > 0) ApplyCharge(agentID, (int)MoneyTransactionType.GroupCreate, PriceGroupCreate, "group creation"); } // transCode is the transaction code, e.g. 1101 for uploads public UUID ApplyCharge(UUID agentID, int transCode, int transAmount, string transDesc) { // for transCodes, see comments at EOF UUID transID = doMoneyTransfer(agentID, CurrencyAccountID, transAmount, transCode, transDesc); return transID; } public void PostInitialize() { } public void Close() { } public string Name { get { return "InWorldzCurrencyModule"; } } public bool IsSharedModule { get { return true; } } #endregion public EconomyData GetEconomyData() { EconomyData edata = new EconomyData(); edata.ObjectCapacity = ObjectCapacity; edata.ObjectCount = ObjectCount; edata.PriceEnergyUnit = PriceEnergyUnit; edata.PriceGroupCreate = PriceGroupCreate; edata.PriceObjectClaim = PriceObjectClaim; edata.PriceObjectRent = PriceObjectRent; edata.PriceObjectScaleFactor = PriceObjectScaleFactor; edata.PriceParcelClaim = PriceParcelClaim; edata.PriceParcelClaimFactor = PriceParcelClaimFactor; edata.PriceParcelRent = PriceParcelRent; edata.PricePublicObjectDecay = PricePublicObjectDecay; edata.PricePublicObjectDelete = PricePublicObjectDelete; edata.PriceRentLight = PriceRentLight; edata.PriceUpload = PriceUpload; edata.TeleportMinPrice = TeleportMinPrice; return edata; } private void OnNewClient(IClientAPI client) { client.OnEconomyDataRequest += EconomyDataRequestHandler; //client.OnMoneyBalanceRequest += GetClientFunds(client); client.OnRequestPayPrice += requestPayPrice; client.OnObjectBuy += ObjectBuy; client.OnMoneyBalanceRequest += OnMoneyBalanceRequest; } private void EconomyDataRequestHandler(IClientAPI client, UUID agentID) { client.SendEconomyData(EnergyEfficiency, ObjectCapacity, ObjectCount, PriceEnergyUnit, PriceGroupCreate, PriceObjectClaim, PriceObjectRent, PriceObjectScaleFactor, PriceParcelClaim, PriceParcelClaimFactor, PriceParcelRent, PricePublicObjectDecay, PricePublicObjectDelete, PriceRentLight, PriceUpload, TeleportMinPrice, TeleportPriceExponent); } private void OnMoneyBalanceRequest(IClientAPI remoteClient, UUID agentID, UUID sessionID, UUID TransactionID) { Util.FireAndForget(delegate(object obj) { SendMoneyBalance(remoteClient); }); } /// <summary> /// Get the Current Balance /// </summary> /// <param name="avatarID">UUID of the avatar we're getting balance for</param> /// <returns></returns> private int getCurrentBalance(UUID avatarID) { int avatarFunds = 0; using (ISimpleDB db = _connFactory.GetConnection()) { const string TOTALS_SEARCH = "SELECT total FROM economy_totals WHERE user_id=?avatarID"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); List<Dictionary<string, string>> fundsResult = db.QueryWithResults(TOTALS_SEARCH, parms); if (fundsResult.Count == 1) { avatarFunds = Convert.ToInt32(fundsResult[0]["total"]); } else if (fundsResult.Count == 0) { //this user does not yet have a totals entry, we need to insert one const string TOTALS_POPULATOR = "INSERT IGNORE INTO economy_totals(user_id, total) " + "SELECT ?avatarID, SUM(transactionAmount) FROM economy_transaction WHERE destAvatarID = ?avatarID;"; db.QueryNoResults(TOTALS_POPULATOR, parms); //search again for the new total we just inserted fundsResult = db.QueryWithResults(TOTALS_SEARCH, parms); if (fundsResult.Count == 0) { //something is horribly wrong m_log.ErrorFormat("[CURRENCY]: Could not obtain currency total for avatar {0} after initial population", avatarID); avatarFunds = 0; } else { avatarFunds = Convert.ToInt32(fundsResult[0]["total"]); } } else { //something is horribly wrong m_log.ErrorFormat("[CURRENCY]: Multiple currency totals found for {0}. Table corrupt?", avatarID); avatarFunds = 0; } if (avatarFunds < MinDebugMoney) // only if configfile has MinDebugMoney=nnn avatarFunds = MinDebugMoney; // allow testing with fake money that restocks on login return avatarFunds; } } // See comments at the end of this file for the meaning of 'type' here (transaction type). private UUID doMoneyTransfer(UUID sourceAvatarID, UUID destAvatarID, int amount, int type, string description) { if (amount < 0) return UUID.Zero; // This is where we do all transfers of monies. This is a two step process, one to update the giver, and one // to update the recipient. using (ISimpleDB db = _connFactory.GetConnection()) { //verify the existance of the source and destination avatars Dictionary<string, object> testParms = new Dictionary<string, object>(); testParms.Add("?sourceAvatarID", sourceAvatarID); testParms.Add("?destAvatarID", destAvatarID); List<Dictionary<string, string>> results = db.QueryWithResults("SELECT COUNT(*) as matchCount FROM users WHERE UUID IN (?sourceAvatarID, ?destAvatarID);", testParms); if (results[0]["matchCount"] != "2") { if ((sourceAvatarID != destAvatarID) || (results[0]["matchCount"] != "1")) // don't report user paying themself m_log.Debug("[CURRENCY]: Source or destination avatar(s) do not exist in transaction. This is most likely a spoofed destination."); return UUID.Zero; } DateTime saveNow = DateTime.Now; int saveTime = Util.ToUnixTime(saveNow); Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?sourceAvatarID", sourceAvatarID); parms.Add("?destAvatarID", destAvatarID); parms.Add("?amount", amount); parms.Add("?debit", -amount); parms.Add("?type", type); parms.Add("?description", description); parms.Add("?time", saveTime); string bankQuery1 = "insert into economy_transaction (sourceAvatarID, destAvatarID, transactionAmount, transactionType, transactionDescription, timeOccurred) " + "VALUES (?sourceAvatarID, ?destAvatarID, ?amount, ?type, ?description, ?time)"; db.QueryNoResults(bankQuery1, parms); testParms.Clear(); results = db.QueryWithResults("SELECT LAST_INSERT_ID() AS id;", testParms); ulong transationID = Convert.ToUInt64(results[0]["id"]); string bankQuery2 = "insert into economy_transaction (sourceAvatarID, destAvatarID, transactionAmount, transactionType, transactionDescription, timeOccurred) " + "VALUES (?destAvatarID, ?sourceAvatarID, ?debit, ?type, ?description, ?time)"; db.QueryNoResults(bankQuery2, parms); return new UUID(transationID); } } /// <summary> /// Send the Balance to the viewer /// </summary> /// <param name="client">Client requesting information</param> private void SendMoneyBalanceTransaction(IClientAPI client, UUID transaction, bool success, string transactionDescription, TransactionInfoBlock transInfo) { UUID avatarID = client.AgentId; int avatarFunds = getCurrentBalance(avatarID); client.SendMoneyBalance(transaction, success, transactionDescription, avatarFunds, transInfo); } // Send a pure balance notification only. private void SendMoneyBalance(IClientAPI client) { SendMoneyBalanceTransaction(client, UUID.Zero, true, String.Empty, null); } // Returns the transaction ID that shows up in the transaction history. public string ObjectGiveMoney(UUID objectID, UUID sourceAvatarID, UUID destAvatarID, int amount, out string reason) { reason = String.Empty; if (amount <= 0) { reason = "INVALID_AMOUNT"; return String.Empty; } SceneObjectPart part = findPrim(objectID); if (part == null) { reason = "MISSING_PERMISSION_DEBIT"; // if you can't find it, no perms either return String.Empty; } string objName = part.ParentGroup.Name; string description = String.Format("{0} paid {1}", objName, resolveAgentName(destAvatarID)); int transType = (int)MoneyTransactionType.ObjectPays; if (amount > 0) { // allow users with negative balances to buy freebies int sourceAvatarFunds = getCurrentBalance(sourceAvatarID); if (sourceAvatarFunds < amount) { reason = "LINDENDOLLAR_INSUFFICIENTFUNDS"; return String.Empty; } } UUID transID = doMoneyTransfer(sourceAvatarID, destAvatarID, amount, transType, description); // the transID UUID is actually a ulong stored in a UUID. string result = transID.GetULong().ToString(); reason = String.Empty; TransactionInfoBlock transInfo = new TransactionInfoBlock(); transInfo.Amount = amount; transInfo.TransactionType = transType; transInfo.SourceID = sourceAvatarID; transInfo.DestID = destAvatarID; transInfo.IsSourceGroup = false; transInfo.IsDestGroup = false; transInfo.ItemDescription = Util.StringToBytes256(objName); IClientAPI sourceAvatarClient = LocateClientObject(sourceAvatarID); if (sourceAvatarClient == null) { // Just a quick catch for a null reference, just cause they can't be found doesn't // mean the item can't pay out the money. } else { string sourceText = objName + " paid out " + CurrencySymbol + amount + " to " + resolveAgentName(destAvatarID); SendMoneyBalanceTransaction(sourceAvatarClient, transID, true, sourceText, transInfo); } IClientAPI destAvatarClient = LocateClientObject(destAvatarID); if(destAvatarClient == null) { // Quick catch due to scene issues, don't want to it to fall down if // the destination avatar is not in the same scene list or online at all. } else { string destText = "You were paid " + CurrencySymbol + amount + " by " + part.ParentGroup.Name; SendMoneyBalanceTransaction(destAvatarClient, transID, true, destText, transInfo); } return result; } private bool CheckPayObjectAmount(SceneObjectPart part, int amount) { SceneObjectPart root = part.ParentGroup.RootPart; if (amount < 0) return false; // must be positive amount if (part.ParentGroup.RootPart.PayPrice[0] != SceneObjectPart.PAY_HIDE) return true; // any other value is legal for (int x = 1; x <= 4; x++) { if (root.PayPrice[x] == SceneObjectPart.PAY_DEFAULT) { // amount is only implied, check the implied value switch (x) { case 1: if (amount == SceneObjectPart.PAY_DEFAULT1) return true; break; case 2: if (amount == SceneObjectPart.PAY_DEFAULT2) return true; break; case 3: if (amount == SceneObjectPart.PAY_DEFAULT3) return true; break; case 4: if (amount == SceneObjectPart.PAY_DEFAULT4) return true; break; } } else { // not PAY_DEFAULT, a specific amount on the button if (amount == part.ParentGroup.RootPart.PayPrice[x]) return true; // it's one of the legal amounts listed } } return false; // not one of the listed amounts } // Returns true if the operation should be blocked. private static IMuteListModule m_muteListModule = null; private bool IsMutedObject(SceneObjectGroup group, UUID senderID) { // This may seem backwards but if the payer has this object // or its owner muted, the object cannot give anything back // for payment. Do not allow payment to objects that are muted. if (m_muteListModule == null) m_muteListModule = group.Scene.RequestModuleInterface<IMuteListModule>(); if (m_muteListModule == null) return false; // payer has object owner muted? if (m_muteListModule.IsMuted(group.OwnerID, senderID)) return true; // payer has the object muted? if (m_muteListModule.IsMuted(group.UUID, senderID)) return true; // neither the object nor owner are muted return false; } private void MoneyTransferAction(Object osender, EventManager.MoneyTransferArgs e) { if (e.amount < 0) return; //ScenePresence sourceAvatar = m_scene.GetScenePresence(e.sender); //IClientAPI sourceAvatarClient = sourceAvatar.ControllingClient; UUID sourceAvatarID = e.sender; int transType = e.transactiontype; string transDesc = e.description; UUID destAvatarID = e.receiver; int transAmount = e.amount; IClientAPI sourceAvatarClient; IClientAPI destAvatarClient; string sourceText = String.Empty; string destText = String.Empty; TransactionInfoBlock transInfo = new TransactionInfoBlock(); transInfo.Amount = transAmount; transInfo.TransactionType = transType; transInfo.SourceID = sourceAvatarID; transInfo.DestID = destAvatarID; transInfo.IsSourceGroup = false; transInfo.IsDestGroup = false; transInfo.ItemDescription = new byte[0]; sourceAvatarClient = LocateClientObject(sourceAvatarID); if (sourceAvatarClient == null) { m_log.Debug("[CURRENCY]: Source Avatar not found!"); return; } if (transType == (int)MoneyTransactionType.PayObject) { SceneObjectPart part = findPrim(e.receiver); if (!CheckPayObjectAmount(part, e.amount)) { sourceAvatarClient.SendAgentAlertMessage("Invalid amount used for payment to object.", false); return; } // Check if the object or owner are muted. if (IsMutedObject(part.ParentGroup, sourceAvatarID)) { sourceAvatarClient.SendAgentAlertMessage("Cannot give money to an object or object owner that you have muted. If the viewer has automatically unblocked the owner, you can retry payment.", false); return; } destAvatarID = part.OwnerID; destAvatarClient = LocateClientObject(destAvatarID); Vector3 pos = part.AbsolutePosition; int posx = (int)(pos.X + 0.5); // round to nearest int posy = (int)(pos.Y + 0.5); // round to nearest int posz = (int)(pos.Z + 0.5); // round to nearest transInfo.DestID = destAvatarID; transInfo.ItemDescription = Util.StringToBytes256(part.ParentGroup.RootPart.Name); transDesc = String.Format("Paid {0} via object {1} in {2} at <{3},{4},{5}>", resolveAgentName(destAvatarID), part.ParentGroup.Name, part.ParentGroup.Scene.RegionInfo.RegionName, posx, posy, posz); sourceText = "You paid " + resolveAgentName(destAvatarID) + " " + CurrencySymbol + transAmount + " via " + part.ParentGroup.Name; destText = resolveAgentName(sourceAvatarID) + " paid you " + CurrencySymbol + transAmount; } else { destAvatarID = (e.receiver); destAvatarClient = LocateClientObject(destAvatarID); if (destAvatarClient == null) { } else if (LocateSceneClientIn(destAvatarID).GetScenePresence(destAvatarID).IsBot) { sourceAvatarClient.SendAgentAlertMessage("You cannot pay a bot.", false); return; } transDesc = "Gift"; sourceText = "You paid " + resolveAgentName(destAvatarID) + " " + CurrencySymbol + transAmount; destText = resolveAgentName(sourceAvatarID) + " paid you " + CurrencySymbol + transAmount; } if (transAmount > 0) { // allow users with negative balances to buy freebies int avatarFunds = getCurrentBalance(sourceAvatarID); if (avatarFunds < transAmount) { sourceAvatarClient.SendAgentAlertMessage("Insufficient funds at this time", false); return; } } UUID transID; bool success; if (sourceAvatarID == destAvatarID) { // catching here, they can test but no reason to stuff crap in the db for testing transID = UUID.Zero; success = true; } else { transID = doMoneyTransfer(sourceAvatarID, destAvatarID, transAmount, transType, transDesc); success = (transID != UUID.Zero); } //if this is a scripted transaction let the script know money has changed hands if (transType == (int)MoneyTransactionType.PayObject) { this.OnObjectPaid(e.receiver, sourceAvatarID, transAmount); } SendMoneyBalanceTransaction(sourceAvatarClient, transID, success, sourceText, transInfo); if (destAvatarClient == null) { // don't want to do anything, as they can not be found, this is ugly but will suffice // until we get the scene working correctly to pull every avatar } else { SendMoneyBalanceTransaction(destAvatarClient, transID, success, destText, transInfo); } } private void ClassifiedPayment(Object osender, EventManager.ClassifiedPaymentArgs e) { IClientAPI remoteClient = (IClientAPI)osender; e.mIsAuthorized = false; int costToApply = e.mUpdatedPrice - e.mOrigPrice; if (costToApply > 0) // no refunds for lower prices { // Handle the actual money transaction here. int avatarFunds = getCurrentBalance(e.mBuyerID); if (avatarFunds < costToApply) { string costText = String.Empty; if (e.mOrigPrice != 0) // this is an updated classified costText = "increase "; remoteClient.SendAgentAlertMessage("The classified price " + costText + " (" + CurrencySymbol + costToApply.ToString() + ") exceeds your current balance (" + avatarFunds.ToString() + ").", true); return; } } e.mIsAuthorized = true; if (e.mIsPreCheck) return; // perform actual money transaction doMoneyTransfer(e.mBuyerID, CurrencyAccountID, costToApply, (int)MoneyTransactionType.ClassifiedCharge, e.mDescription); SendMoneyBalance(remoteClient); // send balance update if (e.mOrigPrice == 0) // this is an initial classified charge. remoteClient.SendAgentAlertMessage("You have paid " + CurrencySymbol + costToApply.ToString() + " for this classified ad.", false); else // this is an updated classified remoteClient.SendAgentAlertMessage("You have paid an additional " + CurrencySymbol + costToApply.ToString() + " for this classified ad.", false); } public void ObjectBuy(IClientAPI remoteClient, UUID agentID, UUID sessionID, UUID groupID, UUID categoryID, uint localID, byte saleType, int salePrice) { if (salePrice < 0) return; if (salePrice > 0) { // allow users with negative balances to buy freebies int avatarFunds = getCurrentBalance(agentID); if (avatarFunds < salePrice) { // The viewer runs a check on monies balance, however, let's make sure another viewer // can't exploit this by removing and check their funds ourselves. remoteClient.SendAgentAlertMessage("Insufficient funds to purchase this item!", false); return; } } IClientAPI sourceAvatarClient = LocateClientObject(remoteClient.AgentId); if (sourceAvatarClient == null) { sourceAvatarClient.SendAgentAlertMessage("Purchase failed. No Controlling client found for sourceAvatar!", false); return; } Scene s = LocateSceneClientIn(remoteClient.AgentId); //Scene s = GetScenePresence(remoteClient.AgentId); SceneObjectPart objectPart = s.GetSceneObjectPart(localID); if (objectPart == null) { sourceAvatarClient.SendAgentAlertMessage("Purchase failed. The object was not found.", false); return; } ///// Prevent purchase spoofing, as well as viewer bugs. ///// // Verify that the object is actually for sale if (objectPart.ObjectSaleType == (byte)SaleType.Not) { remoteClient.SendAgentAlertMessage("Purchase failed. The item is not for sale.", false); return; } // Verify that the viewer sale type actually matches the correct sale type of the object if (saleType != objectPart.ObjectSaleType) { remoteClient.SendAgentAlertMessage("Purchase failed. The sale type does not match.", false); return; } // Verify that the buyer is paying the correct amount if (salePrice != objectPart.SalePrice) { remoteClient.SendAgentAlertMessage("Purchase failed. The payment price does not match the sale price.", false); return; } string objName = objectPart.ParentGroup.RootPart.Name; Vector3 pos = objectPart.AbsolutePosition; int posx = (int)(pos.X + 0.5); int posy = (int)(pos.Y + 0.5); int posz = (int)(pos.Z + 0.5); string transDesc = String.Format("{0} in {1} at <{2},{3},{4}>", objName, objectPart.ParentGroup.Scene.RegionInfo.RegionName, posx, posy, posz); string sourceAlertText = "Purchased " + objName + " for " + CurrencySymbol + salePrice; string destAlertText = resolveAgentName(agentID) + " paid you " + CurrencySymbol + salePrice + " via " + objName; int transType = (int)MoneyTransactionType.ObjectSale; UUID transID = UUID.Zero; TransactionInfoBlock transInfo = new TransactionInfoBlock(); transInfo.Amount = salePrice; transInfo.TransactionType = transType; transInfo.SourceID = remoteClient.AgentId; transInfo.DestID = objectPart.OwnerID; transInfo.IsSourceGroup = false; transInfo.IsDestGroup = false; transInfo.ItemDescription = Util.StringToBytes256(objName); if (agentID == objectPart.OwnerID) { // we'll let them test the buy, but nothing happens money wise. if (!s.PerformObjectBuy(remoteClient, categoryID, localID, saleType)) return; sourceAvatarClient.SendBlueBoxMessage(agentID, String.Empty, sourceAlertText); } else { if (salePrice == 0) { // We need to add a counter here for Freebies thus bypassing the DB for transactions cause // Freebies are a pain to have to track in the transaction history. if (!s.PerformObjectBuy(remoteClient, categoryID, localID, saleType)) return; } else { UUID originalOwnerID = objectPart.OwnerID; // capture the original seller's UUID for the money transfer if (!s.PerformObjectBuy(remoteClient, categoryID, localID, saleType)) // changes objectPart.OwnerID return; transID = doMoneyTransfer(remoteClient.AgentId, originalOwnerID, salePrice, transType, transDesc); } SendMoneyBalanceTransaction(sourceAvatarClient, transID, true, sourceAlertText, transInfo); } IClientAPI destAvatarClient = LocateClientObject(objectPart.OwnerID); if (destAvatarClient == null) { return; } else { SendMoneyBalanceTransaction(destAvatarClient, transID, true, destAlertText, transInfo); } } // This method is called after LandManagementModule's handleLandValidationRequest() method has performed that. // All land-related validation belongs there. private void ValidateLandBuy(Object osender, EventManager.LandBuyArgs e) { // internal system parameters (validated) // Scene scene = (Scene)osender; if (e.landValidated && e.parcel != null) { UUID sourceClientID = e.agentId; // this viewer parameter has been validated by LLCV int avatarFunds = getCurrentBalance(sourceClientID); LandData parcel = e.parcel.landData; UUID destClientID = parcel.OwnerID; int transAmount = parcel.SalePrice; if (avatarFunds >= transAmount) e.economyValidated = true; } } private void processLandBuy(Object osender, EventManager.LandBuyArgs e) { if (e.transactionID != 0) { // Not sure what this error is, duplicate purchase request for if the packet comes in a second time? return; } e.transactionID = Util.UnixTimeSinceEpoch(); // This method should not do any additional validation. // Any required validation should have been performed either // in LandManagementModule handleLandValidationRequest() or // in ValidateLandBuy above. int transType = (int)MoneyTransactionType.LandSale; string transDesc = "Land purchase"; UUID sourceClientID = e.agentId; IClientAPI sourceClient = LocateClientObject(sourceClientID); if (!e.economyValidated) { if (sourceClient != null) sourceClient.SendAgentAlertMessage("Could not validate user account balance for purchase.", false); return; } if ((e.parcel == null) || (!e.landValidated)) return; LandData parcel = e.parcel.landData; int transAmount = e.originalParcelPrice; UUID transID = UUID.Zero; UUID destClientID = e.originalParcelOwner; IClientAPI destClient = LocateClientObject(destClientID); // Pick a spot inside the parcel. Since blocks are 4x4, pick a spot 2m inside the bottom corner block. Vector3 pos = parcel.AABBMin; pos.X += 2; pos.Y += 2; transDesc += " at " + e.parcel.regionName + " (" + pos.X + "," + pos.Y + "): " + parcel.Name; // limit the result to 255 for the db storage if (transDesc.Length > 255) transDesc = transDesc.Substring(0, 255); // requires 2 users: source and dest clients must both be users (not groups, not same) transID = doMoneyTransfer(sourceClientID, destClientID, transAmount, transType, transDesc); TransactionInfoBlock transInfo = new TransactionInfoBlock(); transInfo.Amount = transAmount; transInfo.TransactionType = transType; transInfo.ItemDescription = Util.StringToBytes256(transDesc); transInfo.SourceID = sourceClientID; transInfo.IsSourceGroup = false; transInfo.DestID = e.originalParcelOwner; if (e.originalIsGroup) { // not currently supported (blocked in LandManagementModule handleLandValidationRequest()) // unless price is 0, because we cannot pass a group ID to doMoneyTransfer above. transInfo.IsDestGroup = true; } else { transInfo.IsDestGroup = false; } if (sourceClient != null) { string destName = resolveAgentName(destClientID); if (String.IsNullOrEmpty(destName)) destName = "a group (or unknown user)"; string sourceText = "You paid " + CurrencySymbol + transAmount + " to " + destName + " for a parcel of land."; SendMoneyBalanceTransaction(sourceClient, transID, true, sourceText, transInfo); } if (destClient != null) { string destName = resolveAgentName(sourceClientID); if (String.IsNullOrEmpty(destName)) destName = "a group (or unknown user)"; string destText = "You were paid " + CurrencySymbol + transAmount + " by " + destName + " for a parcel of land."; SendMoneyBalanceTransaction(destClient, transID, true, destText, transInfo); } } public bool AmountCovered(UUID agentID, int amount) { if (amount <= 0) return true; // allow users with 0 or negative balance to buy freebies int avatarFunds = getCurrentBalance(agentID); return avatarFunds >= amount; } public void requestPayPrice(IClientAPI client, UUID objectID) { Scene scene = LocateSceneClientIn(client.AgentId); if (scene == null) return; SceneObjectPart task = scene.GetSceneObjectPart(objectID); if (task == null) return; SceneObjectGroup group = task.ParentGroup; SceneObjectPart root = group.RootPart; client.SendPayPrice(objectID, root.PayPrice); } #region AvatarCurrency Helper Functions private SceneObjectPart findPrim(UUID objectID) { lock (m_scenel) { foreach (Scene s in m_scenel.Values) { SceneObjectPart part = s.GetSceneObjectPart(objectID); if (part != null) { return part; } } } return null; } private SceneObjectPart findPrimID(uint localID) { lock (m_scenel) { foreach (Scene objectScene in m_scenel.Values) { SceneObjectPart part = objectScene.GetSceneObjectPart(localID); if (part != null) { return part; } } } return null; } private string resolveAgentName(UUID agentID) { // try avatar username surname Scene scene = GetRandomScene(); string name = scene.CommsManager.UserService.Key2Name(agentID,false); if (String.IsNullOrEmpty(name)) m_log.ErrorFormat("[MONEY]: Could not resolve user {0}", agentID); return name; } public Scene GetRandomScene() { lock (m_scenel) { foreach (Scene rs in m_scenel.Values) return rs; } return null; } private Scene LocateSceneClientIn(UUID AgentId) { lock (m_scenel) { foreach (Scene _scene in m_scenel.Values) { ScenePresence tPresence = _scene.GetScenePresence(AgentId); if (tPresence != null) { if (!tPresence.IsChildAgent) { return _scene; } } } } return null; } private IClientAPI LocateClientObject(UUID AgentID) { ScenePresence tPresence = null; IClientAPI rclient = null; lock (m_scenel) { foreach (Scene _scene in m_scenel.Values) { tPresence = _scene.GetScenePresence(AgentID); if (tPresence != null) { if (!tPresence.IsChildAgent) { rclient = tPresence.ControllingClient; } } if (rclient != null) { return rclient; } } } return null; } } #endregion } // Transaction types, from https://lists.secondlife.com/pipermail/sldev-commits/2009-September.txt /* +class MoneyTransactionType(object): + String.Empty" Money transaction type constants String.Empty" + + Null = 0 + +# Codes 1000-1999 reserved for one-time charges + ObjectClaim = 1000 + LandClaim = 1001 + GroupCreate = 1002 + ObjectPublicClaim = 1003 + GroupJoin = 1004 # May be moved to group transactions eventually + TeleportCharge = 1100 # FF not sure why this jumps to 1100... + UploadCharge = 1101 + LandAuction = 1102 + ClassifiedCharge = 1103 + +# Codes 2000-2999 reserved for recurrent charges + ObjectTax = 2000 + LandTax = 2001 + LightTax = 2002 + ParcelDirFee = 2003 + GroupTax = 2004 # Taxes incurred as part of group membership + ClassifiedRenew = 2005 + +# Codes 3000-3999 reserved for inventory transactions + GiveInventory = 3000 + +# Codes 5000-5999 reserved for transfers between users + ObjectSale = 5000 + Gift = 5001 + LandSale = 5002 + ReferBonus = 5003 + InventorySale = 5004 + RefundPurchase = 5005 + LandPassSale = 5006 + DwellBonus = 5007 + PayObject = 5008 + ObjectPays = 5009 + +# Codes 6000-6999 reserved for group transactions +# GroupJoin = 6000 # reserved for future use + GroupLandDeed = 6001 + GroupObjectDeed = 6002 + GroupLiability = 6003 + GroupDividend = 6004 + MembershipDues = 6005 + +# Codes 8000-8999 reserved for one-type credits + ObjectRelease = 8000 + LandRelease = 8001 + ObjectDelete = 8002 + ObjectPublicDecay = 8003 + ObjectPublicDelete = 8004 + +# Code 9000-9099 reserved for usertool transactions + LindenAdjustment = 9000 + LindenGrant = 9001 + LindenPenalty = 9002 + EventFee = 9003 + EventPrize = 9004 + +# Codes 10000-10999 reserved for stipend credits + StipendBasic = 10000 + StipendDeveloper = 10001 + StipendAlways = 10002 + StipendDaily = 10003 + StipendRating = 10004 + StipendDelta = 10005 + +class TransactionFlags(object): + Null = 0 + SourceGroup = 1 + DestGroup = 2 + OwnerGroup = 4 + SimultaneousContribution = 8 + SimultaneousContributionRemoval = 16 */
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable MemberCanBePrivate.Global #pragma warning disable 618 namespace Apache.Ignite.Core.Tests { using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Affinity.Rendezvous; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cache.Eviction; using Apache.Ignite.Core.Cache.Expiry; using Apache.Ignite.Core.Cache.Store; using Apache.Ignite.Core.Ssl; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Communication.Tcp; using Apache.Ignite.Core.Configuration; using Apache.Ignite.Core.DataStructures.Configuration; using Apache.Ignite.Core.Deployment; using Apache.Ignite.Core.Discovery.Tcp; using Apache.Ignite.Core.Discovery.Tcp.Multicast; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Failure; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.PersistentStore; using Apache.Ignite.Core.Plugin.Cache; using Apache.Ignite.Core.Tests.Binary; using Apache.Ignite.Core.Tests.Plugin; using Apache.Ignite.Core.Transactions; using Apache.Ignite.NLog; using NUnit.Framework; using CheckpointWriteOrder = Apache.Ignite.Core.PersistentStore.CheckpointWriteOrder; using DataPageEvictionMode = Apache.Ignite.Core.Cache.Configuration.DataPageEvictionMode; using WalMode = Apache.Ignite.Core.PersistentStore.WalMode; /// <summary> /// Tests <see cref="IgniteConfiguration"/> serialization. /// </summary> public class IgniteConfigurationSerializerTest { /// <summary> /// Tests the predefined XML. /// </summary> [Test] public void TestPredefinedXml() { var xml = File.ReadAllText("Config\\full-config.xml"); var cfg = IgniteConfiguration.FromXml(xml); Assert.AreEqual("c:", cfg.WorkDirectory); Assert.AreEqual("127.1.1.1", cfg.Localhost); Assert.IsTrue(cfg.IsDaemon); Assert.AreEqual(1024, cfg.JvmMaxMemoryMb); Assert.AreEqual(TimeSpan.FromSeconds(10), cfg.MetricsLogFrequency); Assert.AreEqual(TimeSpan.FromMinutes(1), ((TcpDiscoverySpi)cfg.DiscoverySpi).JoinTimeout); Assert.AreEqual("192.168.1.1", ((TcpDiscoverySpi)cfg.DiscoverySpi).LocalAddress); Assert.AreEqual(6655, ((TcpDiscoverySpi)cfg.DiscoverySpi).LocalPort); Assert.AreEqual(7, ((TcpDiscoveryMulticastIpFinder) ((TcpDiscoverySpi) cfg.DiscoverySpi).IpFinder).AddressRequestAttempts); Assert.AreEqual(new[] { "-Xms1g", "-Xmx4g" }, cfg.JvmOptions); Assert.AreEqual(15, ((LifecycleBean) cfg.LifecycleHandlers.Single()).Foo); Assert.AreEqual("testBar", ((NameMapper) cfg.BinaryConfiguration.NameMapper).Bar); Assert.AreEqual( "Apache.Ignite.Core.Tests.IgniteConfigurationSerializerTest+FooClass, Apache.Ignite.Core.Tests", cfg.BinaryConfiguration.Types.Single()); Assert.IsFalse(cfg.BinaryConfiguration.CompactFooter); Assert.AreEqual(new[] {42, EventType.TaskFailed, EventType.JobFinished}, cfg.IncludedEventTypes); Assert.AreEqual(@"c:\myconfig.xml", cfg.SpringConfigUrl); Assert.IsTrue(cfg.AutoGenerateIgniteInstanceName); Assert.AreEqual(new TimeSpan(1, 2, 3), cfg.LongQueryWarningTimeout); Assert.IsFalse(cfg.IsActiveOnStart); Assert.IsTrue(cfg.AuthenticationEnabled); Assert.AreEqual(10000, cfg.MvccVacuumFrequency); Assert.AreEqual(4, cfg.MvccVacuumThreadCount); Assert.AreEqual(123, cfg.SqlQueryHistorySize); Assert.IsNotNull(cfg.SqlSchemas); Assert.AreEqual(2, cfg.SqlSchemas.Count); Assert.IsTrue(cfg.SqlSchemas.Contains("SCHEMA_1")); Assert.IsTrue(cfg.SqlSchemas.Contains("schema_2")); Assert.AreEqual("someId012", cfg.ConsistentId); Assert.IsFalse(cfg.RedirectJavaConsoleOutput); Assert.AreEqual("secondCache", cfg.CacheConfiguration.Last().Name); var cacheCfg = cfg.CacheConfiguration.First(); Assert.AreEqual(CacheMode.Replicated, cacheCfg.CacheMode); Assert.IsTrue(cacheCfg.ReadThrough); Assert.IsTrue(cacheCfg.WriteThrough); Assert.IsInstanceOf<MyPolicyFactory>(cacheCfg.ExpiryPolicyFactory); Assert.IsTrue(cacheCfg.EnableStatistics); Assert.IsFalse(cacheCfg.WriteBehindCoalescing); Assert.AreEqual(PartitionLossPolicy.ReadWriteAll, cacheCfg.PartitionLossPolicy); Assert.AreEqual("fooGroup", cacheCfg.GroupName); Assert.AreEqual("bar", cacheCfg.KeyConfiguration.Single().AffinityKeyFieldName); Assert.AreEqual("foo", cacheCfg.KeyConfiguration.Single().TypeName); Assert.IsTrue(cacheCfg.OnheapCacheEnabled); Assert.AreEqual(8, cacheCfg.StoreConcurrentLoadAllThreshold); Assert.AreEqual(9, cacheCfg.RebalanceOrder); Assert.AreEqual(10, cacheCfg.RebalanceBatchesPrefetchCount); Assert.AreEqual(11, cacheCfg.MaxQueryIteratorsCount); Assert.AreEqual(12, cacheCfg.QueryDetailMetricsSize); Assert.AreEqual(13, cacheCfg.QueryParallelism); Assert.AreEqual("mySchema", cacheCfg.SqlSchema); var queryEntity = cacheCfg.QueryEntities.Single(); Assert.AreEqual(typeof(int), queryEntity.KeyType); Assert.AreEqual(typeof(string), queryEntity.ValueType); Assert.AreEqual("myTable", queryEntity.TableName); Assert.AreEqual("length", queryEntity.Fields.Single().Name); Assert.AreEqual(typeof(int), queryEntity.Fields.Single().FieldType); Assert.IsTrue(queryEntity.Fields.Single().IsKeyField); Assert.IsTrue(queryEntity.Fields.Single().NotNull); Assert.AreEqual(3.456d, (double)queryEntity.Fields.Single().DefaultValue); Assert.AreEqual("somefield.field", queryEntity.Aliases.Single().FullName); Assert.AreEqual("shortField", queryEntity.Aliases.Single().Alias); var queryIndex = queryEntity.Indexes.Single(); Assert.AreEqual(QueryIndexType.Geospatial, queryIndex.IndexType); Assert.AreEqual("indexFld", queryIndex.Fields.Single().Name); Assert.AreEqual(true, queryIndex.Fields.Single().IsDescending); Assert.AreEqual(123, queryIndex.InlineSize); var nearCfg = cacheCfg.NearConfiguration; Assert.IsNotNull(nearCfg); Assert.AreEqual(7, nearCfg.NearStartSize); var plc = nearCfg.EvictionPolicy as FifoEvictionPolicy; Assert.IsNotNull(plc); Assert.AreEqual(10, plc.BatchSize); Assert.AreEqual(20, plc.MaxSize); Assert.AreEqual(30, plc.MaxMemorySize); var plc2 = cacheCfg.EvictionPolicy as LruEvictionPolicy; Assert.IsNotNull(plc2); Assert.AreEqual(1, plc2.BatchSize); Assert.AreEqual(2, plc2.MaxSize); Assert.AreEqual(3, plc2.MaxMemorySize); var af = cacheCfg.AffinityFunction as RendezvousAffinityFunction; Assert.IsNotNull(af); Assert.AreEqual(99, af.Partitions); Assert.IsTrue(af.ExcludeNeighbors); Assert.AreEqual(new Dictionary<string, object> { {"myNode", "true"}, {"foo", new FooClass {Bar = "Baz"}} }, cfg.UserAttributes); var atomicCfg = cfg.AtomicConfiguration; Assert.AreEqual(2, atomicCfg.Backups); Assert.AreEqual(CacheMode.Local, atomicCfg.CacheMode); Assert.AreEqual(250, atomicCfg.AtomicSequenceReserveSize); var tx = cfg.TransactionConfiguration; Assert.AreEqual(TransactionConcurrency.Optimistic, tx.DefaultTransactionConcurrency); Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.DefaultTransactionIsolation); Assert.AreEqual(new TimeSpan(0,1,2), tx.DefaultTimeout); Assert.AreEqual(15, tx.PessimisticTransactionLogSize); Assert.AreEqual(TimeSpan.FromSeconds(33), tx.PessimisticTransactionLogLinger); var comm = cfg.CommunicationSpi as TcpCommunicationSpi; Assert.IsNotNull(comm); Assert.AreEqual(33, comm.AckSendThreshold); Assert.AreEqual(new TimeSpan(0, 1, 2), comm.IdleConnectionTimeout); Assert.IsInstanceOf<TestLogger>(cfg.Logger); var binType = cfg.BinaryConfiguration.TypeConfigurations.Single(); Assert.AreEqual("typeName", binType.TypeName); Assert.AreEqual("affKeyFieldName", binType.AffinityKeyFieldName); Assert.IsTrue(binType.IsEnum); Assert.AreEqual(true, binType.KeepDeserialized); Assert.IsInstanceOf<IdMapper>(binType.IdMapper); Assert.IsInstanceOf<NameMapper>(binType.NameMapper); Assert.IsInstanceOf<TestSerializer>(binType.Serializer); var plugins = cfg.PluginConfigurations; Assert.IsNotNull(plugins); Assert.IsNotNull(plugins.Cast<TestIgnitePluginConfiguration>().SingleOrDefault()); Assert.IsNotNull(cacheCfg.PluginConfigurations.Cast<MyPluginConfiguration>().SingleOrDefault()); var eventStorage = cfg.EventStorageSpi as MemoryEventStorageSpi; Assert.IsNotNull(eventStorage); Assert.AreEqual(23.45, eventStorage.ExpirationTimeout.TotalSeconds); Assert.AreEqual(129, eventStorage.MaxEventCount); var memCfg = cfg.MemoryConfiguration; Assert.IsNotNull(memCfg); Assert.AreEqual(3, memCfg.ConcurrencyLevel); Assert.AreEqual("dfPlc", memCfg.DefaultMemoryPolicyName); Assert.AreEqual(45, memCfg.PageSize); Assert.AreEqual(67, memCfg.SystemCacheInitialSize); Assert.AreEqual(68, memCfg.SystemCacheMaxSize); var memPlc = memCfg.MemoryPolicies.Single(); Assert.AreEqual(1, memPlc.EmptyPagesPoolSize); Assert.AreEqual(0.2, memPlc.EvictionThreshold); Assert.AreEqual("dfPlc", memPlc.Name); Assert.AreEqual(DataPageEvictionMode.RandomLru, memPlc.PageEvictionMode); Assert.AreEqual("abc", memPlc.SwapFilePath); Assert.AreEqual(89, memPlc.InitialSize); Assert.AreEqual(98, memPlc.MaxSize); Assert.IsTrue(memPlc.MetricsEnabled); Assert.AreEqual(9, memPlc.SubIntervals); Assert.AreEqual(TimeSpan.FromSeconds(62), memPlc.RateTimeInterval); Assert.AreEqual(PeerAssemblyLoadingMode.CurrentAppDomain, cfg.PeerAssemblyLoadingMode); var sql = cfg.SqlConnectorConfiguration; Assert.IsNotNull(sql); Assert.AreEqual("bar", sql.Host); Assert.AreEqual(10, sql.Port); Assert.AreEqual(11, sql.PortRange); Assert.AreEqual(12, sql.SocketSendBufferSize); Assert.AreEqual(13, sql.SocketReceiveBufferSize); Assert.IsTrue(sql.TcpNoDelay); Assert.AreEqual(14, sql.MaxOpenCursorsPerConnection); Assert.AreEqual(15, sql.ThreadPoolSize); var client = cfg.ClientConnectorConfiguration; Assert.IsNotNull(client); Assert.AreEqual("bar", client.Host); Assert.AreEqual(10, client.Port); Assert.AreEqual(11, client.PortRange); Assert.AreEqual(12, client.SocketSendBufferSize); Assert.AreEqual(13, client.SocketReceiveBufferSize); Assert.IsTrue(client.TcpNoDelay); Assert.AreEqual(14, client.MaxOpenCursorsPerConnection); Assert.AreEqual(15, client.ThreadPoolSize); Assert.AreEqual(19, client.IdleTimeout.TotalSeconds); var pers = cfg.PersistentStoreConfiguration; Assert.AreEqual(true, pers.AlwaysWriteFullPages); Assert.AreEqual(TimeSpan.FromSeconds(1), pers.CheckpointingFrequency); Assert.AreEqual(2, pers.CheckpointingPageBufferSize); Assert.AreEqual(3, pers.CheckpointingThreads); Assert.AreEqual(TimeSpan.FromSeconds(4), pers.LockWaitTime); Assert.AreEqual("foo", pers.PersistentStorePath); Assert.AreEqual(5, pers.TlbSize); Assert.AreEqual("bar", pers.WalArchivePath); Assert.AreEqual(TimeSpan.FromSeconds(6), pers.WalFlushFrequency); Assert.AreEqual(7, pers.WalFsyncDelayNanos); Assert.AreEqual(8, pers.WalHistorySize); Assert.AreEqual(WalMode.None, pers.WalMode); Assert.AreEqual(9, pers.WalRecordIteratorBufferSize); Assert.AreEqual(10, pers.WalSegments); Assert.AreEqual(11, pers.WalSegmentSize); Assert.AreEqual("baz", pers.WalStorePath); Assert.IsTrue(pers.MetricsEnabled); Assert.AreEqual(3, pers.SubIntervals); Assert.AreEqual(TimeSpan.FromSeconds(6), pers.RateTimeInterval); Assert.AreEqual(CheckpointWriteOrder.Random, pers.CheckpointWriteOrder); Assert.IsTrue(pers.WriteThrottlingEnabled); var listeners = cfg.LocalEventListeners; Assert.AreEqual(2, listeners.Count); var rebalListener = (LocalEventListener<CacheRebalancingEvent>) listeners.First(); Assert.AreEqual(new[] {EventType.CacheObjectPut, 81}, rebalListener.EventTypes); Assert.AreEqual("Apache.Ignite.Core.Tests.EventsTestLocalListeners+Listener`1" + "[Apache.Ignite.Core.Events.CacheRebalancingEvent]", rebalListener.Listener.GetType().ToString()); var ds = cfg.DataStorageConfiguration; Assert.IsFalse(ds.AlwaysWriteFullPages); Assert.AreEqual(TimeSpan.FromSeconds(1), ds.CheckpointFrequency); Assert.AreEqual(3, ds.CheckpointThreads); Assert.AreEqual(4, ds.ConcurrencyLevel); Assert.AreEqual(TimeSpan.FromSeconds(5), ds.LockWaitTime); Assert.IsTrue(ds.MetricsEnabled); Assert.AreEqual(6, ds.PageSize); Assert.AreEqual("cde", ds.StoragePath); Assert.AreEqual(TimeSpan.FromSeconds(7), ds.MetricsRateTimeInterval); Assert.AreEqual(8, ds.MetricsSubIntervalCount); Assert.AreEqual(9, ds.SystemRegionInitialSize); Assert.AreEqual(10, ds.SystemRegionMaxSize); Assert.AreEqual(11, ds.WalThreadLocalBufferSize); Assert.AreEqual("abc", ds.WalArchivePath); Assert.AreEqual(TimeSpan.FromSeconds(12), ds.WalFlushFrequency); Assert.AreEqual(13, ds.WalFsyncDelayNanos); Assert.AreEqual(14, ds.WalHistorySize); Assert.AreEqual(Core.Configuration.WalMode.Background, ds.WalMode); Assert.AreEqual(15, ds.WalRecordIteratorBufferSize); Assert.AreEqual(16, ds.WalSegments); Assert.AreEqual(17, ds.WalSegmentSize); Assert.AreEqual("wal-store", ds.WalPath); Assert.AreEqual(TimeSpan.FromSeconds(18), ds.WalAutoArchiveAfterInactivity); Assert.IsTrue(ds.WriteThrottlingEnabled); var dr = ds.DataRegionConfigurations.Single(); Assert.AreEqual(1, dr.EmptyPagesPoolSize); Assert.AreEqual(2, dr.EvictionThreshold); Assert.AreEqual(3, dr.InitialSize); Assert.AreEqual(4, dr.MaxSize); Assert.AreEqual("reg2", dr.Name); Assert.AreEqual(Core.Configuration.DataPageEvictionMode.RandomLru, dr.PageEvictionMode); Assert.AreEqual(TimeSpan.FromSeconds(1), dr.MetricsRateTimeInterval); Assert.AreEqual(5, dr.MetricsSubIntervalCount); Assert.AreEqual("swap", dr.SwapPath); Assert.IsTrue(dr.MetricsEnabled); Assert.AreEqual(7, dr.CheckpointPageBufferSize); dr = ds.DefaultDataRegionConfiguration; Assert.AreEqual(2, dr.EmptyPagesPoolSize); Assert.AreEqual(3, dr.EvictionThreshold); Assert.AreEqual(4, dr.InitialSize); Assert.AreEqual(5, dr.MaxSize); Assert.AreEqual("reg1", dr.Name); Assert.AreEqual(Core.Configuration.DataPageEvictionMode.Disabled, dr.PageEvictionMode); Assert.AreEqual(TimeSpan.FromSeconds(3), dr.MetricsRateTimeInterval); Assert.AreEqual(6, dr.MetricsSubIntervalCount); Assert.AreEqual("swap2", dr.SwapPath); Assert.IsFalse(dr.MetricsEnabled); Assert.IsInstanceOf<SslContextFactory>(cfg.SslContextFactory); Assert.IsInstanceOf<StopNodeOrHaltFailureHandler>(cfg.FailureHandler); var failureHandler = (StopNodeOrHaltFailureHandler)cfg.FailureHandler; Assert.IsTrue(failureHandler.TryStop); Assert.AreEqual(TimeSpan.Parse("0:1:0"), failureHandler.Timeout); } /// <summary> /// Tests the serialize deserialize. /// </summary> [Test] public void TestSerializeDeserialize() { // Test custom CheckSerializeDeserialize(GetTestConfig()); // Test custom with different culture to make sure numbers are serialized properly RunWithCustomCulture(() => CheckSerializeDeserialize(GetTestConfig())); // Test default CheckSerializeDeserialize(new IgniteConfiguration()); } /// <summary> /// Tests that all properties are present in the schema. /// </summary> [Test] public void TestAllPropertiesArePresentInSchema() { CheckAllPropertiesArePresentInSchema("IgniteConfigurationSection.xsd", "igniteConfiguration", typeof(IgniteConfiguration)); } /// <summary> /// Checks that all properties are present in schema. /// </summary> [SuppressMessage("ReSharper", "PossibleNullReferenceException")] public static void CheckAllPropertiesArePresentInSchema(string xsd, string sectionName, Type type) { var schema = XDocument.Load(xsd) .Root.Elements() .Single(x => x.Attribute("name").Value == sectionName); CheckPropertyIsPresentInSchema(type, schema); } /// <summary> /// Checks the property is present in schema. /// </summary> // ReSharper disable once UnusedParameter.Local // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local private static void CheckPropertyIsPresentInSchema(Type type, XElement schema) { Func<string, string> toLowerCamel = x => char.ToLowerInvariant(x[0]) + x.Substring(1); foreach (var prop in type.GetProperties()) { if (!prop.CanWrite) continue; // Read-only properties are not configured in XML. if (prop.GetCustomAttributes(typeof(ObsoleteAttribute), true).Any()) continue; // Skip deprecated. var propType = prop.PropertyType; var isCollection = propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(ICollection<>); if (isCollection) propType = propType.GetGenericArguments().First(); var propName = toLowerCamel(prop.Name); Assert.IsTrue(schema.Descendants().Select(x => x.Attribute("name")) .Any(x => x != null && x.Value == propName), "Property is missing in XML schema: " + propName); var isComplexProp = propType.Namespace != null && propType.Namespace.StartsWith("Apache.Ignite.Core"); if (isComplexProp) CheckPropertyIsPresentInSchema(propType, schema); } } /// <summary> /// Tests the schema validation. /// </summary> [Test] public void TestSchemaValidation() { CheckSchemaValidation(); RunWithCustomCulture(CheckSchemaValidation); // Check invalid xml const string invalidXml = @"<igniteConfiguration xmlns='http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection'> <binaryConfiguration /><binaryConfiguration /> </igniteConfiguration>"; Assert.Throws<XmlSchemaValidationException>(() => CheckSchemaValidation(invalidXml)); } /// <summary> /// Tests the XML conversion. /// </summary> [Test] public void TestToXml() { // Empty config Assert.AreEqual("<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n<igniteConfiguration " + "xmlns=\"http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection\" />", new IgniteConfiguration().ToXml()); // Some properties var cfg = new IgniteConfiguration { IgniteInstanceName = "myGrid", ClientMode = true, CacheConfiguration = new[] { new CacheConfiguration("myCache") { CacheMode = CacheMode.Replicated, QueryEntities = new[] { new QueryEntity(typeof(int)), new QueryEntity(typeof(int), typeof(string)) } } }, IncludedEventTypes = new[] { EventType.CacheEntryCreated, EventType.CacheNodesLeft } }; Assert.AreEqual(FixLineEndings(@"<?xml version=""1.0"" encoding=""utf-16""?> <igniteConfiguration clientMode=""true"" igniteInstanceName=""myGrid"" xmlns=""http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection""> <cacheConfiguration> <cacheConfiguration cacheMode=""Replicated"" name=""myCache""> <queryEntities> <queryEntity valueType=""System.Int32"" valueTypeName=""java.lang.Integer"" /> <queryEntity keyType=""System.Int32"" keyTypeName=""java.lang.Integer"" valueType=""System.String"" valueTypeName=""java.lang.String"" /> </queryEntities> </cacheConfiguration> </cacheConfiguration> <includedEventTypes> <int>CacheEntryCreated</int> <int>CacheNodesLeft</int> </includedEventTypes> </igniteConfiguration>"), cfg.ToXml()); // Custom section name and indent var sb = new StringBuilder(); var settings = new XmlWriterSettings { Indent = true, IndentChars = " " }; using (var xmlWriter = XmlWriter.Create(sb, settings)) { cfg.ToXml(xmlWriter, "igCfg"); } Assert.AreEqual(FixLineEndings(@"<?xml version=""1.0"" encoding=""utf-16""?> <igCfg clientMode=""true"" igniteInstanceName=""myGrid"" xmlns=""http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection""> <cacheConfiguration> <cacheConfiguration cacheMode=""Replicated"" name=""myCache""> <queryEntities> <queryEntity valueType=""System.Int32"" valueTypeName=""java.lang.Integer"" /> <queryEntity keyType=""System.Int32"" keyTypeName=""java.lang.Integer"" valueType=""System.String"" valueTypeName=""java.lang.String"" /> </queryEntities> </cacheConfiguration> </cacheConfiguration> <includedEventTypes> <int>CacheEntryCreated</int> <int>CacheNodesLeft</int> </includedEventTypes> </igCfg>"), sb.ToString()); } /// <summary> /// Tests the deserialization. /// </summary> [Test] public void TestFromXml() { // Empty section. var cfg = IgniteConfiguration.FromXml("<x />"); AssertExtensions.ReflectionEqual(new IgniteConfiguration(), cfg); // Empty section with XML header. cfg = IgniteConfiguration.FromXml("<?xml version=\"1.0\" encoding=\"utf-16\"?><x />"); AssertExtensions.ReflectionEqual(new IgniteConfiguration(), cfg); // Simple test. cfg = IgniteConfiguration.FromXml(@"<igCfg igniteInstanceName=""myGrid"" clientMode=""true"" />"); AssertExtensions.ReflectionEqual(new IgniteConfiguration {IgniteInstanceName = "myGrid", ClientMode = true}, cfg); // Invalid xml. var ex = Assert.Throws<ConfigurationErrorsException>(() => IgniteConfiguration.FromXml(@"<igCfg foo=""bar"" />")); Assert.AreEqual("Invalid IgniteConfiguration attribute 'foo=bar', there is no such property " + "on 'Apache.Ignite.Core.IgniteConfiguration'", ex.Message); // Xml reader. using (var xmlReader = XmlReader.Create( new StringReader(@"<igCfg igniteInstanceName=""myGrid"" clientMode=""true"" />"))) { cfg = IgniteConfiguration.FromXml(xmlReader); } AssertExtensions.ReflectionEqual(new IgniteConfiguration { IgniteInstanceName = "myGrid", ClientMode = true }, cfg); } /// <summary> /// Ensures windows-style \r\n line endings in a string literal. /// Git settings may cause string literals in both styles. /// </summary> private static string FixLineEndings(string s) { return s.Split('\n').Select(x => x.TrimEnd('\r')) .Aggregate((acc, x) => string.Format("{0}\r\n{1}", acc, x)); } /// <summary> /// Checks the schema validation. /// </summary> private static void CheckSchemaValidation() { CheckSchemaValidation(GetTestConfig().ToXml()); } /// <summary> /// Checks the schema validation. /// </summary> private static void CheckSchemaValidation(string xml) { var xmlns = "http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection"; var schemaFile = "IgniteConfigurationSection.xsd"; CheckSchemaValidation(xml, xmlns, schemaFile); } /// <summary> /// Checks the schema validation. /// </summary> public static void CheckSchemaValidation(string xml, string xmlns, string schemaFile) { var document = new XmlDocument(); document.Schemas.Add(xmlns, XmlReader.Create(schemaFile)); document.Load(new StringReader(xml)); document.Validate(null); } /// <summary> /// Checks the serialize deserialize. /// </summary> /// <param name="cfg">The config.</param> private static void CheckSerializeDeserialize(IgniteConfiguration cfg) { var resCfg = SerializeDeserialize(cfg); AssertExtensions.ReflectionEqual(cfg, resCfg); } /// <summary> /// Serializes and deserializes a config. /// </summary> private static IgniteConfiguration SerializeDeserialize(IgniteConfiguration cfg) { var xml = cfg.ToXml(); return IgniteConfiguration.FromXml(xml); } /// <summary> /// Gets the test configuration. /// </summary> private static IgniteConfiguration GetTestConfig() { return new IgniteConfiguration { IgniteInstanceName = "gridName", JvmOptions = new[] {"1", "2"}, Localhost = "localhost11", JvmClasspath = "classpath", Assemblies = new[] {"asm1", "asm2", "asm3"}, BinaryConfiguration = new BinaryConfiguration { TypeConfigurations = new[] { new BinaryTypeConfiguration { IsEnum = true, KeepDeserialized = true, AffinityKeyFieldName = "affKeyFieldName", TypeName = "typeName", IdMapper = new IdMapper(), NameMapper = new NameMapper(), Serializer = new TestSerializer() }, new BinaryTypeConfiguration { IsEnum = false, KeepDeserialized = false, AffinityKeyFieldName = "affKeyFieldName", TypeName = "typeName2", Serializer = new BinaryReflectiveSerializer() } }, Types = new[] {typeof(string).FullName}, IdMapper = new IdMapper(), KeepDeserialized = true, NameMapper = new NameMapper(), Serializer = new TestSerializer() }, CacheConfiguration = new[] { new CacheConfiguration("cacheName") { AtomicityMode = CacheAtomicityMode.Transactional, Backups = 15, CacheMode = CacheMode.Replicated, CacheStoreFactory = new TestCacheStoreFactory(), CopyOnRead = false, EagerTtl = false, Invalidate = true, KeepBinaryInStore = true, LoadPreviousValue = true, LockTimeout = TimeSpan.FromSeconds(56), MaxConcurrentAsyncOperations = 24, QueryEntities = new[] { new QueryEntity { Fields = new[] { new QueryField("field", typeof(int)) { IsKeyField = true, NotNull = true, DefaultValue = "foo" } }, Indexes = new[] { new QueryIndex("field") { IndexType = QueryIndexType.FullText, InlineSize = 32 } }, Aliases = new[] { new QueryAlias("field.field", "fld") }, KeyType = typeof(string), ValueType = typeof(long), TableName = "table-1", KeyFieldName = "k", ValueFieldName = "v" }, }, ReadFromBackup = false, RebalanceBatchSize = 33, RebalanceDelay = TimeSpan.MaxValue, RebalanceMode = CacheRebalanceMode.Sync, RebalanceThrottle = TimeSpan.FromHours(44), RebalanceTimeout = TimeSpan.FromMinutes(8), SqlEscapeAll = true, WriteBehindBatchSize = 45, WriteBehindEnabled = true, WriteBehindFlushFrequency = TimeSpan.FromSeconds(55), WriteBehindFlushSize = 66, WriteBehindFlushThreadCount = 2, WriteBehindCoalescing = false, WriteSynchronizationMode = CacheWriteSynchronizationMode.FullAsync, NearConfiguration = new NearCacheConfiguration { NearStartSize = 5, EvictionPolicy = new FifoEvictionPolicy { BatchSize = 19, MaxMemorySize = 1024, MaxSize = 555 } }, EvictionPolicy = new LruEvictionPolicy { BatchSize = 18, MaxMemorySize = 1023, MaxSize = 554 }, AffinityFunction = new RendezvousAffinityFunction { ExcludeNeighbors = true, Partitions = 48 }, ExpiryPolicyFactory = new MyPolicyFactory(), EnableStatistics = true, PluginConfigurations = new[] { new MyPluginConfiguration() }, MemoryPolicyName = "somePolicy", PartitionLossPolicy = PartitionLossPolicy.ReadOnlyAll, GroupName = "abc", SqlIndexMaxInlineSize = 24, KeyConfiguration = new[] { new CacheKeyConfiguration { AffinityKeyFieldName = "abc", TypeName = "def" }, }, OnheapCacheEnabled = true, StoreConcurrentLoadAllThreshold = 7, RebalanceOrder = 3, RebalanceBatchesPrefetchCount = 4, MaxQueryIteratorsCount = 512, QueryDetailMetricsSize = 100, QueryParallelism = 16, SqlSchema = "foo" } }, ClientMode = true, DiscoverySpi = new TcpDiscoverySpi { NetworkTimeout = TimeSpan.FromSeconds(1), SocketTimeout = TimeSpan.FromSeconds(2), AckTimeout = TimeSpan.FromSeconds(3), JoinTimeout = TimeSpan.FromSeconds(4), MaxAckTimeout = TimeSpan.FromSeconds(5), IpFinder = new TcpDiscoveryMulticastIpFinder { TimeToLive = 110, MulticastGroup = "multicastGroup", AddressRequestAttempts = 10, MulticastPort = 987, ResponseTimeout = TimeSpan.FromDays(1), LocalAddress = "127.0.0.2", Endpoints = new[] {"", "abc"} }, ClientReconnectDisabled = true, ForceServerMode = true, IpFinderCleanFrequency = TimeSpan.FromMinutes(7), LocalAddress = "127.0.0.1", LocalPort = 49900, LocalPortRange = 13, ReconnectCount = 11, StatisticsPrintFrequency = TimeSpan.FromSeconds(20), ThreadPriority = 6, TopologyHistorySize = 1234567 }, IgniteHome = "igniteHome", IncludedEventTypes = EventType.CacheQueryAll, JvmDllPath = @"c:\jvm", JvmInitialMemoryMb = 1024, JvmMaxMemoryMb = 2048, LifecycleHandlers = new[] {new LifecycleBean(), new LifecycleBean()}, MetricsExpireTime = TimeSpan.FromSeconds(15), MetricsHistorySize = 45, MetricsLogFrequency = TimeSpan.FromDays(2), MetricsUpdateFrequency = TimeSpan.MinValue, NetworkSendRetryCount = 7, NetworkSendRetryDelay = TimeSpan.FromSeconds(98), NetworkTimeout = TimeSpan.FromMinutes(4), SuppressWarnings = true, WorkDirectory = @"c:\work", IsDaemon = true, UserAttributes = Enumerable.Range(1, 10).ToDictionary(x => x.ToString(), x => x % 2 == 0 ? (object) x : new FooClass {Bar = x.ToString()}), AtomicConfiguration = new AtomicConfiguration { CacheMode = CacheMode.Replicated, AtomicSequenceReserveSize = 200, Backups = 2 }, TransactionConfiguration = new TransactionConfiguration { PessimisticTransactionLogSize = 23, DefaultTransactionIsolation = TransactionIsolation.ReadCommitted, DefaultTimeout = TimeSpan.FromDays(2), DefaultTransactionConcurrency = TransactionConcurrency.Optimistic, PessimisticTransactionLogLinger = TimeSpan.FromHours(3) }, CommunicationSpi = new TcpCommunicationSpi { LocalPort = 47501, MaxConnectTimeout = TimeSpan.FromSeconds(34), MessageQueueLimit = 15, ConnectTimeout = TimeSpan.FromSeconds(17), IdleConnectionTimeout = TimeSpan.FromSeconds(19), SelectorsCount = 8, ReconnectCount = 33, SocketReceiveBufferSize = 512, AckSendThreshold = 99, DirectBuffer = false, DirectSendBuffer = true, LocalPortRange = 45, LocalAddress = "127.0.0.1", TcpNoDelay = false, SlowClientQueueLimit = 98, SocketSendBufferSize = 2045, UnacknowledgedMessagesBufferSize = 3450 }, SpringConfigUrl = "test", Logger = new IgniteNLogLogger(), FailureDetectionTimeout = TimeSpan.FromMinutes(2), ClientFailureDetectionTimeout = TimeSpan.FromMinutes(3), LongQueryWarningTimeout = TimeSpan.FromDays(4), PluginConfigurations = new[] {new TestIgnitePluginConfiguration()}, EventStorageSpi = new MemoryEventStorageSpi { ExpirationTimeout = TimeSpan.FromMilliseconds(12345), MaxEventCount = 257 }, MemoryConfiguration = new MemoryConfiguration { ConcurrencyLevel = 3, DefaultMemoryPolicyName = "somePolicy", PageSize = 4, SystemCacheInitialSize = 5, SystemCacheMaxSize = 6, MemoryPolicies = new[] { new MemoryPolicyConfiguration { Name = "myDefaultPlc", PageEvictionMode = DataPageEvictionMode.Random2Lru, InitialSize = 245 * 1024 * 1024, MaxSize = 345 * 1024 * 1024, EvictionThreshold = 0.88, EmptyPagesPoolSize = 77, SwapFilePath = "myPath1", RateTimeInterval = TimeSpan.FromSeconds(22), SubIntervals = 99 }, new MemoryPolicyConfiguration { Name = "customPlc", PageEvictionMode = DataPageEvictionMode.RandomLru, EvictionThreshold = 0.77, EmptyPagesPoolSize = 66, SwapFilePath = "somePath2", MetricsEnabled = true } } }, PeerAssemblyLoadingMode = PeerAssemblyLoadingMode.CurrentAppDomain, ClientConnectorConfiguration = new ClientConnectorConfiguration { Host = "foo", Port = 2, PortRange = 3, MaxOpenCursorsPerConnection = 4, SocketReceiveBufferSize = 5, SocketSendBufferSize = 6, TcpNoDelay = false, ThinClientEnabled = false, OdbcEnabled = false, JdbcEnabled = false, ThreadPoolSize = 7, IdleTimeout = TimeSpan.FromMinutes(5) }, PersistentStoreConfiguration = new PersistentStoreConfiguration { AlwaysWriteFullPages = true, CheckpointingFrequency = TimeSpan.FromSeconds(25), CheckpointingPageBufferSize = 28 * 1024 * 1024, CheckpointingThreads = 2, LockWaitTime = TimeSpan.FromSeconds(5), PersistentStorePath = Path.GetTempPath(), TlbSize = 64 * 1024, WalArchivePath = Path.GetTempPath(), WalFlushFrequency = TimeSpan.FromSeconds(3), WalFsyncDelayNanos = 3, WalHistorySize = 10, WalMode = WalMode.Background, WalRecordIteratorBufferSize = 32 * 1024 * 1024, WalSegments = 6, WalSegmentSize = 5 * 1024 * 1024, WalStorePath = Path.GetTempPath(), SubIntervals = 25, MetricsEnabled = true, RateTimeInterval = TimeSpan.FromDays(1), CheckpointWriteOrder = CheckpointWriteOrder.Random, WriteThrottlingEnabled = true }, IsActiveOnStart = false, ConsistentId = "myId123", LocalEventListeners = new[] { new LocalEventListener<IEvent> { EventTypes = new[] {1, 2}, Listener = new MyEventListener() } }, DataStorageConfiguration = new DataStorageConfiguration { AlwaysWriteFullPages = true, CheckpointFrequency = TimeSpan.FromSeconds(25), CheckpointThreads = 2, LockWaitTime = TimeSpan.FromSeconds(5), StoragePath = Path.GetTempPath(), WalThreadLocalBufferSize = 64 * 1024, WalArchivePath = Path.GetTempPath(), WalFlushFrequency = TimeSpan.FromSeconds(3), WalFsyncDelayNanos = 3, WalHistorySize = 10, WalMode = Core.Configuration.WalMode.None, WalRecordIteratorBufferSize = 32 * 1024 * 1024, WalSegments = 6, WalSegmentSize = 5 * 1024 * 1024, WalPath = Path.GetTempPath(), MetricsEnabled = true, MetricsSubIntervalCount = 7, MetricsRateTimeInterval = TimeSpan.FromSeconds(9), CheckpointWriteOrder = Core.Configuration.CheckpointWriteOrder.Sequential, WriteThrottlingEnabled = true, SystemRegionInitialSize = 64 * 1024 * 1024, SystemRegionMaxSize = 128 * 1024 * 1024, ConcurrencyLevel = 1, PageSize = 5 * 1024, WalAutoArchiveAfterInactivity = TimeSpan.FromSeconds(19), DefaultDataRegionConfiguration = new DataRegionConfiguration { Name = "reg1", EmptyPagesPoolSize = 50, EvictionThreshold = 0.8, InitialSize = 100 * 1024 * 1024, MaxSize = 150 * 1024 * 1024, MetricsEnabled = true, PageEvictionMode = Core.Configuration.DataPageEvictionMode.RandomLru, PersistenceEnabled = false, MetricsRateTimeInterval = TimeSpan.FromMinutes(2), MetricsSubIntervalCount = 6, SwapPath = Path.GetTempPath(), CheckpointPageBufferSize = 7 }, DataRegionConfigurations = new[] { new DataRegionConfiguration { Name = "reg2", EmptyPagesPoolSize = 51, EvictionThreshold = 0.7, InitialSize = 101 * 1024 * 1024, MaxSize = 151 * 1024 * 1024, MetricsEnabled = false, PageEvictionMode = Core.Configuration.DataPageEvictionMode.RandomLru, PersistenceEnabled = false, MetricsRateTimeInterval = TimeSpan.FromMinutes(3), MetricsSubIntervalCount = 7, SwapPath = Path.GetTempPath() } } }, SslContextFactory = new SslContextFactory(), FailureHandler = new StopNodeOrHaltFailureHandler { TryStop = false, Timeout = TimeSpan.FromSeconds(10) }, SqlQueryHistorySize = 345 }; } /// <summary> /// Runs the with custom culture. /// </summary> /// <param name="action">The action.</param> private static void RunWithCustomCulture(Action action) { RunWithCulture(action, CultureInfo.InvariantCulture); RunWithCulture(action, CultureInfo.GetCultureInfo("ru-RU")); } /// <summary> /// Runs the with culture. /// </summary> /// <param name="action">The action.</param> /// <param name="cultureInfo">The culture information.</param> private static void RunWithCulture(Action action, CultureInfo cultureInfo) { var oldCulture = Thread.CurrentThread.CurrentCulture; try { Thread.CurrentThread.CurrentCulture = cultureInfo; action(); } finally { Thread.CurrentThread.CurrentCulture = oldCulture; } } /// <summary> /// Test bean. /// </summary> public class LifecycleBean : ILifecycleHandler { /// <summary> /// Gets or sets the foo. /// </summary> /// <value> /// The foo. /// </value> public int Foo { get; set; } /// <summary> /// This method is called when lifecycle event occurs. /// </summary> /// <param name="evt">Lifecycle event.</param> public void OnLifecycleEvent(LifecycleEventType evt) { // No-op. } } /// <summary> /// Test mapper. /// </summary> public class NameMapper : IBinaryNameMapper { /// <summary> /// Gets or sets the bar. /// </summary> /// <value> /// The bar. /// </value> public string Bar { get; set; } /// <summary> /// Gets the type name. /// </summary> /// <param name="name">The name.</param> /// <returns> /// Type name. /// </returns> public string GetTypeName(string name) { return name; } /// <summary> /// Gets the field name. /// </summary> /// <param name="name">The name.</param> /// <returns> /// Field name. /// </returns> public string GetFieldName(string name) { return name; } } /// <summary> /// Serializer. /// </summary> public class TestSerializer : IBinarySerializer { /** <inheritdoc /> */ public void WriteBinary(object obj, IBinaryWriter writer) { // No-op. } /** <inheritdoc /> */ public void ReadBinary(object obj, IBinaryReader reader) { // No-op. } } /// <summary> /// Test class. /// </summary> public class FooClass { public string Bar { get; set; } 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 string.Equals(Bar, ((FooClass) obj).Bar); } public override int GetHashCode() { return Bar != null ? Bar.GetHashCode() : 0; } public static bool operator ==(FooClass left, FooClass right) { return Equals(left, right); } public static bool operator !=(FooClass left, FooClass right) { return !Equals(left, right); } } /// <summary> /// Test factory. /// </summary> public class TestCacheStoreFactory : IFactory<ICacheStore> { /// <summary> /// Creates an instance of the cache store. /// </summary> /// <returns> /// New instance of the cache store. /// </returns> public ICacheStore CreateInstance() { return null; } } /// <summary> /// Test logger. /// </summary> public class TestLogger : ILogger { /** <inheritdoc /> */ public void Log(LogLevel level, string message, object[] args, IFormatProvider formatProvider, string category, string nativeErrorInfo, Exception ex) { throw new NotImplementedException(); } /** <inheritdoc /> */ public bool IsEnabled(LogLevel level) { throw new NotImplementedException(); } } /// <summary> /// Test factory. /// </summary> public class MyPolicyFactory : IFactory<IExpiryPolicy> { /** <inheritdoc /> */ public IExpiryPolicy CreateInstance() { throw new NotImplementedException(); } } public class MyPluginConfiguration : ICachePluginConfiguration { int? ICachePluginConfiguration.CachePluginConfigurationClosureFactoryId { get { return 0; } } void ICachePluginConfiguration.WriteBinary(IBinaryRawWriter writer) { throw new NotImplementedException(); } } public class MyEventListener : IEventListener<IEvent> { public bool Invoke(IEvent evt) { throw new NotImplementedException(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using BTDB.IL; using BTDB.StreamLayer; using System.Diagnostics; using System.Text; using Microsoft.Extensions.Primitives; namespace BTDB.FieldHandler; public class EnumFieldHandler : IFieldHandler { readonly byte[] _configuration; readonly bool _signed; Type? _enumType; public class EnumConfiguration { readonly bool _signed; readonly bool _flags; readonly string[] _names; readonly ulong[] _values; public EnumConfiguration(Type enumType) { _signed = IsSignedEnum(enumType); _flags = IsFlagsEnum(enumType); _names = enumType.GetEnumNames(); var members = enumType.GetMembers(BindingFlags.Static | BindingFlags.Public); Debug.Assert(members.Length == _names.Length); for (int i = 0; i < members.Length; i++) { var a = members[i].GetCustomAttributes<PersistedNameAttribute>().FirstOrDefault(); if (a != null) _names[i] = a.Name; } var undertype = enumType.GetEnumUnderlyingType(); var enumValues = enumType.GetEnumValues(); IEnumerable<ulong> enumValuesUlongs; if (undertype == typeof(int)) enumValuesUlongs = enumValues.Cast<int>().Select(i => (ulong)i); else if (undertype == typeof(uint)) enumValuesUlongs = enumValues.Cast<uint>().Select(i => (ulong)i); else if (undertype == typeof(sbyte)) enumValuesUlongs = enumValues.Cast<sbyte>().Select(i => (ulong)i); else if (undertype == typeof(byte)) enumValuesUlongs = enumValues.Cast<byte>().Select(i => (ulong)i); else if (undertype == typeof(short)) enumValuesUlongs = enumValues.Cast<short>().Select(i => (ulong)i); else if (undertype == typeof(ushort)) enumValuesUlongs = enumValues.Cast<ushort>().Select(i => (ulong)i); else if (undertype == typeof(long)) enumValuesUlongs = enumValues.Cast<long>().Select(i => (ulong)i); else enumValuesUlongs = enumValues.Cast<ulong>(); _values = enumValuesUlongs.ToArray(); } public EnumConfiguration(byte[] configuration) { var reader = new SpanReader(configuration); var header = reader.ReadVUInt32(); _signed = (header & 1) != 0; _flags = (header & 2) != 0; var count = header >> 2; _names = new string[count]; _values = new ulong[count]; for (var i = 0; i < count; i++) Names[i] = reader.ReadString()!; if (_signed) { for (var i = 0; i < count; i++) Values[i] = (ulong)reader.ReadVInt64(); } else { for (var i = 0; i < count; i++) Values[i] = reader.ReadVUInt64(); } } public bool Signed => _signed; public bool Flags => _flags; public string[] Names => _names; public ulong[] Values => _values; public byte[] ToConfiguration() { var writer = new SpanWriter(); writer.WriteVUInt32((_signed ? 1u : 0) + (Flags ? 2u : 0) + 4u * (uint)Names.Length); foreach (var name in Names) { writer.WriteString(name); } foreach (var value in Values) { if (_signed) writer.WriteVInt64((long)value); else writer.WriteVUInt64(value); } return writer.GetSpan().ToArray(); } public Type ToType() { var builder = ILBuilder.Instance; var literals = new Dictionary<string, object>(); for (var i = 0; i < Names.Length; i++) { if (_signed) { literals.Add(Names[i], (long)Values[i]); } else { literals.Add(Names[i], Values[i]); } } return builder.NewEnum("EnumByFieldHandler", _signed ? typeof(long) : typeof(ulong), literals); } public static bool operator ==(EnumConfiguration? left, EnumConfiguration? right) { if (ReferenceEquals(left, right)) return true; if (ReferenceEquals(left, null)) return false; return left.Equals(right); } public static bool operator !=(EnumConfiguration? left, EnumConfiguration? right) { return !(left == right); } public bool Equals(EnumConfiguration? other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return other._flags.Equals(_flags) && _names.SequenceEqual(other._names) && _values.SequenceEqual(other._values); } public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof(EnumConfiguration)) return false; return Equals((EnumConfiguration)obj); } public override int GetHashCode() { unchecked { var result = _flags.GetHashCode(); result = (result * 397) ^ _names.GetHashCode(); result = (result * 397) ^ _values.GetHashCode(); return result; } } public bool IsSubsetOf(EnumConfiguration targetCfg) { if (_flags != targetCfg._flags) return false; var targetDict = targetCfg.Names.Zip(targetCfg.Values, (k, v) => new KeyValuePair<string, ulong>(k, v)) .ToDictionary(p => p.Key, p => p.Value); for (var i = 0; i < _names.Length; i++) { if (!targetDict.TryGetValue(_names[i], out var targetValue)) return false; if (_values[i] != targetValue) return false; } return true; } public bool IsBinaryRepresentationSubsetOf(EnumConfiguration targetCfg) { var targetSet = targetCfg.Values.ToHashSet(); return _values.All(v => targetSet.Contains(v)); } } public EnumFieldHandler(Type enumType) { if (!IsCompatibleWith(enumType)) throw new ArgumentException("enumType"); _enumType = enumType; var ec = new EnumConfiguration(enumType); _signed = ec.Signed; _configuration = ec.ToConfiguration(); } public EnumFieldHandler(byte[] configuration) { _configuration = configuration; var ec = new EnumConfiguration(configuration); _signed = ec.Signed; } static bool IsSignedEnum(Type enumType) { return SignedFieldHandler.IsCompatibleWith(enumType.GetEnumUnderlyingType()); } static bool IsFlagsEnum(Type type) { return type.GetCustomAttributes(typeof(FlagsAttribute), false).Length != 0; } public static string HandlerName => "Enum"; public string Name => HandlerName; public byte[] Configuration => _configuration; public static bool IsCompatibleWith(Type type) { if (!type.IsEnum) return false; var enumUnderlyingType = type.GetEnumUnderlyingType(); return SignedFieldHandler.IsCompatibleWith(enumUnderlyingType) || UnsignedFieldHandler.IsCompatibleWith(enumUnderlyingType); } public Type HandledType() { return _enumType ??= new EnumConfiguration(_configuration).ToType(); } public bool NeedsCtx() { return false; } public void Load(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen>? pushCtx) { pushReader(ilGenerator); Type typeRead; if (_signed) { ilGenerator.Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadVInt64))!); typeRead = typeof(long); } else { ilGenerator.Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadVUInt64))!); typeRead = typeof(ulong); } DefaultTypeConvertorGenerator.Instance.GenerateConversion(typeRead, _enumType!.GetEnumUnderlyingType())!(ilGenerator); } public void Skip(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen>? pushCtx) { pushReader(ilGenerator); if (_signed) { ilGenerator.Call(typeof(SpanReader).GetMethod(nameof(SpanReader.SkipVInt64))!); } else { ilGenerator.Call(typeof(SpanReader).GetMethod(nameof(SpanReader.SkipVUInt64))!); } } public void Save(IILGen ilGenerator, Action<IILGen> pushWriter, Action<IILGen>? pushCtx, Action<IILGen> pushValue) { pushWriter(ilGenerator); pushValue(ilGenerator); if (_signed) { ilGenerator .ConvI8() .Call(typeof(SpanWriter).GetMethod(nameof(SpanWriter.WriteVInt64))!); } else { ilGenerator .ConvU8() .Call(typeof(SpanWriter).GetMethod(nameof(SpanWriter.WriteVUInt64))!); } } public IFieldHandler SpecializeLoadForType(Type type, IFieldHandler? typeHandler, IFieldHandlerLogger? logger) { if (typeHandler == this) return this; var enumTypeHandler = typeHandler as EnumFieldHandler; if (typeHandler == null && type.IsEnum) { enumTypeHandler = new EnumFieldHandler(type); typeHandler = enumTypeHandler; } if (enumTypeHandler != null && _signed == enumTypeHandler._signed) { if (new EnumConfiguration(Configuration).IsBinaryRepresentationSubsetOf(new EnumConfiguration(enumTypeHandler.Configuration))) return typeHandler; } logger?.ReportTypeIncompatibility(_enumType, this, type, typeHandler); return this; } public IFieldHandler SpecializeSaveForType(Type type) { return SpecializeLoadForType(type, null, null); } public bool IsCompatibleWith(Type type, FieldHandlerOptions options) { return IsCompatibleWith(type); } public NeedsFreeContent FreeContent(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen>? pushCtx) { Skip(ilGenerator, pushReader, pushCtx); return NeedsFreeContent.No; } public override string ToString() { var ec = new EnumConfiguration(Configuration); var sb = new StringBuilder(); sb.Append("Enum"); if (_enumType != null) { sb.Append(' '); sb.Append(_enumType.ToSimpleName()); } if (ec.Flags) sb.Append("[Flags]"); if (!ec.Signed) sb.Append("[Unsigned]"); sb.Append('{'); for (var i = 0; i < ec.Names.Length; i++) { if (i > 0) sb.Append(','); sb.Append(ec.Names[i]); sb.Append('='); sb.Append(ec.Values[i]); } sb.Append('}'); return sb.ToString(); } }
using System; using System.Collections.Generic; using ModestTree; namespace Zenject { public abstract class StaticMemoryPoolBase<TValue> : IDespawnableMemoryPool<TValue>, IDisposable where TValue : class, new() { readonly Stack<TValue> _stack = new Stack<TValue>(); Action<TValue> _onDespawnedMethod; int _activeCount; public StaticMemoryPoolBase(Action<TValue> onDespawnedMethod) { _onDespawnedMethod = onDespawnedMethod; StaticMemoryPoolRegistry.Add(this); } public Action<TValue> OnDespawnedMethod { set { _onDespawnedMethod = value; } } public int NumTotal { get { return NumInactive + NumActive; } } public int NumActive { get { return _activeCount; } } public int NumInactive { get { return _stack.Count; } } public Type ItemType { get { return typeof(TValue); } } public void Resize(int desiredPoolSize) { Assert.That(desiredPoolSize >= 0, "Attempted to resize the pool to a negative amount"); while (_stack.Count > desiredPoolSize) { _stack.Pop(); } while (desiredPoolSize > _stack.Count) { _stack.Push(Alloc()); } Assert.IsEqual(_stack.Count, desiredPoolSize); } public void Dispose() { StaticMemoryPoolRegistry.Remove(this); } public void ClearActiveCount() { _activeCount = 0; } public void Clear() { Resize(0); } public void ShrinkBy(int numToRemove) { Resize(_stack.Count - numToRemove); } public void ExpandBy(int numToAdd) { Resize(_stack.Count + numToAdd); } TValue Alloc() { return new TValue(); } protected TValue SpawnInternal() { TValue element; if (_stack.Count == 0) { element = Alloc(); } else { element = _stack.Pop(); } _activeCount++; return element; } void IMemoryPool.Despawn(object item) { Despawn((TValue)item); } public void Despawn(TValue element) { if (_onDespawnedMethod != null) { _onDespawnedMethod(element); } if (_stack.Count > 0 && ReferenceEquals(_stack.Peek(), element)) { ModestTree.Log.Error("Despawn error. Trying to destroy object that is already released to pool."); } Assert.That(!_stack.Contains(element), "Attempted to despawn element twice!"); _activeCount--; _stack.Push(element); } } // Zero parameters public class StaticMemoryPool<TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TValue> where TValue : class, new() { Action<TValue> _onSpawnMethod; public StaticMemoryPool( Action<TValue> onSpawnMethod = null, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { _onSpawnMethod = onSpawnMethod; } public Action<TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn() { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(item); } return item; } } // One parameter public class StaticMemoryPool<TParam1, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TValue> where TValue : class, new() { Action<TParam1, TValue> _onSpawnMethod; public StaticMemoryPool( Action<TParam1, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public Action<TParam1, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 param) { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(param, item); } return item; } } // Two parameter public class StaticMemoryPool<TParam1, TParam2, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TValue> where TValue : class, new() { Action<TParam1, TParam2, TValue> _onSpawnMethod; public StaticMemoryPool( Action<TParam1, TParam2, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public Action<TParam1, TParam2, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 p1, TParam2 p2) { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(p1, p2, item); } return item; } } // Three parameters public class StaticMemoryPool<TParam1, TParam2, TParam3, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TValue> where TValue : class, new() { Action<TParam1, TParam2, TParam3, TValue> _onSpawnMethod; public StaticMemoryPool( Action<TParam1, TParam2, TParam3, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public Action<TParam1, TParam2, TParam3, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3) { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(p1, p2, p3, item); } return item; } } // Four parameters public class StaticMemoryPool<TParam1, TParam2, TParam3, TParam4, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TParam4, TValue> where TValue : class, new() { #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TValue> _onSpawnMethod; public StaticMemoryPool( #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4) { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(p1, p2, p3, p4, item); } return item; } } // Five parameters public class StaticMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> where TValue : class, new() { #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> _onSpawnMethod; public StaticMemoryPool( #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5) { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(p1, p2, p3, p4, p5, item); } return item; } } // Six parameters public class StaticMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> where TValue : class, new() { #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> _onSpawnMethod; public StaticMemoryPool( #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6) { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(p1, p2, p3, p4, p5, p6, item); } return item; } } // Seven parameters public class StaticMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> where TValue : class, new() { #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> _onSpawnMethod; public StaticMemoryPool( #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6, TParam7 p7) { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(p1, p2, p3, p4, p5, p6, p7, item); } return item; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using BTCPayServer.Abstractions.Extensions; using BTCPayServer.Client.Models; using BTCPayServer.Data; using BTCPayServer.JsonConverters; using BTCPayServer.Models; using BTCPayServer.Payments; using BTCPayServer.Payments.Bitcoin; using NBitcoin; using NBitcoin.DataEncoders; using NBitpayClient; using NBXplorer; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; namespace BTCPayServer.Services.Invoices { public class InvoiceCryptoInfo : NBitpayClient.InvoiceCryptoInfo { [JsonProperty("paymentUrls")] public new InvoicePaymentUrls PaymentUrls { get; set; } public class InvoicePaymentUrls : NBitpayClient.InvoicePaymentUrls { [JsonExtensionData] public Dictionary<string, JToken> AdditionalData { get; set; } } } public class InvoiceMetadata { public static readonly JsonSerializer MetadataSerializer; static InvoiceMetadata() { var seria = new JsonSerializer(); seria.DefaultValueHandling = DefaultValueHandling.Ignore; seria.FloatParseHandling = FloatParseHandling.Decimal; seria.ContractResolver = new CamelCasePropertyNamesContractResolver(); MetadataSerializer = seria; } [JsonIgnore] public string OrderId { get => GetMetadata<string>("orderId"); set => SetMetadata("orderId", value); } [JsonIgnore] public string OrderUrl { get => GetMetadata<string>("orderUrl"); set => SetMetadata("orderUrl", value); } [JsonIgnore] public string PaymentRequestId { get => GetMetadata<string>("paymentRequestId"); set => SetMetadata("paymentRequestId", value); } [JsonIgnore] public string BuyerName { get => GetMetadata<string>("buyerName"); set => SetMetadata("buyerName", value); } [JsonIgnore] public string BuyerEmail { get => GetMetadata<string>("buyerEmail"); set => SetMetadata("buyerEmail", value); } [JsonIgnore] public string BuyerCountry { get => GetMetadata<string>("buyerCountry"); set => SetMetadata("buyerCountry", value); } [JsonIgnore] public string BuyerZip { get => GetMetadata<string>("buyerZip"); set => SetMetadata("buyerZip", value); } [JsonIgnore] public string BuyerState { get => GetMetadata<string>("buyerState"); set => SetMetadata("buyerState", value); } [JsonIgnore] public string BuyerCity { get => GetMetadata<string>("buyerCity"); set => SetMetadata("buyerCity", value); } [JsonIgnore] public string BuyerAddress2 { get => GetMetadata<string>("buyerAddress2"); set => SetMetadata("buyerAddress2", value); } [JsonIgnore] public string BuyerAddress1 { get => GetMetadata<string>("buyerAddress1"); set => SetMetadata("buyerAddress1", value); } [JsonIgnore] public string BuyerPhone { get => GetMetadata<string>("buyerPhone"); set => SetMetadata("buyerPhone", value); } [JsonIgnore] public string ItemDesc { get => GetMetadata<string>("itemDesc"); set => SetMetadata("itemDesc", value); } [JsonIgnore] public string ItemCode { get => GetMetadata<string>("itemCode"); set => SetMetadata("itemCode", value); } [JsonIgnore] public bool? Physical { get => GetMetadata<bool?>("physical"); set => SetMetadata("physical", value); } [JsonIgnore] public decimal? TaxIncluded { get => GetMetadata<decimal?>("taxIncluded"); set => SetMetadata("taxIncluded", value); } [JsonIgnore] public string PosData { get => GetMetadata<string>("posData"); set => SetMetadata("posData", value); } [JsonExtensionData] public IDictionary<string, JToken> AdditionalData { get; set; } public T GetMetadata<T>(string propName) { if (AdditionalData == null || !(AdditionalData.TryGetValue(propName, out var jt) is true)) return default; if (jt.Type == JTokenType.Null) return default; if (typeof(T) == typeof(string)) { return (T)(object)jt.ToString(); } try { return jt.Value<T>(); } catch (Exception) { return default; } } public void SetMetadata<T>(string propName, T value) { JToken data; if (typeof(T) == typeof(string) && value is string v) { data = new JValue(v); AdditionalData ??= new Dictionary<string, JToken>(); AdditionalData.AddOrReplace(propName, data); return; } if (value is null) { AdditionalData?.Remove(propName); } else { try { if (value is string s) { data = JToken.Parse(s); } else { data = JToken.FromObject(value); } } catch (Exception) { data = JToken.FromObject(value); } AdditionalData ??= new Dictionary<string, JToken>(); AdditionalData.AddOrReplace(propName, data); } } public static InvoiceMetadata FromJObject(JObject jObject) { return jObject.ToObject<InvoiceMetadata>(MetadataSerializer); } public JObject ToJObject() { return JObject.FromObject(this, MetadataSerializer); } } public class InvoiceEntity { class BuyerInformation { [JsonProperty(PropertyName = "buyerName")] public string BuyerName { get; set; } [JsonProperty(PropertyName = "buyerEmail")] public string BuyerEmail { get; set; } [JsonProperty(PropertyName = "buyerCountry")] public string BuyerCountry { get; set; } [JsonProperty(PropertyName = "buyerZip")] public string BuyerZip { get; set; } [JsonProperty(PropertyName = "buyerState")] public string BuyerState { get; set; } [JsonProperty(PropertyName = "buyerCity")] public string BuyerCity { get; set; } [JsonProperty(PropertyName = "buyerAddress2")] public string BuyerAddress2 { get; set; } [JsonProperty(PropertyName = "buyerAddress1")] public string BuyerAddress1 { get; set; } [JsonProperty(PropertyName = "buyerPhone")] public string BuyerPhone { get; set; } } class ProductInformation { [JsonProperty(PropertyName = "itemDesc")] public string ItemDesc { get; set; } [JsonProperty(PropertyName = "itemCode")] public string ItemCode { get; set; } [JsonProperty(PropertyName = "physical")] public bool Physical { get; set; } [JsonProperty(PropertyName = "price")] public decimal Price { get; set; } [JsonProperty(PropertyName = "taxIncluded", DefaultValueHandling = DefaultValueHandling.Ignore)] public decimal TaxIncluded { get; set; } [JsonProperty(PropertyName = "currency")] public string Currency { get; set; } } [JsonIgnore] public BTCPayNetworkProvider Networks { get; set; } public const int InternalTagSupport_Version = 1; public const int GreenfieldInvoices_Version = 2; public const int Lastest_Version = 2; public int Version { get; set; } public string Id { get; set; } public string StoreId { get; set; } public SpeedPolicy SpeedPolicy { get; set; } public string DefaultLanguage { get; set; } [Obsolete("Use GetPaymentMethod(network) instead")] public decimal Rate { get; set; } public DateTimeOffset InvoiceTime { get; set; } public DateTimeOffset ExpirationTime { get; set; } [Obsolete("Use GetPaymentMethod(network).GetPaymentMethodDetails().GetDestinationAddress() instead")] public string DepositAddress { get; set; } public InvoiceMetadata Metadata { get; set; } public decimal Price { get; set; } public string Currency { get; set; } public string DefaultPaymentMethod { get; set; } #nullable enable public PaymentMethodId? GetDefaultPaymentMethod() { PaymentMethodId.TryParse(DefaultPaymentMethod, out var id); return id; } #nullable restore [JsonExtensionData] public IDictionary<string, JToken> AdditionalData { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public HashSet<string> InternalTags { get; set; } = new HashSet<string>(); public string[] GetInternalTags(string prefix) { return InternalTags == null ? Array.Empty<string>() : InternalTags .Where(t => t.StartsWith(prefix, StringComparison.InvariantCulture)) .Select(t => t.Substring(prefix.Length)).ToArray(); } [Obsolete("Use GetDerivationStrategies instead")] public string DerivationStrategy { get; set; } [Obsolete("Use GetPaymentMethodFactories() instead")] public string DerivationStrategies { get; set; } public IEnumerable<T> GetSupportedPaymentMethod<T>(PaymentMethodId paymentMethodId) where T : ISupportedPaymentMethod { return GetSupportedPaymentMethod() .Where(p => paymentMethodId == null || p.PaymentId == paymentMethodId) .OfType<T>(); } public IEnumerable<T> GetSupportedPaymentMethod<T>() where T : ISupportedPaymentMethod { return GetSupportedPaymentMethod<T>(null); } public IEnumerable<ISupportedPaymentMethod> GetSupportedPaymentMethod() { #pragma warning disable CS0618 bool btcReturned = false; if (!string.IsNullOrEmpty(DerivationStrategies)) { JObject strategies = JObject.Parse(DerivationStrategies); foreach (var strat in strategies.Properties()) { if (!PaymentMethodId.TryParse(strat.Name, out var paymentMethodId)) { continue; } var network = Networks.GetNetwork<BTCPayNetworkBase>(paymentMethodId.CryptoCode); if (network != null) { if (network == Networks.BTC && paymentMethodId.PaymentType == PaymentTypes.BTCLike) btcReturned = true; yield return paymentMethodId.PaymentType.DeserializeSupportedPaymentMethod(network, strat.Value); } } } if (!btcReturned && !string.IsNullOrEmpty(DerivationStrategy)) { if (Networks.BTC != null) { yield return BTCPayServer.DerivationSchemeSettings.Parse(DerivationStrategy, Networks.BTC); } } #pragma warning restore CS0618 } internal void SetSupportedPaymentMethods(IEnumerable<ISupportedPaymentMethod> derivationStrategies) { JObject obj = new JObject(); foreach (var strat in derivationStrategies) { obj.Add(strat.PaymentId.ToString(), PaymentMethodExtensions.Serialize(strat)); #pragma warning disable CS0618 // This field should eventually disappear DerivationStrategy = null; } DerivationStrategies = JsonConvert.SerializeObject(obj); #pragma warning restore CS0618 } [JsonIgnore] public InvoiceStatusLegacy Status { get; set; } [JsonProperty(PropertyName = "status")] [Obsolete("Use Status instead")] public string StatusString => InvoiceState.ToString(Status); [JsonIgnore] public InvoiceExceptionStatus ExceptionStatus { get; set; } [JsonProperty(PropertyName = "exceptionStatus")] [Obsolete("Use ExceptionStatus instead")] public string ExceptionStatusString => InvoiceState.ToString(ExceptionStatus); [Obsolete("Use GetPayments instead")] public List<PaymentEntity> Payments { get; set; } #pragma warning disable CS0618 public List<PaymentEntity> GetPayments(bool accountedOnly) { return Payments?.Where(entity => entity.GetPaymentMethodId() != null && (!accountedOnly || entity.Accounted)).ToList() ?? new List<PaymentEntity>(); } public List<PaymentEntity> GetPayments(string cryptoCode, bool accountedOnly) { return GetPayments(accountedOnly).Where(p => p.CryptoCode == cryptoCode).ToList(); } public List<PaymentEntity> GetPayments(BTCPayNetworkBase network, bool accountedOnly) { return GetPayments(network.CryptoCode, accountedOnly); } #pragma warning restore CS0618 public bool Refundable { get; set; } public bool? RequiresRefundEmail { get; set; } = null; public string RefundMail { get; set; } [JsonProperty("redirectURL")] public string RedirectURLTemplate { get; set; } [JsonIgnore] public Uri RedirectURL => FillPlaceholdersUri(RedirectURLTemplate); private Uri FillPlaceholdersUri(string v) { var uriStr = (v ?? string.Empty).Replace("{OrderId}", System.Web.HttpUtility.UrlEncode(Metadata.OrderId) ?? "", StringComparison.OrdinalIgnoreCase) .Replace("{InvoiceId}", System.Web.HttpUtility.UrlEncode(Id) ?? "", StringComparison.OrdinalIgnoreCase); if (Uri.TryCreate(uriStr, UriKind.Absolute, out var uri) && (uri.Scheme == "http" || uri.Scheme == "https")) return uri; return null; } public bool RedirectAutomatically { get; set; } [Obsolete("Use GetPaymentMethod(network).GetTxFee() instead")] public Money TxFee { get; set; } public bool FullNotifications { get; set; } public string NotificationEmail { get; set; } [JsonProperty("notificationURL")] public string NotificationURLTemplate { get; set; } [JsonIgnore] public Uri NotificationURL => FillPlaceholdersUri(NotificationURLTemplate); public string ServerUrl { get; set; } [Obsolete("Use Set/GetPaymentMethod() instead")] [JsonProperty(PropertyName = "cryptoData")] public JObject PaymentMethod { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)] public DateTimeOffset MonitoringExpiration { get; set; } public HistoricalAddressInvoiceData[] HistoricalAddresses { get; set; } public HashSet<string> AvailableAddressHashes { get; set; } public bool ExtendedNotifications { get; set; } public List<InvoiceEventData> Events { get; internal set; } public double PaymentTolerance { get; set; } public bool Archived { get; set; } [JsonConverter(typeof(StringEnumConverter))] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public InvoiceType Type { get; set; } public bool IsExpired() { return DateTimeOffset.UtcNow > ExpirationTime; } public InvoiceResponse EntityToDTO() { ServerUrl = ServerUrl ?? ""; InvoiceResponse dto = new InvoiceResponse { Id = Id, StoreId = StoreId, OrderId = Metadata.OrderId, PosData = Metadata.PosData, CurrentTime = DateTimeOffset.UtcNow, InvoiceTime = InvoiceTime, ExpirationTime = ExpirationTime, #pragma warning disable CS0618 // Type or member is obsolete Status = StatusString, ExceptionStatus = ExceptionStatus == InvoiceExceptionStatus.None ? new JValue(false) : new JValue(ExceptionStatusString), #pragma warning restore CS0618 // Type or member is obsolete Currency = Currency, Flags = new Flags() { Refundable = Refundable }, PaymentSubtotals = new Dictionary<string, decimal>(), PaymentTotals = new Dictionary<string, decimal>(), SupportedTransactionCurrencies = new Dictionary<string, NBitpayClient.InvoiceSupportedTransactionCurrency>(), Addresses = new Dictionary<string, string>(), PaymentCodes = new Dictionary<string, InvoiceCryptoInfo.InvoicePaymentUrls>(), ExchangeRates = new Dictionary<string, Dictionary<string, decimal>>() }; dto.Url = ServerUrl.WithTrailingSlash() + $"invoice?id=" + Id; dto.CryptoInfo = new List<InvoiceCryptoInfo>(); dto.MinerFees = new Dictionary<string, MinerFeeInfo>(); foreach (var info in this.GetPaymentMethods()) { var accounting = info.Calculate(); var cryptoInfo = new InvoiceCryptoInfo(); var subtotalPrice = accounting.TotalDue - accounting.NetworkFee; var cryptoCode = info.GetId().CryptoCode; var details = info.GetPaymentMethodDetails(); var address = details?.GetPaymentDestination(); var exrates = new Dictionary<string, decimal> { { Currency, cryptoInfo.Rate } }; cryptoInfo.CryptoCode = cryptoCode; cryptoInfo.PaymentType = info.GetId().PaymentType.ToString(); cryptoInfo.Rate = info.Rate; cryptoInfo.Price = subtotalPrice.ToString(); cryptoInfo.Due = accounting.Due.ToString(); cryptoInfo.Paid = accounting.Paid.ToString(); cryptoInfo.TotalDue = accounting.TotalDue.ToString(); cryptoInfo.NetworkFee = accounting.NetworkFee.ToString(); cryptoInfo.TxCount = accounting.TxCount; cryptoInfo.CryptoPaid = accounting.CryptoPaid.ToString(); cryptoInfo.Address = address; cryptoInfo.ExRates = exrates; var paymentId = info.GetId(); cryptoInfo.Url = ServerUrl.WithTrailingSlash() + $"i/{paymentId}/{Id}"; cryptoInfo.Payments = GetPayments(info.Network, true).Select(entity => { var data = entity.GetCryptoPaymentData(); return new InvoicePaymentInfo() { Id = data.GetPaymentId(), Fee = entity.NetworkFee, Value = data.GetValue(), Completed = data.PaymentCompleted(entity), Confirmed = data.PaymentConfirmed(entity, SpeedPolicy), Destination = data.GetDestination(), PaymentType = data.GetPaymentType().ToString(), ReceivedDate = entity.ReceivedTime.DateTime }; }).ToList(); if (details?.Activated is true) { paymentId.PaymentType.PopulateCryptoInfo(info, cryptoInfo, ServerUrl); if (paymentId.PaymentType == PaymentTypes.BTCLike) { var minerInfo = new MinerFeeInfo(); minerInfo.TotalFee = accounting.NetworkFee.Satoshi; minerInfo.SatoshiPerBytes = ((BitcoinLikeOnChainPaymentMethod)details).FeeRate .GetFee(1).Satoshi; dto.MinerFees.TryAdd(cryptoInfo.CryptoCode, minerInfo); #pragma warning disable 618 if (info.CryptoCode == "BTC") { dto.BTCPrice = cryptoInfo.Price; dto.Rate = cryptoInfo.Rate; dto.ExRates = cryptoInfo.ExRates; dto.BitcoinAddress = cryptoInfo.Address; dto.BTCPaid = cryptoInfo.Paid; dto.BTCDue = cryptoInfo.Due; dto.PaymentUrls = cryptoInfo.PaymentUrls; } #pragma warning restore 618 } } dto.CryptoInfo.Add(cryptoInfo); dto.PaymentCodes.Add(paymentId.ToString(), cryptoInfo.PaymentUrls); dto.PaymentSubtotals.Add(paymentId.ToString(), subtotalPrice.Satoshi); dto.PaymentTotals.Add(paymentId.ToString(), accounting.TotalDue.Satoshi); dto.SupportedTransactionCurrencies.TryAdd(cryptoCode, new InvoiceSupportedTransactionCurrency() { Enabled = true }); dto.Addresses.Add(paymentId.ToString(), address); dto.ExchangeRates.TryAdd(cryptoCode, exrates); } //dto.AmountPaid dto.MinerFees & dto.TransactionCurrency are not supported by btcpayserver as we have multi currency payment support per invoice dto.ItemCode = Metadata.ItemCode; dto.ItemDesc = Metadata.ItemDesc; dto.TaxIncluded = Metadata.TaxIncluded ?? 0m; dto.Price = Price; dto.Currency = Currency; dto.Buyer = new JObject(); dto.Buyer.Add(new JProperty("name", Metadata.BuyerName)); dto.Buyer.Add(new JProperty("address1", Metadata.BuyerAddress1)); dto.Buyer.Add(new JProperty("address2", Metadata.BuyerAddress2)); dto.Buyer.Add(new JProperty("locality", Metadata.BuyerCity)); dto.Buyer.Add(new JProperty("region", Metadata.BuyerState)); dto.Buyer.Add(new JProperty("postalCode", Metadata.BuyerZip)); dto.Buyer.Add(new JProperty("country", Metadata.BuyerCountry)); dto.Buyer.Add(new JProperty("phone", Metadata.BuyerPhone)); dto.Buyer.Add(new JProperty("email", string.IsNullOrWhiteSpace(Metadata.BuyerEmail) ? RefundMail : Metadata.BuyerEmail)); dto.Token = Encoders.Base58.EncodeData(RandomUtils.GetBytes(16)); //No idea what it is useful for dto.Guid = Guid.NewGuid().ToString(); return dto; } internal bool Support(PaymentMethodId paymentMethodId) { var rates = GetPaymentMethods(); return rates.TryGet(paymentMethodId) != null; } public PaymentMethod GetPaymentMethod(PaymentMethodId paymentMethodId) { GetPaymentMethods().TryGetValue(paymentMethodId, out var data); return data; } public PaymentMethod GetPaymentMethod(BTCPayNetworkBase network, PaymentType paymentType) { return GetPaymentMethod(new PaymentMethodId(network.CryptoCode, paymentType)); } public PaymentMethodDictionary GetPaymentMethods() { PaymentMethodDictionary paymentMethods = new PaymentMethodDictionary(); var serializer = new Serializer(null); #pragma warning disable CS0618 if (PaymentMethod != null) { foreach (var prop in PaymentMethod.Properties()) { var r = serializer.ToObject<PaymentMethod>(prop.Value.ToString()); if (!PaymentMethodId.TryParse(prop.Name, out var paymentMethodId)) { continue; } r.CryptoCode = paymentMethodId.CryptoCode; r.PaymentType = paymentMethodId.PaymentType.ToString(); r.ParentEntity = this; if (Networks != null) { r.Network = Networks.GetNetwork<BTCPayNetworkBase>(r.CryptoCode); if (r.Network is null) continue; } paymentMethods.Add(r); } } #pragma warning restore CS0618 return paymentMethods; } public void SetPaymentMethod(PaymentMethod paymentMethod) { var dict = GetPaymentMethods(); dict.AddOrReplace(paymentMethod); SetPaymentMethods(dict); } public void SetPaymentMethods(PaymentMethodDictionary paymentMethods) { var obj = new JObject(); var serializer = new Serializer(null); #pragma warning disable CS0618 foreach (var v in paymentMethods) { var clone = serializer.ToObject<PaymentMethod>(serializer.ToString(v)); clone.CryptoCode = null; clone.PaymentType = null; obj.Add(new JProperty(v.GetId().ToString(), JObject.Parse(serializer.ToString(clone)))); } PaymentMethod = obj; foreach (var cryptoData in paymentMethods) { cryptoData.ParentEntity = this; } #pragma warning restore CS0618 } public InvoiceState GetInvoiceState() { return new InvoiceState(Status, ExceptionStatus); } /// <summary> /// Invoice version < 1 were saving metadata directly under the InvoiceEntity /// object. But in version > 2, the metadata is saved under the InvoiceEntity.Metadata object /// This method is extracting metadata from the InvoiceEntity of version < 1 invoices and put them in InvoiceEntity.Metadata. /// </summary> internal void MigrateLegacyInvoice() { T TryParseMetadata<T>(string field) where T : class { if (AdditionalData.TryGetValue(field, out var token) && token is JObject obj) { return obj.ToObject<T>(); } return null; } if (TryParseMetadata<BuyerInformation>("buyerInformation") is BuyerInformation buyerInformation && TryParseMetadata<ProductInformation>("productInformation") is ProductInformation productInformation) { var wellknown = new InvoiceMetadata() { BuyerAddress1 = buyerInformation.BuyerAddress1, BuyerAddress2 = buyerInformation.BuyerAddress2, BuyerCity = buyerInformation.BuyerCity, BuyerCountry = buyerInformation.BuyerCountry, BuyerEmail = buyerInformation.BuyerEmail, BuyerName = buyerInformation.BuyerName, BuyerPhone = buyerInformation.BuyerPhone, BuyerState = buyerInformation.BuyerState, BuyerZip = buyerInformation.BuyerZip, ItemCode = productInformation.ItemCode, ItemDesc = productInformation.ItemDesc, Physical = productInformation.Physical, TaxIncluded = productInformation.TaxIncluded }; if (AdditionalData.TryGetValue("posData", out var token) && token is JValue val && val.Type == JTokenType.String) { wellknown.PosData = val.Value<string>(); } if (AdditionalData.TryGetValue("orderId", out var token2) && token2 is JValue val2 && val2.Type == JTokenType.String) { wellknown.OrderId = val2.Value<string>(); } Metadata = wellknown; Currency = productInformation.Currency?.Trim().ToUpperInvariant(); Price = productInformation.Price; } else { throw new InvalidOperationException("Not a legacy invoice"); } } public bool IsUnsetTopUp() { return Type == InvoiceType.TopUp && Price == 0.0m; } } public enum InvoiceStatusLegacy { New, Paid, Expired, Invalid, Complete, Confirmed } public static class InvoiceStatusLegacyExtensions { public static InvoiceStatus ToModernStatus(this InvoiceStatusLegacy legacy) { switch (legacy) { case InvoiceStatusLegacy.Complete: case InvoiceStatusLegacy.Confirmed: return InvoiceStatus.Settled; case InvoiceStatusLegacy.Expired: return InvoiceStatus.Expired; case InvoiceStatusLegacy.Invalid: return InvoiceStatus.Invalid; case InvoiceStatusLegacy.Paid: return InvoiceStatus.Processing; case InvoiceStatusLegacy.New: return InvoiceStatus.New; default: throw new NotSupportedException(); } } } public class InvoiceState { static readonly Dictionary<string, InvoiceStatusLegacy> _StringToInvoiceStatus; static readonly Dictionary<InvoiceStatusLegacy, string> _InvoiceStatusToString; static readonly Dictionary<string, InvoiceExceptionStatus> _StringToExceptionStatus; static readonly Dictionary<InvoiceExceptionStatus, string> _ExceptionStatusToString; static InvoiceState() { _StringToInvoiceStatus = new Dictionary<string, InvoiceStatusLegacy>(); _StringToInvoiceStatus.Add("paid", InvoiceStatusLegacy.Paid); _StringToInvoiceStatus.Add("expired", InvoiceStatusLegacy.Expired); _StringToInvoiceStatus.Add("invalid", InvoiceStatusLegacy.Invalid); _StringToInvoiceStatus.Add("complete", InvoiceStatusLegacy.Complete); _StringToInvoiceStatus.Add("new", InvoiceStatusLegacy.New); _StringToInvoiceStatus.Add("confirmed", InvoiceStatusLegacy.Confirmed); _InvoiceStatusToString = _StringToInvoiceStatus.ToDictionary(kv => kv.Value, kv => kv.Key); _StringToExceptionStatus = new Dictionary<string, InvoiceExceptionStatus>(); _StringToExceptionStatus.Add(string.Empty, InvoiceExceptionStatus.None); _StringToExceptionStatus.Add("paidPartial", InvoiceExceptionStatus.PaidPartial); _StringToExceptionStatus.Add("paidLate", InvoiceExceptionStatus.PaidLate); _StringToExceptionStatus.Add("paidOver", InvoiceExceptionStatus.PaidOver); _StringToExceptionStatus.Add("marked", InvoiceExceptionStatus.Marked); _ExceptionStatusToString = _StringToExceptionStatus.ToDictionary(kv => kv.Value, kv => kv.Key); _StringToExceptionStatus.Add("false", InvoiceExceptionStatus.None); } public InvoiceState(string status, string exceptionStatus) { Status = _StringToInvoiceStatus[status]; ExceptionStatus = _StringToExceptionStatus[exceptionStatus ?? string.Empty]; } public InvoiceState(InvoiceStatusLegacy status, InvoiceExceptionStatus exceptionStatus) { Status = status; ExceptionStatus = exceptionStatus; } public InvoiceStatusLegacy Status { get; } public InvoiceExceptionStatus ExceptionStatus { get; } public static string ToString(InvoiceStatusLegacy status) { return _InvoiceStatusToString[status]; } public static string ToString(InvoiceExceptionStatus exceptionStatus) { return _ExceptionStatusToString[exceptionStatus]; } public bool CanMarkComplete() { return (Status == InvoiceStatusLegacy.Paid) || (Status == InvoiceStatusLegacy.New) || ((Status == InvoiceStatusLegacy.New || Status == InvoiceStatusLegacy.Expired) && ExceptionStatus == InvoiceExceptionStatus.PaidPartial) || ((Status == InvoiceStatusLegacy.New || Status == InvoiceStatusLegacy.Expired) && ExceptionStatus == InvoiceExceptionStatus.PaidLate) || (Status != InvoiceStatusLegacy.Complete && ExceptionStatus == InvoiceExceptionStatus.Marked) || (Status == InvoiceStatusLegacy.Invalid); } public bool CanMarkInvalid() { return (Status == InvoiceStatusLegacy.Paid) || (Status == InvoiceStatusLegacy.New) || ((Status == InvoiceStatusLegacy.New || Status == InvoiceStatusLegacy.Expired) && ExceptionStatus == InvoiceExceptionStatus.PaidPartial) || ((Status == InvoiceStatusLegacy.New || Status == InvoiceStatusLegacy.Expired) && ExceptionStatus == InvoiceExceptionStatus.PaidLate) || (Status != InvoiceStatusLegacy.Invalid && ExceptionStatus == InvoiceExceptionStatus.Marked); } public override int GetHashCode() { return HashCode.Combine(Status, ExceptionStatus); } public static bool operator ==(InvoiceState a, InvoiceState b) { if (a is null && b is null) return true; if (a is null) return false; return a.Equals(b); } public static bool operator !=(InvoiceState a, InvoiceState b) { return !(a == b); } public bool Equals(InvoiceState o) { if (o is null) return false; return o.Status == Status && o.ExceptionStatus == ExceptionStatus; } public override bool Equals(object obj) { if (obj is InvoiceState o) { return this.Equals(o); } return false; } public override string ToString() { return Status.ToModernStatus().ToString() + (ExceptionStatus == InvoiceExceptionStatus.None ? string.Empty : $" ({ToString(ExceptionStatus)})"); } } public class PaymentMethodAccounting { /// <summary>Total amount of this invoice</summary> public Money TotalDue { get; set; } /// <summary>Amount of crypto remaining to pay this invoice</summary> public Money Due { get; set; } /// <summary>Same as Due, can be negative</summary> public Money DueUncapped { get; set; } /// <summary>If DueUncapped is negative, that means user overpaid invoice</summary> public Money OverpaidHelper { get { return DueUncapped > Money.Zero ? Money.Zero : -DueUncapped; } } /// <summary> /// Total amount of the invoice paid after conversion to this crypto currency /// </summary> public Money Paid { get; set; } /// <summary> /// Total amount of the invoice paid in this currency /// </summary> public Money CryptoPaid { get; set; } /// <summary> /// Number of transactions required to pay /// </summary> public int TxRequired { get; set; } /// <summary> /// Number of transactions using this payment method /// </summary> public int TxCount { get; set; } /// <summary> /// Total amount of network fee to pay to the invoice /// </summary> public Money NetworkFee { get; set; } /// <summary> /// Total amount of network fee to pay to the invoice /// </summary> public Money NetworkFeeAlreadyPaid { get; set; } /// <summary> /// Minimum required to be paid in order to accept invoice as paid /// </summary> public Money MinimumTotalDue { get; set; } } public interface IPaymentMethod { PaymentMethodId GetId(); decimal Rate { get; set; } IPaymentMethodDetails GetPaymentMethodDetails(); } public class PaymentMethod : IPaymentMethod { [JsonIgnore] public InvoiceEntity ParentEntity { get; set; } [JsonIgnore] public BTCPayNetworkBase Network { get; set; } [JsonProperty(PropertyName = "cryptoCode", DefaultValueHandling = DefaultValueHandling.Ignore)] [Obsolete("Use GetId().CryptoCode instead")] public string CryptoCode { get; set; } [JsonProperty(PropertyName = "paymentType", DefaultValueHandling = DefaultValueHandling.Ignore)] [Obsolete("Use GetId().PaymentType instead")] public string PaymentType { get; set; } /// <summary> /// We only use this to pass a singleton asking to the payment handler to prefer payments through TOR, we don't really /// need to save this information /// </summary> [JsonIgnore] public bool PreferOnion { get; set; } public PaymentMethodId GetId() { #pragma warning disable CS0618 // Type or member is obsolete return new PaymentMethodId(CryptoCode, string.IsNullOrEmpty(PaymentType) ? PaymentTypes.BTCLike : PaymentTypes.Parse(PaymentType)); #pragma warning restore CS0618 // Type or member is obsolete } public void SetId(PaymentMethodId id) { #pragma warning disable CS0618 // Type or member is obsolete CryptoCode = id.CryptoCode; PaymentType = id.PaymentType.ToString(); #pragma warning restore CS0618 // Type or member is obsolete } [JsonProperty(PropertyName = "rate")] public decimal Rate { get; set; } [Obsolete("Use GetPaymentMethodDetails() instead")] [JsonProperty(PropertyName = "paymentMethod")] public JObject PaymentMethodDetails { get; set; } public IPaymentMethodDetails GetPaymentMethodDetails() { #pragma warning disable CS0618 // Type or member is obsolete // Legacy, old code does not have PaymentMethods if (string.IsNullOrEmpty(PaymentType) || PaymentMethodDetails == null) { return new Payments.Bitcoin.BitcoinLikeOnChainPaymentMethod() { FeeRate = FeeRate, DepositAddress = string.IsNullOrEmpty(DepositAddress) ? null : DepositAddress, NextNetworkFee = NextNetworkFee }; } else { IPaymentMethodDetails details = GetId().PaymentType.DeserializePaymentMethodDetails(Network, PaymentMethodDetails.ToString()); if (details is Payments.Bitcoin.BitcoinLikeOnChainPaymentMethod btcLike) { btcLike.NextNetworkFee = NextNetworkFee; btcLike.DepositAddress = string.IsNullOrEmpty(DepositAddress) ? null : DepositAddress; btcLike.FeeRate = FeeRate; } return details; } throw new NotSupportedException(PaymentType); #pragma warning restore CS0618 // Type or member is obsolete } public PaymentMethod SetPaymentMethodDetails(IPaymentMethodDetails paymentMethod) { #pragma warning disable CS0618 // Type or member is obsolete // Legacy, need to fill the old fields if (PaymentType == null) PaymentType = paymentMethod.GetPaymentType().ToString(); else if (PaymentType != paymentMethod.GetPaymentType().ToString()) throw new InvalidOperationException("Invalid payment method affected"); if (paymentMethod is Payments.Bitcoin.BitcoinLikeOnChainPaymentMethod bitcoinPaymentMethod) { NextNetworkFee = bitcoinPaymentMethod.NextNetworkFee; FeeRate = bitcoinPaymentMethod.FeeRate; DepositAddress = bitcoinPaymentMethod.DepositAddress; } PaymentMethodDetails = JObject.Parse(paymentMethod.GetPaymentType().SerializePaymentMethodDetails(Network, paymentMethod)); #pragma warning restore CS0618 // Type or member is obsolete return this; } [JsonProperty(PropertyName = "feeRate")] [Obsolete("Use ((BitcoinLikeOnChainPaymentMethod)GetPaymentMethod()).FeeRate")] public FeeRate FeeRate { get; set; } [JsonProperty(PropertyName = "txFee")] [Obsolete("Use ((BitcoinLikeOnChainPaymentMethod)GetPaymentMethod()).NextNetworkFee")] public Money NextNetworkFee { get; set; } [JsonProperty(PropertyName = "depositAddress")] [Obsolete("Use ((BitcoinLikeOnChainPaymentMethod)GetPaymentMethod()).DepositAddress")] public string DepositAddress { get; set; } public PaymentMethodAccounting Calculate(Func<PaymentEntity, bool> paymentPredicate = null) { paymentPredicate = paymentPredicate ?? new Func<PaymentEntity, bool>((p) => true); var paymentMethods = ParentEntity.GetPaymentMethods(); var totalDue = ParentEntity.Price / Rate; var paid = 0m; var cryptoPaid = 0.0m; int precision = Network?.Divisibility ?? 8; var totalDueNoNetworkCost = Money.Coins(Extensions.RoundUp(totalDue, precision)); bool paidEnough = paid >= Extensions.RoundUp(totalDue, precision); int txRequired = 0; decimal networkFeeAlreadyPaid = 0.0m; _ = ParentEntity.GetPayments(true) .Where(p => paymentPredicate(p)) .OrderBy(p => p.ReceivedTime) .Select(_ => { var txFee = _.GetValue(paymentMethods, GetId(), _.NetworkFee, precision); networkFeeAlreadyPaid += txFee; paid += _.GetValue(paymentMethods, GetId(), null, precision); if (!paidEnough) { totalDue += txFee; } paidEnough |= Extensions.RoundUp(paid, precision) >= Extensions.RoundUp(totalDue, precision); if (GetId() == _.GetPaymentMethodId()) { cryptoPaid += _.GetCryptoPaymentData().GetValue(); txRequired++; } return _; }).ToArray(); var accounting = new PaymentMethodAccounting(); accounting.TxCount = txRequired; if (!paidEnough) { txRequired++; totalDue += GetTxFee(); } accounting.TotalDue = Money.Coins(Extensions.RoundUp(totalDue, precision)); accounting.Paid = Money.Coins(Extensions.RoundUp(paid, precision)); accounting.TxRequired = txRequired; accounting.CryptoPaid = Money.Coins(Extensions.RoundUp(cryptoPaid, precision)); accounting.Due = Money.Max(accounting.TotalDue - accounting.Paid, Money.Zero); accounting.DueUncapped = accounting.TotalDue - accounting.Paid; accounting.NetworkFee = accounting.TotalDue - totalDueNoNetworkCost; accounting.NetworkFeeAlreadyPaid = Money.Coins(Extensions.RoundUp(networkFeeAlreadyPaid, precision)); // If the total due is 0, there is no payment tolerance to calculate var minimumTotalDueSatoshi = accounting.TotalDue.Satoshi == 0 ? 0 : Math.Max(1.0m, accounting.TotalDue.Satoshi * (1.0m - ((decimal)ParentEntity.PaymentTolerance / 100.0m))); accounting.MinimumTotalDue = Money.Satoshis(minimumTotalDueSatoshi); return accounting; } private decimal GetTxFee() { return GetPaymentMethodDetails()?.GetNextNetworkFee() ?? 0m; } } public class PaymentEntity { [NotMapped] [JsonIgnore] public BTCPayNetworkBase Network { get; set; } public int Version { get; set; } [Obsolete("Use ReceivedTime instead")] [JsonProperty("receivedTime", DefaultValueHandling = DefaultValueHandling.Ignore)] // Old invoices were storing the received time in second public DateTimeOffset? ReceivedTimeSeconds { get; set; } [Obsolete("Use ReceivedTime instead")] [JsonProperty("receivedTimeMs", DefaultValueHandling = DefaultValueHandling.Ignore)] [JsonConverter(typeof(DateTimeMilliJsonConverter))] // Our RBF detection logic depends on properly ordering payments based on // received time, so we needed a received time in milli to ensure that // even if payments are separated by less than a second, they would still be ordered correctly public DateTimeOffset? ReceivedTimeMilli { get; set; } [JsonIgnore] public DateTimeOffset ReceivedTime { get { #pragma warning disable 618 return (ReceivedTimeMilli ?? ReceivedTimeSeconds).GetValueOrDefault(); #pragma warning restore 618 } set { #pragma warning disable 618 ReceivedTimeMilli = value; #pragma warning restore 618 } } public decimal NetworkFee { get; set; } [Obsolete("Use ((BitcoinLikePaymentData)GetCryptoPaymentData()).Outpoint")] public OutPoint Outpoint { get; set; } [Obsolete("Use ((BitcoinLikePaymentData)GetCryptoPaymentData()).Output")] public TxOut Output { get; set; } public bool Accounted { get; set; } [Obsolete("Use GetpaymentMethodId().CryptoCode instead")] public string CryptoCode { get; set; } [Obsolete("Use GetCryptoPaymentData() instead")] public string CryptoPaymentData { get; set; } [Obsolete("Use GetpaymentMethodId().PaymentType instead")] public string CryptoPaymentDataType { get; set; } public CryptoPaymentData GetCryptoPaymentData() { CryptoPaymentData paymentData = null; #pragma warning disable CS0618 // Type or member is obsolete if (string.IsNullOrEmpty(CryptoPaymentData)) { // For invoices created when CryptoPaymentDataType was not existing, we just consider that it is a RBFed payment for safety var bitcoin = new BitcoinLikePaymentData(); bitcoin.Network = Network; bitcoin.Outpoint = Outpoint; bitcoin.Output = Output; bitcoin.RBF = true; bitcoin.ConfirmationCount = 0; bitcoin.Legacy = true; bitcoin.Output = Output; bitcoin.Outpoint = Outpoint; paymentData = bitcoin; } else { var paymentMethodId = GetPaymentMethodId(); if (paymentMethodId is null) { return null; } paymentData = paymentMethodId.PaymentType.DeserializePaymentData(Network, CryptoPaymentData); if (paymentData is null) { return null; } paymentData.Network = Network; if (paymentData is BitcoinLikePaymentData bitcoin) { bitcoin.Output = Output; bitcoin.Outpoint = Outpoint; } } return paymentData; } public PaymentEntity SetCryptoPaymentData(CryptoPaymentData cryptoPaymentData) { #pragma warning disable CS0618 if (cryptoPaymentData is Payments.Bitcoin.BitcoinLikePaymentData paymentData) { // Legacy Outpoint = paymentData.Outpoint; Output = paymentData.Output; /// } CryptoPaymentDataType = cryptoPaymentData.GetPaymentType().ToString(); CryptoPaymentData = GetPaymentMethodId().PaymentType.SerializePaymentData(Network, cryptoPaymentData); #pragma warning restore CS0618 return this; } internal decimal GetValue(PaymentMethodDictionary paymentMethods, PaymentMethodId paymentMethodId, decimal? value, int precision) { value = value ?? this.GetCryptoPaymentData().GetValue(); var to = paymentMethodId; var from = this.GetPaymentMethodId(); if (to == from) return decimal.Round(value.Value, precision); var fromRate = paymentMethods[from].Rate; var toRate = paymentMethods[to].Rate; var fiatValue = fromRate * decimal.Round(value.Value, precision); var otherCurrencyValue = toRate == 0 ? 0.0m : fiatValue / toRate; return otherCurrencyValue; } public PaymentMethodId GetPaymentMethodId() { #pragma warning disable CS0618 // Type or member is obsolete PaymentType paymentType; if (string.IsNullOrEmpty(CryptoPaymentDataType)) { paymentType = BitcoinPaymentType.Instance; ; } else if (!PaymentTypes.TryParse(CryptoPaymentDataType, out paymentType)) { return null; } return new PaymentMethodId(CryptoCode ?? "BTC", paymentType); #pragma warning restore CS0618 // Type or member is obsolete } public string GetCryptoCode() { #pragma warning disable CS0618 return CryptoCode ?? "BTC"; #pragma warning restore CS0618 } } /// <summary> /// A record of a payment /// </summary> public interface CryptoPaymentData { [JsonIgnore] BTCPayNetworkBase Network { get; set; } /// <summary> /// Returns an identifier which uniquely identify the payment /// </summary> /// <returns>The payment id</returns> string GetPaymentId(); /// <summary> /// Returns terms which will be indexed and searchable in the search bar of invoice /// </summary> /// <returns>The search terms</returns> string[] GetSearchTerms(); /// <summary> /// Get value of what as been paid /// </summary> /// <returns>The amount paid</returns> decimal GetValue(); bool PaymentCompleted(PaymentEntity entity); bool PaymentConfirmed(PaymentEntity entity, SpeedPolicy speedPolicy); PaymentType GetPaymentType(); string GetDestination(); } }
// <copyright file="Cookie.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.Linq; using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium { /// <summary> /// Represents a cookie in the browser. /// </summary> [Serializable] [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public class Cookie { private string cookieName; private string cookieValue; private string cookiePath; private string cookieDomain; private string sameSite; private bool isHttpOnly; private bool secure; private DateTime? cookieExpiry; private readonly string[] sameSiteValues = {"Strict", "Lax", "None"}; /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class with a specific name and value. /// </summary> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <exception cref="ArgumentException">If the name is <see langword="null"/> or an empty string, /// or if it contains a semi-colon.</exception> /// <exception cref="ArgumentNullException">If the value is <see langword="null"/>.</exception> public Cookie(string name, string value) : this(name, value, null) { } /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class with a specific name, /// value, and path. /// </summary> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <param name="path">The path of the cookie.</param> /// <exception cref="ArgumentException">If the name is <see langword="null"/> or an empty string, /// or if it contains a semi-colon.</exception> /// <exception cref="ArgumentNullException">If the value is <see langword="null"/>.</exception> public Cookie(string name, string value, string path) : this(name, value, path, null) { } /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class with a specific name, /// value, path and expiration date. /// </summary> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <param name="path">The path of the cookie.</param> /// <param name="expiry">The expiration date of the cookie.</param> /// <exception cref="ArgumentException">If the name is <see langword="null"/> or an empty string, /// or if it contains a semi-colon.</exception> /// <exception cref="ArgumentNullException">If the value is <see langword="null"/>.</exception> public Cookie(string name, string value, string path, DateTime? expiry) : this(name, value, null, path, expiry) { } /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class with a specific name, /// value, domain, path and expiration date. /// </summary> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <param name="domain">The domain of the cookie.</param> /// <param name="path">The path of the cookie.</param> /// <param name="expiry">The expiration date of the cookie.</param> /// <exception cref="ArgumentException">If the name is <see langword="null"/> or an empty string, /// or if it contains a semi-colon.</exception> /// <exception cref="ArgumentNullException">If the value is <see langword="null"/>.</exception> public Cookie(string name, string value, string domain, string path, DateTime? expiry) : this(name, value, domain, path, expiry, false, false, null) { } /// <summary> /// Initializes a new instance of the <see cref="ReturnedCookie"/> class with a specific name, /// value, domain, path and expiration date. /// </summary> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <param name="domain">The domain of the cookie.</param> /// <param name="path">The path of the cookie.</param> /// <param name="expiry">The expiration date of the cookie.</param> /// <param name="isSecure"><see langword="true"/> if the cookie is secure; otherwise <see langword="false"/></param> /// <param name="isHttpOnly"><see langword="true"/> if the cookie is an HTTP-only cookie; otherwise <see langword="false"/></param> /// <param name="sameSite">The SameSite value of cookie.</param> /// <exception cref="ArgumentException">If the name and value are both an empty string, /// or if the name contains a semi-colon.</exception> /// <exception cref="ArgumentNullException">If the name, value or currentUrl is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException">If the same site value is not valid or same site value is "None" but secure is set to false.</exception> public Cookie(string name, string value, string domain, string path, DateTime? expiry, bool secure, bool isHttpOnly, string sameSite) { if (name == null) { throw new ArgumentNullException(nameof(value), "Cookie name cannot be null"); } if (value == null) { throw new ArgumentNullException(nameof(value), "Cookie value cannot be null"); } if (name == string.Empty && value == string.Empty) { throw new ArgumentException("Cookie name and value cannot both be empty string"); } if (name.IndexOf(';') != -1) { throw new ArgumentException("Cookie names cannot contain a ';': " + name, nameof(name)); } this.cookieName = name; this.cookieValue = value; if (!string.IsNullOrEmpty(path)) { this.cookiePath = path; } this.cookieDomain = StripPort(domain); if (expiry != null) { this.cookieExpiry = expiry; } this.isHttpOnly = isHttpOnly; this.secure = secure; if (!string.IsNullOrEmpty(sameSite)) { if (!sameSiteValues.Contains(sameSite)) { throw new ArgumentException("Invalid sameSite cookie value. It should either \"Lax\", \"Strict\" or \"None\" ", nameof(sameSite)); } this.sameSite = sameSite; } } /// <summary> /// Gets the name of the cookie. /// </summary> [JsonProperty("name")] public string Name { get { return this.cookieName; } } /// <summary> /// Gets the value of the cookie. /// </summary> [JsonProperty("value")] public string Value { get { return this.cookieValue; } } /// <summary> /// Gets the domain of the cookie. /// </summary> [JsonProperty("domain", NullValueHandling = NullValueHandling.Ignore)] public string Domain { get { return this.cookieDomain; } } /// <summary> /// Gets the path of the cookie. /// </summary> [JsonProperty("path", NullValueHandling = NullValueHandling.Ignore)] public virtual string Path { get { return this.cookiePath; } } /// <summary> /// Gets a value indicating whether the cookie is secure. /// </summary> [JsonProperty("secure")] public virtual bool Secure { get { return this.secure; } } /// <summary> /// Gets a value indicating whether the cookie is an HTTP-only cookie. /// </summary> [JsonProperty("httpOnly")] public virtual bool IsHttpOnly { get { return this.isHttpOnly; } } /// <summary> /// Gets the SameSite setting for the cookie. /// </summary> [JsonProperty("sameSite", NullValueHandling = NullValueHandling.Ignore)] public virtual string SameSite { get { return this.sameSite; } } /// <summary> /// Gets the expiration date of the cookie. /// </summary> public DateTime? Expiry { get { return this.cookieExpiry; } } /// <summary> /// Gets the cookie expiration date in seconds from the defined zero date (01 January 1970 00:00:00 UTC). /// </summary> /// <remarks>This property only exists so that the JSON serializer can serialize a /// cookie without resorting to a custom converter.</remarks> [JsonProperty("expiry", NullValueHandling = NullValueHandling.Ignore)] internal long? ExpirySeconds { get { if (this.cookieExpiry == null) { return null; } DateTime zeroDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); TimeSpan span = this.cookieExpiry.Value.ToUniversalTime().Subtract(zeroDate); long totalSeconds = Convert.ToInt64(span.TotalSeconds); return totalSeconds; } } /// <summary> /// Converts a Dictionary to a Cookie. /// </summary> /// <param name="rawCookie">The Dictionary object containing the cookie parameters.</param> /// <returns>A <see cref="Cookie"/> object with the proper parameters set.</returns> public static Cookie FromDictionary(Dictionary<string, object> rawCookie) { if (rawCookie == null) { throw new ArgumentNullException(nameof(rawCookie), "Dictionary cannot be null"); } string name = rawCookie["name"].ToString(); string value = string.Empty; if (rawCookie["value"] != null) { value = rawCookie["value"].ToString(); } string path = "/"; if (rawCookie.ContainsKey("path") && rawCookie["path"] != null) { path = rawCookie["path"].ToString(); } string domain = string.Empty; if (rawCookie.ContainsKey("domain") && rawCookie["domain"] != null) { domain = rawCookie["domain"].ToString(); } DateTime? expires = null; if (rawCookie.ContainsKey("expiry") && rawCookie["expiry"] != null) { expires = ConvertExpirationTime(rawCookie["expiry"].ToString()); } bool secure = false; if (rawCookie.ContainsKey("secure") && rawCookie["secure"] != null) { secure = bool.Parse(rawCookie["secure"].ToString()); } bool isHttpOnly = false; if (rawCookie.ContainsKey("httpOnly") && rawCookie["httpOnly"] != null) { isHttpOnly = bool.Parse(rawCookie["httpOnly"].ToString()); } string sameSite = null; if (rawCookie.ContainsKey("sameSite") && rawCookie["sameSite"] != null) { sameSite = rawCookie["sameSite"].ToString(); } return new ReturnedCookie(name, value, domain, path, expires, secure, isHttpOnly, sameSite); } /// <summary> /// Creates and returns a string representation of the cookie. /// </summary> /// <returns>A string representation of the cookie.</returns> public override string ToString() { return this.cookieName + "=" + this.cookieValue + (this.cookieExpiry == null ? string.Empty : "; expires=" + this.cookieExpiry.Value.ToUniversalTime().ToString("ddd MM dd yyyy hh:mm:ss UTC", CultureInfo.InvariantCulture)) + (string.IsNullOrEmpty(this.cookiePath) ? string.Empty : "; path=" + this.cookiePath) + (string.IsNullOrEmpty(this.cookieDomain) ? string.Empty : "; domain=" + this.cookieDomain) + "; isHttpOnly= " + this.isHttpOnly + "; secure= " + this.secure + (string.IsNullOrEmpty(this.sameSite) ? string.Empty : "; sameSite=" + this.sameSite); } /// <summary> /// Determines whether the specified <see cref="object">Object</see> is equal /// to the current <see cref="object">Object</see>. /// </summary> /// <param name="obj">The <see cref="object">Object</see> to compare with the /// current <see cref="object">Object</see>.</param> /// <returns><see langword="true"/> if the specified <see cref="object">Object</see> /// is equal to the current <see cref="object">Object</see>; otherwise, /// <see langword="false"/>.</returns> public override bool Equals(object obj) { // Two cookies are equal if the name and value match Cookie cookie = obj as Cookie; if (this == obj) { return true; } if (cookie == null) { return false; } if (!this.cookieName.Equals(cookie.cookieName)) { return false; } return !(this.cookieValue != null ? !this.cookieValue.Equals(cookie.cookieValue) : cookie.Value != null); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns>A hash code for the current <see cref="object">Object</see>.</returns> public override int GetHashCode() { return this.cookieName.GetHashCode(); } private static string StripPort(string domain) { return string.IsNullOrEmpty(domain) ? null : domain.Split(':')[0]; } private static DateTime? ConvertExpirationTime(string expirationTime) { DateTime? expires = null; double seconds = 0; if (double.TryParse(expirationTime, NumberStyles.Number, CultureInfo.InvariantCulture, out seconds)) { try { expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(seconds).ToLocalTime(); } catch (ArgumentOutOfRangeException) { expires = DateTime.MaxValue.ToLocalTime(); } } return expires; } } }
#region Header /* * JsonMockWrapper.cs * Mock object implementing IJsonWrapper, to facilitate actions like * skipping data more efficiently. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. */ #endregion namespace Cake.Gitter { using System; using System.Collections; using System.Collections.Specialized; namespace LitJson { internal class JsonMockWrapper : IJsonWrapper { public bool IsArray { get { return false; } } public bool IsBoolean { get { return false; } } public bool IsDouble { get { return false; } } public bool IsInt { get { return false; } } public bool IsLong { get { return false; } } public bool IsObject { get { return false; } } public bool IsString { get { return false; } } public bool GetBoolean() { return false; } public double GetDouble() { return 0.0; } public int GetInt() { return 0; } public JsonType GetJsonType() { return JsonType.None; } public long GetLong() { return 0L; } public string GetString() { return ""; } public void SetBoolean(bool val) { } public void SetDouble(double val) { } public void SetInt(int val) { } public void SetJsonType(JsonType type) { } public void SetLong(long val) { } public void SetString(string val) { } public string ToJson() { return ""; } public void ToJson(JsonWriter writer) { } bool IList.IsFixedSize { get { return true; } } bool IList.IsReadOnly { get { return true; } } object IList.this[int index] { get { return null; } set { } } int IList.Add(object value) { return 0; } void IList.Clear() { } bool IList.Contains(object value) { return false; } int IList.IndexOf(object value) { return -1; } void IList.Insert(int i, object v) { } void IList.Remove(object value) { } void IList.RemoveAt(int index) { } int ICollection.Count { get { return 0; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return null; } } void ICollection.CopyTo(Array array, int index) { } IEnumerator IEnumerable.GetEnumerator() { return null; } bool IDictionary.IsFixedSize { get { return true; } } bool IDictionary.IsReadOnly { get { return true; } } ICollection IDictionary.Keys { get { return null; } } ICollection IDictionary.Values { get { return null; } } object IDictionary.this[object key] { get { return null; } set { } } void IDictionary.Add(object k, object v) { } void IDictionary.Clear() { } bool IDictionary.Contains(object key) { return false; } void IDictionary.Remove(object key) { } IDictionaryEnumerator IDictionary.GetEnumerator() { return null; } object IOrderedDictionary.this[int idx] { get { return null; } set { } } IDictionaryEnumerator IOrderedDictionary.GetEnumerator() { return null; } void IOrderedDictionary.Insert(int i, object k, object v) { } void IOrderedDictionary.RemoveAt(int i) { } } } }
// 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.Runtime; using System.Runtime.CompilerServices; namespace Internal.Runtime.CompilerHelpers { /// <summary> /// Math helpers for generated code. The helpers marked with [RuntimeExport] and the type /// itself need to be public because they constitute a public contract with the .NET Native toolchain. /// </summary> [CLSCompliant(false)] public static class MathHelpers { #if !BIT64 // // 64-bit checked multiplication for 32-bit platforms // // Helper to multiply two 32-bit uints [MethodImpl(MethodImplOptions.AggressiveInlining)] private static UInt64 Mul32x32To64(UInt32 a, UInt32 b) { return a * (UInt64)b; } // Helper to get high 32-bit of 64-bit int [MethodImpl(MethodImplOptions.AggressiveInlining)] private static UInt32 Hi32Bits(Int64 a) { return (UInt32)(a >> 32); } // Helper to get high 32-bit of 64-bit int [MethodImpl(MethodImplOptions.AggressiveInlining)] private static UInt32 Hi32Bits(UInt64 a) { return (UInt32)(a >> 32); } [RuntimeExport("LMulOvf")] public static Int64 LMulOvf(Int64 i, Int64 j) { Int64 ret; // Remember the sign of the result Int32 sign = (Int32)(Hi32Bits(i) ^ Hi32Bits(j)); // Convert to unsigned multiplication if (i < 0) i = -i; if (j < 0) j = -j; // Get the upper 32 bits of the numbers UInt32 val1High = Hi32Bits(i); UInt32 val2High = Hi32Bits(j); UInt64 valMid; if (val1High == 0) { // Compute the 'middle' bits of the long multiplication valMid = Mul32x32To64(val2High, (UInt32)i); } else { if (val2High != 0) goto ThrowExcep; // Compute the 'middle' bits of the long multiplication valMid = Mul32x32To64(val1High, (UInt32)j); } // See if any bits after bit 32 are set if (Hi32Bits(valMid) != 0) goto ThrowExcep; ret = (Int64)(Mul32x32To64((UInt32)i, (UInt32)j) + (valMid << 32)); // check for overflow if (Hi32Bits(ret) < (UInt32)valMid) goto ThrowExcep; if (sign >= 0) { // have we spilled into the sign bit? if (ret < 0) goto ThrowExcep; } else { ret = -ret; // have we spilled into the sign bit? if (ret > 0) goto ThrowExcep; } return ret; ThrowExcep: return ThrowLngOvf(); } [RuntimeExport("ULMulOvf")] public static UInt64 ULMulOvf(UInt64 i, UInt64 j) { UInt64 ret; // Get the upper 32 bits of the numbers UInt32 val1High = Hi32Bits(i); UInt32 val2High = Hi32Bits(j); UInt64 valMid; if (val1High == 0) { if (val2High == 0) return Mul32x32To64((UInt32)i, (UInt32)j); // Compute the 'middle' bits of the long multiplication valMid = Mul32x32To64(val2High, (UInt32)i); } else { if (val2High != 0) goto ThrowExcep; // Compute the 'middle' bits of the long multiplication valMid = Mul32x32To64(val1High, (UInt32)j); } // See if any bits after bit 32 are set if (Hi32Bits(valMid) != 0) goto ThrowExcep; ret = Mul32x32To64((UInt32)i, (UInt32)j) + (valMid << 32); // check for overflow if (Hi32Bits(ret) < (UInt32)valMid) goto ThrowExcep; return ret; ThrowExcep: return ThrowULngOvf(); } #endif // BIT64 [RuntimeExport("Dbl2IntOvf")] public static int Dbl2IntOvf(double val) { const double two31 = 2147483648.0; // Note that this expression also works properly for val = NaN case if (val > -two31 - 1 && val < two31) return unchecked((int)val); return ThrowIntOvf(); } [RuntimeExport("Dbl2LngOvf")] public static long Dbl2LngOvf(double val) { const double two63 = 2147483648.0 * 4294967296.0; // Note that this expression also works properly for val = NaN case // We need to compare with the very next double to two63. 0x402 is epsilon to get us there. if (val > -two63 - 0x402 && val < two63) return unchecked((long)val); return ThrowLngOvf(); } [RuntimeExport("Dbl2ULngOvf")] public static ulong Dbl2ULngOvf(double val) { const double two64 = 2.0 * 2147483648.0 * 4294967296.0; // Note that this expression also works properly for val = NaN case if (val < two64) return unchecked((ulong)val); return ThrowULngOvf(); } [RuntimeExport("Flt2IntOvf")] public static int Flt2IntOvf(float val) { const double two31 = 2147483648.0; // Note that this expression also works properly for val = NaN case if (val > -two31 - 1 && val < two31) return ((int)val); return ThrowIntOvf(); } [RuntimeExport("Flt2LngOvf")] public static long Flt2LngOvf(float val) { const double two63 = 2147483648.0 * 4294967296.0; // Note that this expression also works properly for val = NaN case // We need to compare with the very next double to two63. 0x402 is epsilon to get us there. if (val > -two63 - 0x402 && val < two63) return ((Int64)val); return ThrowIntOvf(); } // // Matching return types of throw helpers enables tailcalling them. It improves performance // of the hot path because of it does not need to raise full stackframe. // [MethodImpl(MethodImplOptions.NoInlining)] private static int ThrowIntOvf() { throw new OverflowException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static long ThrowLngOvf() { throw new OverflowException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ulong ThrowULngOvf() { throw new OverflowException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Text.Json { internal static partial class JsonHelpers { private struct DateTimeParseData { public int Year; public int Month; public int Day; public int Hour; public int Minute; public int Second; public int Fraction; // This value should never be greater than 9_999_999. public int OffsetHours; public int OffsetMinutes; public bool OffsetNegative => OffsetToken == JsonConstants.Hyphen; public byte OffsetToken; } /// <summary> /// Parse the given UTF-8 <paramref name="source"/> as extended ISO 8601 format. /// </summary> /// <param name="source">UTF-8 source to parse.</param> /// <param name="value">The parsed <see cref="DateTime"/> if successful.</param> /// <returns>"true" if successfully parsed.</returns> public static bool TryParseAsISO(ReadOnlySpan<byte> source, out DateTime value) { if (!TryParseDateTimeOffset(source, out DateTimeParseData parseData)) { value = default; return false; } if (parseData.OffsetToken == JsonConstants.UtcOffsetToken) { return TryCreateDateTime(parseData, DateTimeKind.Utc, out value); } else if (parseData.OffsetToken == JsonConstants.Plus || parseData.OffsetToken == JsonConstants.Hyphen) { if (!TryCreateDateTimeOffset(ref parseData, out DateTimeOffset dateTimeOffset)) { value = default; return false; } value = dateTimeOffset.LocalDateTime; return true; } return TryCreateDateTime(parseData, DateTimeKind.Unspecified, out value); } /// <summary> /// Parse the given UTF-8 <paramref name="source"/> as extended ISO 8601 format. /// </summary> /// <param name="source">UTF-8 source to parse.</param> /// <param name="value">The parsed <see cref="DateTimeOffset"/> if successful.</param> /// <returns>"true" if successfully parsed.</returns> public static bool TryParseAsISO(ReadOnlySpan<byte> source, out DateTimeOffset value) { if (!TryParseDateTimeOffset(source, out DateTimeParseData parseData)) { value = default; return false; } if (parseData.OffsetToken == JsonConstants.UtcOffsetToken || // Same as specifying an offset of "+00:00", except that DateTime's Kind gets set to UTC rather than Local parseData.OffsetToken == JsonConstants.Plus || parseData.OffsetToken == JsonConstants.Hyphen) { return TryCreateDateTimeOffset(ref parseData, out value); } // No offset, attempt to read as local time. return TryCreateDateTimeOffsetInterpretingDataAsLocalTime(parseData, out value); } /// <summary> /// ISO 8601 date time parser (ISO 8601-1:2019). /// </summary> /// <param name="source">The date/time to parse in UTF-8 format.</param> /// <param name="parseData">The parsed <see cref="DateTimeParseData"/> for the given <paramref name="source"/>.</param> /// <remarks> /// Supports extended calendar date (5.2.2.1) and complete (5.4.2.1) calendar date/time of day /// representations with optional specification of seconds and fractional seconds. /// /// Times can be explicitly specified as UTC ("Z" - 5.3.3) or offsets from UTC ("+/-hh:mm" 5.3.4.2). /// If unspecified they are considered to be local per spec. /// /// Examples: (TZD is either "Z" or hh:mm offset from UTC) /// /// YYYY-MM-DD (eg 1997-07-16) /// YYYY-MM-DDThh:mm (eg 1997-07-16T19:20) /// YYYY-MM-DDThh:mm:ss (eg 1997-07-16T19:20:30) /// YYYY-MM-DDThh:mm:ss.s (eg 1997-07-16T19:20:30.45) /// YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00) /// YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:3001:00) /// YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45Z) /// /// Generally speaking we always require the "extended" option when one exists (3.1.3.5). /// The extended variants have separator characters between components ('-', ':', '.', etc.). /// Spaces are not permitted. /// </remarks> /// <returns>"true" if successfully parsed.</returns> private static bool TryParseDateTimeOffset(ReadOnlySpan<byte> source, out DateTimeParseData parseData) { // Source does not have enough characters for YYYY-MM-DD if (source.Length < 10) { parseData = default; return false; } // Parse the calendar date // ----------------------- // ISO 8601-1:2019 5.2.2.1b "Calendar date complete extended format" // [dateX] = [year]["-"][month]["-"][day] // [year] = [YYYY] [0000 - 9999] (4.3.2) // [month] = [MM] [01 - 12] (4.3.3) // [day] = [DD] [01 - 28, 29, 30, 31] (4.3.4) // // Note: 5.2.2.2 "Representations with reduced precision" allows for // just [year]["-"][month] (a) and just [year] (b), but we currently // don't permit it. parseData = new DateTimeParseData(); { uint digit1 = source[0] - (uint)'0'; uint digit2 = source[1] - (uint)'0'; uint digit3 = source[2] - (uint)'0'; uint digit4 = source[3] - (uint)'0'; if (digit1 > 9 || digit2 > 9 || digit3 > 9 || digit4 > 9) { return false; } parseData.Year = (int)(digit1 * 1000 + digit2 * 100 + digit3 * 10 + digit4); } if (source[4] != JsonConstants.Hyphen || !TryGetNextTwoDigits(source.Slice(start: 5, length: 2), ref parseData.Month) || source[7] != JsonConstants.Hyphen || !TryGetNextTwoDigits(source.Slice(start: 8, length: 2), ref parseData.Day)) { return false; } // We now have YYYY-MM-DD [dateX] Debug.Assert(source.Length >= 10); if (source.Length == 10) { // Just a calendar date return true; } // Parse the time of day // --------------------- // // ISO 8601-1:2019 5.3.1.2b "Local time of day complete extended format" // [timeX] = ["T"][hour][":"][min][":"][sec] // [hour] = [hh] [00 - 23] (4.3.8a) // [minute] = [mm] [00 - 59] (4.3.9a) // [sec] = [ss] [00 - 59, 60 with a leap second] (4.3.10a) // // ISO 8601-1:2019 5.3.3 "UTC of day" // [timeX]["Z"] // // ISO 8601-1:2019 5.3.4.2 "Local time of day with the time shift between // local time scale and UTC" (Extended format) // // [shiftX] = ["+"|"-"][hour][":"][min] // // Notes: // // "T" is optional per spec, but _only_ when times are used alone. In our // case, we're reading out a complete date & time and as such require "T". // (5.4.2.1b). // // For [timeX] We allow seconds to be omitted per 5.3.1.3a "Representations // with reduced precision". 5.3.1.3b allows just specifying the hour, but // we currently don't permit this. // // Decimal fractions are allowed for hours, minutes and seconds (5.3.14). // We only allow fractions for seconds currently. Lower order components // can't follow, i.e. you can have T23.3, but not T23.3:04. There must be // one digit, but the max number of digits is implemenation defined. We // currently allow up to 16 digits of fractional seconds only. While we // support 16 fractional digits we only parse the first seven, anything // past that is considered a zero. This is to stay compatible with the // DateTime implementation which is limited to this resolution. if (source.Length < 16) { // Source does not have enough characters for YYYY-MM-DDThh:mm return false; } // Parse THH:MM (e.g. "T10:32") if (source[10] != JsonConstants.TimePrefix || source[13] != JsonConstants.Colon || !TryGetNextTwoDigits(source.Slice(start: 11, length: 2), ref parseData.Hour) || !TryGetNextTwoDigits(source.Slice(start: 14, length: 2), ref parseData.Minute)) { return false; } // We now have YYYY-MM-DDThh:mm Debug.Assert(source.Length >= 16); if (source.Length == 16) { return true; } byte curByte = source[16]; int sourceIndex = 17; // Either a TZD ['Z'|'+'|'-'] or a seconds separator [':'] is valid at this point switch (curByte) { case JsonConstants.UtcOffsetToken: parseData.OffsetToken = JsonConstants.UtcOffsetToken; return sourceIndex == source.Length; case JsonConstants.Plus: case JsonConstants.Hyphen: parseData.OffsetToken = curByte; return ParseOffset(ref parseData, source.Slice(sourceIndex)); case JsonConstants.Colon: break; default: return false; } // Try reading the seconds if (source.Length < 19 || !TryGetNextTwoDigits(source.Slice(start: 17, length: 2), ref parseData.Second)) { return false; } // We now have YYYY-MM-DDThh:mm:ss Debug.Assert(source.Length >= 19); if (source.Length == 19) { return true; } curByte = source[19]; sourceIndex = 20; // Either a TZD ['Z'|'+'|'-'] or a seconds decimal fraction separator ['.'] is valid at this point switch (curByte) { case JsonConstants.UtcOffsetToken: parseData.OffsetToken = JsonConstants.UtcOffsetToken; return sourceIndex == source.Length; case JsonConstants.Plus: case JsonConstants.Hyphen: parseData.OffsetToken = curByte; return ParseOffset(ref parseData, source.Slice(sourceIndex)); case JsonConstants.Period: break; default: return false; } // Source does not have enough characters for second fractions (i.e. ".s") // YYYY-MM-DDThh:mm:ss.s if (source.Length < 21) { return false; } // Parse fraction. This value should never be greater than 9_999_999 { int numDigitsRead = 0; int fractionEnd = Math.Min(sourceIndex + JsonConstants.DateTimeParseNumFractionDigits, source.Length); while (sourceIndex < fractionEnd && IsDigit(curByte = source[sourceIndex])) { if (numDigitsRead < JsonConstants.DateTimeNumFractionDigits) { parseData.Fraction = (parseData.Fraction * 10) + (int)(curByte - (uint)'0'); numDigitsRead++; } sourceIndex++; } if (parseData.Fraction != 0) { while (numDigitsRead < JsonConstants.DateTimeNumFractionDigits) { parseData.Fraction *= 10; numDigitsRead++; } } } // We now have YYYY-MM-DDThh:mm:ss.s Debug.Assert(sourceIndex <= source.Length); if (sourceIndex == source.Length) { return true; } curByte = source[sourceIndex++]; // TZD ['Z'|'+'|'-'] is valid at this point switch (curByte) { case JsonConstants.UtcOffsetToken: parseData.OffsetToken = JsonConstants.UtcOffsetToken; return sourceIndex == source.Length; case JsonConstants.Plus: case JsonConstants.Hyphen: parseData.OffsetToken = curByte; return ParseOffset(ref parseData, source.Slice(sourceIndex)) && true; default: return false; } static bool ParseOffset(ref DateTimeParseData parseData, ReadOnlySpan<byte> offsetData) { // Parse the hours for the offset if (offsetData.Length < 2 || !TryGetNextTwoDigits(offsetData.Slice(0, 2), ref parseData.OffsetHours)) { return false; } // We now have YYYY-MM-DDThh:mm:ss.s+|-hh if (offsetData.Length == 2) { // Just hours offset specified return true; } // Ensure we have enough for ":mm" if (offsetData.Length != 5 || offsetData[2] != JsonConstants.Colon || !TryGetNextTwoDigits(offsetData.Slice(3), ref parseData.OffsetMinutes)) { return false; } return true; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryGetNextTwoDigits(ReadOnlySpan<byte> source, ref int value) { Debug.Assert(source.Length == 2); uint digit1 = source[0] - (uint)'0'; uint digit2 = source[1] - (uint)'0'; if (digit1 > 9 || digit2 > 9) { value = default; return false; } value = (int)(digit1 * 10 + digit2); return true; } // The following methods are borrowed verbatim from src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.Helpers.cs /// <summary> /// Overflow-safe DateTimeOffset factory. /// </summary> private static bool TryCreateDateTimeOffset(DateTime dateTime, ref DateTimeParseData parseData, out DateTimeOffset value) { if (((uint)parseData.OffsetHours) > JsonConstants.MaxDateTimeUtcOffsetHours) { value = default; return false; } if (((uint)parseData.OffsetMinutes) > 59) { value = default; return false; } if (parseData.OffsetHours == JsonConstants.MaxDateTimeUtcOffsetHours && parseData.OffsetMinutes != 0) { value = default; return false; } long offsetTicks = (((long)parseData.OffsetHours) * 3600 + ((long)parseData.OffsetMinutes) * 60) * TimeSpan.TicksPerSecond; if (parseData.OffsetNegative) { offsetTicks = -offsetTicks; } try { value = new DateTimeOffset(ticks: dateTime.Ticks, offset: new TimeSpan(ticks: offsetTicks)); } catch (ArgumentOutOfRangeException) { // If we got here, the combination of the DateTime + UTC offset strayed outside the 1..9999 year range. This case seems rare enough // that it's better to catch the exception rather than replicate DateTime's range checking (which it's going to do anyway.) value = default; return false; } return true; } /// <summary> /// Overflow-safe DateTimeOffset factory. /// </summary> private static bool TryCreateDateTimeOffset(ref DateTimeParseData parseData, out DateTimeOffset value) { if (!TryCreateDateTime(parseData, kind: DateTimeKind.Unspecified, out DateTime dateTime)) { value = default; return false; } if (!TryCreateDateTimeOffset(dateTime: dateTime, ref parseData, out value)) { value = default; return false; } return true; } /// <summary> /// Overflow-safe DateTimeOffset/Local time conversion factory. /// </summary> private static bool TryCreateDateTimeOffsetInterpretingDataAsLocalTime(DateTimeParseData parseData, out DateTimeOffset value) { if (!TryCreateDateTime(parseData, DateTimeKind.Local, out DateTime dateTime)) { value = default; return false; } try { value = new DateTimeOffset(dateTime); } catch (ArgumentOutOfRangeException) { // If we got here, the combination of the DateTime + UTC offset strayed outside the 1..9999 year range. This case seems rare enough // that it's better to catch the exception rather than replicate DateTime's range checking (which it's going to do anyway.) value = default; return false; } return true; } /// <summary> /// Overflow-safe DateTime factory. /// </summary> private static bool TryCreateDateTime(DateTimeParseData parseData, DateTimeKind kind, out DateTime value) { if (parseData.Year == 0) { value = default; return false; } Debug.Assert(parseData.Year <= 9999); // All of our callers to date parse the year from fixed 4-digit fields so this value is trusted. if ((((uint)parseData.Month) - 1) >= 12) { value = default; return false; } uint dayMinusOne = ((uint)parseData.Day) - 1; if (dayMinusOne >= 28 && dayMinusOne >= DateTime.DaysInMonth(parseData.Year, parseData.Month)) { value = default; return false; } if (((uint)parseData.Hour) > 23) { value = default; return false; } if (((uint)parseData.Minute) > 59) { value = default; return false; } // This needs to allow leap seconds when appropriate. // See https://github.com/dotnet/corefx/issues/39185. if (((uint)parseData.Second) > 59) { value = default; return false; } Debug.Assert(parseData.Fraction >= 0 && parseData.Fraction <= JsonConstants.MaxDateTimeFraction); // All of our callers to date parse the fraction from fixed 7-digit fields so this value is trusted. int[] days = DateTime.IsLeapYear(parseData.Year) ? s_daysToMonth366 : s_daysToMonth365; int yearMinusOne = parseData.Year - 1; int totalDays = (yearMinusOne * 365) + (yearMinusOne / 4) - (yearMinusOne / 100) + (yearMinusOne / 400) + days[parseData.Month - 1] + parseData.Day - 1; long ticks = totalDays * TimeSpan.TicksPerDay; int totalSeconds = (parseData.Hour * 3600) + (parseData.Minute * 60) + parseData.Second; ticks += totalSeconds * TimeSpan.TicksPerSecond; ticks += parseData.Fraction; value = new DateTime(ticks: ticks, kind: kind); return true; } private static readonly int[] s_daysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; private static readonly int[] s_daysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace ServantHR.Api.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; 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); } } } }
using OpenKh.Engine.Input; using OpenKh.Engine.Renderers; using OpenKh.Game.Infrastructure; using System.Collections.Generic; using System.Linq; namespace OpenKh.Game.Menu { public class MainMenu : MenuBase { private const int MaxCharacterCount = 4; private const int MaxMenuElementCount = 8; private const int CharacterHpBar = 98; private const int CharacterMpBar = 99; private const int MsgLv = 0x39FC; private const int MsgHp = 0x39FD; private const int MsgMp = 0x39FE; private static readonly ushort[] MenuOptions = new ushort[MaxMenuElementCount] { 0x844b, // Items 0x844d, // Abilities 0x8451, // Customize 0x844e, // Party 0x844f, // Status 0x8450, // Journal 0x8450, // Journal 0xb617, // Config }; private static readonly ushort[] CharacterNames = new ushort[MaxCharacterCount] { 0x851f, // Sora 0x8520, // Donald 0x8521, // Goofy 0x852c, // Riku }; private IAnimatedSequence _backgroundSeq; private IAnimatedSequence _menuSeq; private IAnimatedSequence _characterSeq; private int _optionCount = 0; private int _optionSelected = 0; private bool _isDebugMenuVisible; public override ushort MenuNameId => 0; protected override bool IsEnd => _backgroundSeq.IsEnd && _menuSeq.IsEnd && _characterSeq.IsEnd; public int SelectedOption { get => _optionSelected; set { if (_optionCount == 0) return; _optionSelected = value; if (_optionSelected < 0) _optionSelected += _optionCount; _optionSelected %= _optionCount; InvalidateMenu(); } } public bool IsDebugMenuVisible { get => _isDebugMenuVisible; set { if (_isDebugMenuVisible != value) { _isDebugMenuVisible = value; InvalidateMenu(); } } } public MainMenu(IMenuManager menuManager) : base(menuManager) { InitializeMenu(); } private void InvalidateMenu() { var frame = _menuSeq.FrameIndex; _menuSeq = InitializeMenuOptions(true); _menuSeq.Begin(); _menuSeq.FrameIndex = frame; } private void InitializeMenu() { _backgroundSeq = SequenceFactory.Create(new AnimatedSequenceDesc { SequenceIndexStart = 46, SequenceIndexLoop = 47, SequenceIndexEnd = 48, }); _menuSeq = InitializeMenuOptions(); _characterSeq = SequenceFactory.Create(Enumerable.Range(0, 5) .Select(i => new AnimatedSequenceDesc { SequenceIndexStart = 101, SequenceIndexLoop = 102, SequenceIndexEnd = 103, StackIndex = i + 1, StackWidth = AnimatedSequenceDesc.DefaultStacking, Children = new List<AnimatedSequenceDesc>() { new AnimatedSequenceDesc { SequenceIndexLoop = 93, Children = new List<AnimatedSequenceDesc>() { new AnimatedSequenceDesc { SequenceIndexLoop = 124, MessageText = "Donald", Flags = AnimationFlags.TextIgnoreColor, TextAnchor = TextAnchor.BottomCenter, }, new AnimatedSequenceDesc() { SequenceIndexLoop = 90, Children = new List<AnimatedSequenceDesc>() { new AnimatedSequenceDesc { SequenceIndexLoop = 124, MessageId = MsgLv, TextAnchor = TextAnchor.BottomLeft, }, new AnimatedSequenceDesc { SequenceIndexLoop = 124, MessageText = "99", TextAnchor = TextAnchor.BottomRight, }, new AnimatedSequenceDesc() { StackIndex = 1, SequenceIndexLoop = 121, MessageId = MsgHp, TextAnchor = TextAnchor.BottomLeft, }, new AnimatedSequenceDesc() { StackIndex = 1, SequenceIndexLoop = 121, MessageText = "60/60", TextAnchor = TextAnchor.BottomRight, }, new AnimatedSequenceDesc() { StackIndex = 1, SequenceIndexLoop = CharacterHpBar, TextAnchor = TextAnchor.BottomLeft, }, new AnimatedSequenceDesc() { StackIndex = 2, SequenceIndexLoop = 118, MessageId = MsgMp, TextAnchor = TextAnchor.BottomLeft, }, new AnimatedSequenceDesc() { StackIndex = 2, SequenceIndexLoop = 118, MessageText = "120/120", TextAnchor = TextAnchor.BottomRight, }, new AnimatedSequenceDesc() { StackIndex = 2, SequenceIndexLoop = CharacterMpBar, TextAnchor = TextAnchor.BottomLeft, }, } }, } } } }) ); } protected override void ProcessInput(IInput input) { if (input.Repeated.Up) SelectedOption--; if (input.Repeated.Down) SelectedOption++; if (input.Triggered.Confirm) { switch (SelectedOption) { case 4: Push(new MenuStatus(MenuManager)); break; case 6: if (_isDebugMenuVisible) Push(new MenuDebug(MenuManager)); else Push(new MenuConfig(MenuManager)); break; default: Push(new MenuTemplate(MenuManager, 0)); break; } } else if (input.Triggered.Cancel) MenuManager.CloseAllMenu(); IsDebugMenuVisible = input.Pressed.R2; } private IAnimatedSequence InitializeMenuOptions(bool skipIntro = false) { const int MenuOptionsBitfields = 0xbf; var menuDesc = new List<AnimatedSequenceDesc>(); var menuOptions = MenuOptionsBitfields; _optionCount = 0; for (int bitIndex = 0; menuOptions > 0; bitIndex++) { var bitMask = 1 << bitIndex; if ((menuOptions & bitMask) == 0) continue; menuOptions -= bitMask; if (_optionCount >= MenuOptions.Length) break; string overrideTextField = null; if (bitIndex == 7 && _isDebugMenuVisible) overrideTextField = MenuDebug.Name; AnimatedSequenceDesc desc = _optionCount != _optionSelected ? new AnimatedSequenceDesc { SequenceIndexStart = skipIntro ? -1 : 133, SequenceIndexLoop = 134, SequenceIndexEnd = 135, StackIndex = _optionCount, StackWidth = 0, StackHeight = AnimatedSequenceDesc.DefaultStacking, MessageId = MenuOptions[bitIndex], MessageText = overrideTextField, Flags = AnimationFlags.TextTranslateX, } : new AnimatedSequenceDesc { SequenceIndexLoop = 132, SequenceIndexEnd = 135, StackIndex = _optionCount, StackWidth = 0, StackHeight = AnimatedSequenceDesc.DefaultStacking, MessageId = MenuOptions[bitIndex], MessageText = overrideTextField, Flags = AnimationFlags.TextTranslateX | AnimationFlags.ChildStackHorizontally, Children = new List<AnimatedSequenceDesc> { new AnimatedSequenceDesc { SequenceIndexLoop = 25, TextAnchor = TextAnchor.BottomLeft, Flags = AnimationFlags.NoChildTranslationX, }, new AnimatedSequenceDesc { SequenceIndexStart = skipIntro ? -1 : 27, SequenceIndexLoop = 28, SequenceIndexEnd = 29, } } }; menuDesc.Add(desc); _optionCount++; } return SequenceFactory.Create(menuDesc); } public override void Open() { _backgroundSeq.Begin(); _menuSeq.Begin(); _characterSeq.Begin(); base.Open(); } public override void Close() { _backgroundSeq.End(); _menuSeq.End(); _characterSeq.End(); base.Close(); } protected override void MyUpdate(double deltaTime) { _backgroundSeq.Update(deltaTime); _menuSeq.Update(deltaTime); _characterSeq.Update(deltaTime); } protected override void MyDraw() { _backgroundSeq.Draw(0, 0); _menuSeq.Draw(0, 0); _characterSeq.Draw(0, 0); } } }
// 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 Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Dsa.Tests { public partial class DSASignVerify { [Fact] public static void Fips186_2_1() { // http://csrc.nist.gov/groups/STM/cavp/documents/dss/186-2dsatestvectors.zip // SigGen.txt, first case const string p = "f5422387a66acb198173f466e987ca692fd2337af0ed1ec7aa5f2e2088d0742c" + "2d41ded76317001ca4044115f00aff09ad59d49b07c35ec2b25088be17ac391a" + "f17575d52c232153df94f0023a0a17ca29d8548dfa08c5f034bad0bd4511ffae" + "6b3c504c6f728d31d1e92aad9e88382a8a42b050441a747bb71dd84cb01d9ee7"; const string q = "f4a9d1750b46e27c3af7587c5d019ffc99f11f25"; const string g = "7400ad91528a6c9e891f3f5fce7496ef4d01bf91a979736547049406ab4a2d2f" + "e49fa3730cfb86a5af3ff21f5022f07e4ee0c15a88b8bd7b5f0bf8dea3863afb" + "4f1cac16aba490d93f44be79c1cd01ce2e12dfdb75c593d64e5bf97e839526db" + "cc0288cd3beb2fd7941f67d138faa88f9de90901efdc752569a4d1afbd193846"; const string x = "485e8ad4a4e49a85e0397af0bb115df175ead894"; const string y = "ec86482ea1c463198d074bad01790283fb8866e53ab5e821219f0f4a25e7d047" + "3f9cbd2ab7348625d322ea7f09ec9a15bbcc5a9ff1f3692392768970e9e86554" + "5d3aa2934148f6d0a6ec410a16d5059c58ce428912f532cbc8f9bbbcf3657367" + "d159212c11afd856587b1b092ab1bdae3c443661e6ba27078d03eb31e63e5922"; const string msg = "96452f7f94b9cc004931df8f8118be7e56f16a1502e00934f16c96391b83d724" + "90be8ffa54e7f6676eb966a63ce657a6095f8d65e1cf90a0a4685daf5ae35bab" + "c6c290d13ed9152bba0cc76d2a5a401d0d1b06f63f85018f12753338a16da324" + "61d89acef996129554b46ca9f47b612b89ad3b90c20b4547631a809b982797da"; const string r = "ed4715b8d218d31b7adf0bea5165777a7414315e"; const string s = "29c70a036aa83eb0742f1fa3f56ccead0fc0f61d"; Validate(p, q, g, x, y, msg, r, s, HashAlgorithmName.SHA1); } [ConditionalFact(nameof(SupportsFips186_3))] public static void Fips186_3_L1024_N160_SHA256_1() { // http://csrc.nist.gov/groups/STM/cavp/documents/dss/186-3dsatestvectors.zip // SigGen.txt // [mod = L=1024, N=160, SHA-256], first case const string p = "cba13e533637c37c0e80d9fcd052c1e41a88ac325c4ebe13b7170088d54eef48" + "81f3d35eae47c210385a8485d2423a64da3ffda63a26f92cf5a304f39260384a" + "9b7759d8ac1adc81d3f8bfc5e6cb10efb4e0f75867f4e848d1a338586dd0648f" + "eeb163647ffe7176174370540ee8a8f588da8cc143d939f70b114a7f981b8483"; const string q = "95031b8aa71f29d525b773ef8b7c6701ad8a5d99"; const string g = "45bcaa443d4cd1602d27aaf84126edc73bd773de6ece15e97e7fef46f13072b7" + "adcaf7b0053cf4706944df8c4568f26c997ee7753000fbe477a37766a4e970ff" + "40008eb900b9de4b5f9ae06e06db6106e78711f3a67feca74dd5bddcdf675ae4" + "014ee9489a42917fbee3bb9f2a24df67512c1c35c97bfbf2308eaacd28368c5c"; const string x = "2eac4f4196fedb3e651b3b00040184cfd6da2ab4"; const string y = "4cd6178637d0f0de1488515c3b12e203a3c0ca652f2fe30d088dc7278a87affa" + "634a727a721932d671994a958a0f89223c286c3a9b10a96560542e2626b72e0c" + "d28e5133fb57dc238b7fab2de2a49863ecf998751861ae668bf7cad136e6933f" + "57dfdba544e3147ce0e7370fa6e8ff1de690c51b4aeedf0485183889205591e8"; const string msg = "812172f09cbae62517804885754125fc6066e9a902f9db2041eeddd7e8da67e4" + "a2e65d0029c45ecacea6002f9540eb1004c883a8f900fd84a98b5c449ac49c56" + "f3a91d8bed3f08f427935fbe437ce46f75cd666a0707265c61a096698dc2f36b" + "28c65ec7b6e475c8b67ddfb444b2ee6a984e9d6d15233e25e44bd8d7924d129d"; const string r = "76683a085d6742eadf95a61af75f881276cfd26a"; const string s = "3b9da7f9926eaaad0bebd4845c67fcdb64d12453"; Validate(p, q, g, x, y, msg, r, s, HashAlgorithmName.SHA256); } [ConditionalFact(nameof(SupportsFips186_3))] public static void Fips186_3_L1024_N160_SHA384_1() { // http://csrc.nist.gov/groups/STM/cavp/documents/dss/186-3dsatestvectors.zip // SigGen.txt // [mod = L=1024, N=160, SHA-384], first case const string p = "f24a4afc72c7e373a3c30962332fe5405c45930963909418c30792aaf135ddea" + "561e94f24726716b75a18828982e4ce44c1fddcb746487b6b77a9a5a17f868ab" + "50cd621b5bc9da470880b287d7398190a42a5ee22ed8d1ff147e2019810c8298" + "ed68e1ca69d41d555f249e649fb1725ddb075c17b37beff467fdd1609243373f"; const string q = "da065a078ddb56ee5d2ad06cafab20820d2c4755"; const string g = "47b5591b79043e4e03ca78a0e277c9a21e2a6b543bf4f044104cd9ac93eff8e1" + "01bb6031efc8c596d5d2f92e3a3d0f1f74702dd54f77d3cd46c04dee7a5de9f0" + "0ad317691fddcefe4a220a2651acae7fcedda92bfcca855db6705e8d864f8192" + "bf6bf860c00f08ad6493ecc1872e0028d5c86d44505db57422515c3825a6f78a"; const string x = "649820168eb594f59cd9b28b9aefe8cc106a6c4f"; const string y = "43a27b740f422cb2dc3eaa232315883a2f6a22927f997d024f5a638b507b17d3" + "b1cbd3ec691cc674470960a0146efdecb95bb5fe249749e3c806cd5cc3e7f7ba" + "b845dadbe1f50b3366fb827a942ce6246dda7bd2c13e1b4a926c0c82c8846395" + "52d9d46036f9a4bc2a9e51c2d76e3074d1f53a63224c4279e0fa460474d4ffde"; const string msg = "b0dbbf4a421ba5c5b0e52f09629801c113258c252f29898c3354706e39ec5824" + "be523d0e2f8cfe022cd61165301274d5d621a59755f50404d8b802371ce616de" + "fa962e3636ae934ec34e4bcf77a16c7eff8cf4cc08a0f4849d6ad4307e9f8df8" + "3f24ad16ab46d1a61d2d7d4e21681eb2ae281a1a5f9bca8573a3f5281d308a5a"; const string r = "77c4d99f62b3ad7dd1fe6498db45a5da73ce7bde"; const string s = "23871a002ae503fdabaa6a84dcc8f38769737f01"; Validate(p, q, g, x, y, msg, r, s, HashAlgorithmName.SHA384); } [ConditionalFact(nameof(SupportsFips186_3))] public static void Fips186_3_L1024_N160_SHA384_4() { // http://csrc.nist.gov/groups/STM/cavp/documents/dss/186-3dsatestvectors.zip // SigGen.txt // [mod = L=1024, N=160, SHA-384], fourth case (s=00....) const string p = "f24a4afc72c7e373a3c30962332fe5405c45930963909418c30792aaf135ddea" + "561e94f24726716b75a18828982e4ce44c1fddcb746487b6b77a9a5a17f868ab" + "50cd621b5bc9da470880b287d7398190a42a5ee22ed8d1ff147e2019810c8298" + "ed68e1ca69d41d555f249e649fb1725ddb075c17b37beff467fdd1609243373f"; const string q = "da065a078ddb56ee5d2ad06cafab20820d2c4755"; const string g = "47b5591b79043e4e03ca78a0e277c9a21e2a6b543bf4f044104cd9ac93eff8e1" + "01bb6031efc8c596d5d2f92e3a3d0f1f74702dd54f77d3cd46c04dee7a5de9f0" + "0ad317691fddcefe4a220a2651acae7fcedda92bfcca855db6705e8d864f8192" + "bf6bf860c00f08ad6493ecc1872e0028d5c86d44505db57422515c3825a6f78a"; const string x = "bb318987a043158b97fdbbc2707471a38316ce58"; const string y = "c9003995b014afad66de25fc0a2210b1f1b22d275da51a27faacda042fd76456" + "86ec8b1b62d58d8af2e1063ab8e146d11e3a07710bc4521228f35f5173443bbf" + "d089f642cd16641c57199c9ab6e0d9b0c01931c2d162f5e20dbe7365c93adc62" + "fd5a461bea5956d7c11ac67647bedcead5bb311224a496aa155992aee74e45ad"; const string msg = "36a25659a7f1de66b4721b48855cdebe98fe6113241b7beddc2691493ed0add0" + "b6a9fbbf9fb870a1bc68a901b932f47ded532f93493b1c081408165807b38efc" + "e7acc7dbc216bef74ed59e20973326553cc83779f742e3f469a7278eeb1537dd" + "71cd8f15114d84693c2e6bbf62814a08e82ba71539f4cb4bf08c869d7db9dea9"; const string r = "17cc53b5b9558cc41df946055b8d7e1971be86d7"; const string s = "003c21503971c03b5ef4edc804d2f7d33f9ea9cc"; Validate(p, q, g, x, y, msg, r, s, HashAlgorithmName.SHA384); } [ConditionalFact(nameof(SupportsFips186_3))] public static void Fips186_3_L1024_N160_SHA512_1() { // http://csrc.nist.gov/groups/STM/cavp/documents/dss/186-3dsatestvectors.zip // SigGen.txt // [mod = L=1024, N=160, SHA-512], first case const string p = "88d968e9602ecbda6d86f7c970a3ffbeb1da962f28c0afb9270ef05bc330ca98" + "c3adf83c072feb05fb2e293b5065bbb0cbcc930c24d8d07869deaecd92a2604c" + "0f5dd35c5b431fda6a222c52c3562bf7571c710209be8b3b858818788725fe81" + "12b7d6bc82e0ff1cbbf5d6fe94690af2b510e41ad8207dc2c02fb9fa5cefaab5"; const string q = "a665689b9e5b9ce82fd1676006cf4cf67ecc56b7"; const string g = "267e282857417752113fba3fca7155b5ce89e7c8a33c1a29122e2b720965fc04" + "245267ff87fc67a5730fe5b308013aa3266990fbb398185a87e055b443a868ce" + "0ce13ae6aee330b9d25d3bbb362665c5881daf0c5aa75e9d4a82e8f04c91a9ad" + "294822e33978ab0c13fadc45831f9d37da4efa0fc2c5eb01371fa85b7ddb1f82"; const string x = "07ce8862e64b7f6c7482046dbfc93907123e5214"; const string y = "60f5341e48ca7a3bc5decee61211dd2727cd8e2fc7635f3aabea262366e458f5" + "c51c311afda916cb0dcdc5d5a5729f573a532b594743199bcfa7454903e74b33" + "ddfe65896306cec20ebd8427682fa501ee06bc4c5d1425cbe31828ba008b19c9" + "da68136cf71840b205919e783a628a5a57cf91cf569b2854ffef7a096eda96c9"; const string msg = "3a84a5314e90fd33bb7cd6ca68720c69058da1da1b359046ae8922cac8afc5e0" + "25771635fb4735491521a728441b5cb087d60776ee0ecc2174a41985a82cf46d" + "8f8d8b274a0cc439b00971077c745f8cf701cf56bf9914cc57209b555dc87ca8" + "c13da063270c60fc2c988e692b75a7f2a669903b93d2e14e8efb6fb9f8694a78"; const string r = "a53f1f8f20b8d3d4720f14a8bab5226b079d9953"; const string s = "11f53f6a4e56b51f60e20d4957ae89e162aea616"; Validate(p, q, g, x, y, msg, r, s, HashAlgorithmName.SHA512); } [ConditionalFact(nameof(SupportsFips186_3))] public static void Fips186_3_L1024_N160_SHA512_4() { // http://csrc.nist.gov/groups/STM/cavp/documents/dss/186-3dsatestvectors.zip // SigGen.txt // [mod = L=1024, N=160, SHA-512], fourth case (r=000....) const string p = "88d968e9602ecbda6d86f7c970a3ffbeb1da962f28c0afb9270ef05bc330ca98" + "c3adf83c072feb05fb2e293b5065bbb0cbcc930c24d8d07869deaecd92a2604c" + "0f5dd35c5b431fda6a222c52c3562bf7571c710209be8b3b858818788725fe81" + "12b7d6bc82e0ff1cbbf5d6fe94690af2b510e41ad8207dc2c02fb9fa5cefaab5"; const string q = "a665689b9e5b9ce82fd1676006cf4cf67ecc56b7"; const string g = "267e282857417752113fba3fca7155b5ce89e7c8a33c1a29122e2b720965fc04" + "245267ff87fc67a5730fe5b308013aa3266990fbb398185a87e055b443a868ce" + "0ce13ae6aee330b9d25d3bbb362665c5881daf0c5aa75e9d4a82e8f04c91a9ad" + "294822e33978ab0c13fadc45831f9d37da4efa0fc2c5eb01371fa85b7ddb1f82"; const string msg = "16250c74ccb40443625a37c4b7e2b3615255768241f254a506fa819efbb8698a" + "de38fc75946b3af09055578f28a181827dda311bd4038fd47f6d86cceb1bbbef" + "2df20bf595a0ad77afd39c84877434ade3812f05ec541e0403abadc778d116fd" + "077c95c6ec0f47241f4db813f31986b7504c1cd9ddb496ac6ed22b45e7df72cc"; const string x = "3fee04cc08624f3a7f34c538d87692209dd74797"; const string y = "6e8c85150c5c9ca6dcb04806671db1b672fc1087c995311d7087ad12ab18f2c1" + "4b612cea13bf79518d2b570b8b696b3e4efcd0fda522a253bbcb7dbb711d984c" + "598fa201c21a8a9e2774bc15020920cd8c27c2875c779b08ef95093caac2c9ce" + "a37ec498c23dd24b684abcb467ec952a202cbd2df7960c1ef929cc2b611ca6c8"; const string r = "00018f0fdc16d914971c8f310f1af7796c6f662a"; const string s = "62b7aecc75cbc6db00dd0c24339f7bdb5ae966a5"; Validate(p, q, g, x, y, msg, r, s, HashAlgorithmName.SHA512); } [ConditionalFact(nameof(SupportsFips186_3))] public static void Fips186_3_L2048_N256_SHA256_1() { // http://csrc.nist.gov/groups/STM/cavp/documents/dss/186-3dsatestvectors.zip // SigGen.txt // [mod = L=2048, N=256, SHA-256], first case const string p = "a8adb6c0b4cf9588012e5deff1a871d383e0e2a85b5e8e03d814fe13a059705e" + "663230a377bf7323a8fa117100200bfd5adf857393b0bbd67906c081e585410e" + "38480ead51684dac3a38f7b64c9eb109f19739a4517cd7d5d6291e8af20a3fbf" + "17336c7bf80ee718ee087e322ee41047dabefbcc34d10b66b644ddb3160a28c0" + "639563d71993a26543eadb7718f317bf5d9577a6156561b082a10029cd44012b" + "18de6844509fe058ba87980792285f2750969fe89c2cd6498db3545638d5379d" + "125dccf64e06c1af33a6190841d223da1513333a7c9d78462abaab31b9f96d5f" + "34445ceb6309f2f6d2c8dde06441e87980d303ef9a1ff007e8be2f0be06cc15f"; const string q = "e71f8567447f42e75f5ef85ca20fe557ab0343d37ed09edc3f6e68604d6b9dfb"; const string g = "5ba24de9607b8998e66ce6c4f812a314c6935842f7ab54cd82b19fa104abfb5d" + "84579a623b2574b37d22ccae9b3e415e48f5c0f9bcbdff8071d63b9bb956e547" + "af3a8df99e5d3061979652ff96b765cb3ee493643544c75dbe5bb39834531952" + "a0fb4b0378b3fcbb4c8b5800a5330392a2a04e700bb6ed7e0b85795ea38b1b96" + "2741b3f33b9dde2f4ec1354f09e2eb78e95f037a5804b6171659f88715ce1a9b" + "0cc90c27f35ef2f10ff0c7c7a2bb0154d9b8ebe76a3d764aa879af372f4240de" + "8347937e5a90cec9f41ff2f26b8da9a94a225d1a913717d73f10397d2183f1ba" + "3b7b45a68f1ff1893caf69a827802f7b6a48d51da6fbefb64fd9a6c5b75c4561"; const string x = "446969025446247f84fdea74d02d7dd13672b2deb7c085be11111441955a377b"; const string y = "5a55dceddd1134ee5f11ed85deb4d634a3643f5f36dc3a70689256469a0b651a" + "d22880f14ab85719434f9c0e407e60ea420e2a0cd29422c4899c416359dbb1e5" + "92456f2b3cce233259c117542fd05f31ea25b015d9121c890b90e0bad033be13" + "68d229985aac7226d1c8c2eab325ef3b2cd59d3b9f7de7dbc94af1a9339eb430" + "ca36c26c46ecfa6c5481711496f624e188ad7540ef5df26f8efacb820bd17a1f" + "618acb50c9bc197d4cb7ccac45d824a3bf795c234b556b06aeb9291734532520" + "84003f69fe98045fe74002ba658f93475622f76791d9b2623d1b5fff2cc16844" + "746efd2d30a6a8134bfc4c8cc80a46107901fb973c28fc553130f3286c1489da"; const string msg = "4e3a28bcf90d1d2e75f075d9fbe55b36c5529b17bc3a9ccaba6935c9e2054825" + "5b3dfae0f91db030c12f2c344b3a29c4151c5b209f5e319fdf1c23b190f64f1f" + "e5b330cb7c8fa952f9d90f13aff1cb11d63181da9efc6f7e15bfed4862d1a62c" + "7dcf3ba8bf1ff304b102b1ec3f1497dddf09712cf323f5610a9d10c3d9132659"; const string r = "633055e055f237c38999d81c397848c38cce80a55b649d9e7905c298e2a51447"; const string s = "2bbf68317660ec1e4b154915027b0bc00ee19cfc0bf75d01930504f2ce10a8b0"; Validate(p, q, g, x, y, msg, r, s, HashAlgorithmName.SHA256); } [ConditionalFact(nameof(SupportsFips186_3))] public static void Fips186_3_L2048_N256_SHA384_1() { // http://csrc.nist.gov/groups/STM/cavp/documents/dss/186-3dsatestvectors.zip // SigGen.txt // [mod = L=2048, N=256, SHA-384], first case const string p = "a6167c16fff74e29342b8586aed3cd896f7b1635a2286ff16fdff41a06317ca6" + "b05ca2ba7c060ad6db1561621ccb0c40b86a03619bfff32e204cbd90b79dcb5f" + "86ebb493e3bd1988d8097fa23fa4d78fb3cddcb00c466423d8fa719873c37645" + "fe4eecc57171bbedfe56fa9474c96385b8ba378c79972d7aaae69a2ba64cde8e" + "5654f0f7b74550cd3447e7a472a33b4037db468dde31c348aa25e82b7fc41b83" + "7f7fc226a6103966ecd8f9d14c2d3149556d43829f137451b8d20f8520b0ce8e" + "3d705f74d0a57ea872c2bdee9714e0b63906cddfdc28b6777d19325000f8ed52" + "78ec5d912d102109319cba3b6469d4672909b4f0dbeec0bbb634b551ba0cf213"; const string q = "8427529044d214c07574f7b359c2e01c23fd97701b328ac8c1385b81c5373895"; const string g = "6fc232415c31200cf523af3483f8e26ace808d2f1c6a8b863ab042cc7f6b7144" + "b2d39472c3cb4c7681d0732843503d8f858cbe476e6740324aaa295950105978" + "c335069b919ff9a6ff4b410581b80712fe5d3e04ddb4dfd26d5e7fbca2b0c52d" + "8d404343d57b2f9b2a26daa7ece30ceab9e1789f9751aaa9387049965af32650" + "c6ca5b374a5ae70b3f98e053f51857d6bbb17a670e6eaaf89844d641e1e13d5a" + "1b24d053dc6b8fd101c624786951927e426310aba9498a0042b3dc7bbc59d705" + "f80d9b807de415f7e94c5cf9d789992d3bb8336d1d808cb86b56dde09d934bb5" + "27033922de14bf307376ab7d22fbcd616f9eda479ab214a17850bdd0802a871c"; const string x = "459eb1588e9f7dd4f286677a7415cb25a1b46e7a7cfadc8a45100383e20da69d"; const string y = "5ca7151bca0e457bbc46f59f71d81ab16688dc0eb7e4d17b166c3326c5b12c5b" + "debb3613224d1a754023c50b83cb5ecc139096cef28933b3b12ca31038e40893" + "83597c59cc27b902be5da62cae7da5f4af90e9410ed1604082e2e38e25eb0b78" + "dfac0aeb2ad3b19dc23539d2bcd755db1cc6c9805a7dd109e1c98667a5b9d52b" + "21c2772121b8d0d2b246e5fd3da80728e85bbf0d7067d1c6baa64394a29e7fcb" + "f80842bd4ab02b35d83f59805a104e0bd69d0079a065f59e3e6f21573a00da99" + "0b72ea537fa98caaa0a58800a7e7a0623e263d4fca65ebb8eded46efdfe7db92" + "c9ebd38062d8f12534f015b186186ee2361d62c24e4f22b3e95da0f9062ce04d"; const string msg = "8c78cffdcf25d8230b835b30512684c9b252115870b603d1b4ba2eb5d35b33f2" + "6d96b684126ec34fff67dfe5c8c856acfe3a9ff45ae11d415f30449bcdc3bf9a" + "9fb5a7e48afeaba6d0b0fc9bce0197eb2bf7a840249d4e550c5a25dc1c71370e" + "67933edad2362fae6fad1efba5c08dc1931ca2841b44b78c0c63a1665ffac860"; const string r = "4fd8f25c059030027381d4167c3174b6be0088c15f0a573d7ebd05960f5a1eb2"; const string s = "5f56869cee7bf64fec5d5d6ea15bb1fa1169003a87eccc1621b90a1b892226f2"; Validate(p, q, g, x, y, msg, r, s, HashAlgorithmName.SHA384); } [ConditionalFact(nameof(SupportsFips186_3))] public static void Fips186_3_L2048_N256_SHA1_1() { // http://csrc.nist.gov/groups/STM/cavp/documents/dss/186-3dsatestvectors.zip // SigGen.txt // [mod = L=2048, N=256, SHA-1, first case const string p = "c1a59d215573949e0b20a974c2edf2e3137ff2463062f75f1d13df12aba1076b" + "b2d013402b60af6c187fb0fa362167c976c2617c726f9077f09e18c11b60f650" + "08825bd6c02a1f57d3eb0ad41cd547de43d87f2525f971d42b306506e7ca03be" + "63b35f4ada172d0a06924440a14250d7822ac2d5aeafed4619e79d4158a7d5eb" + "2d9f023db181a8f094b2c6cb87cb8535416ac19813f07144660c557745f44a01" + "c6b1029092c129b0d27183e82c5a21a80177ee7476eb95c466fb472bd3d2dc28" + "6ce25847e93cbfa9ad39cc57035d0c7b64b926a9c7f5a7b2bc5abcbfbdc0b0e3" + "fede3c1e02c44afc8aefc7957da07a0e5fd12339db8667616f62286df80d58ab"; const string q = "8000000000000000000000001bd62c65e8b87c89797f8f0cbfa55e4a6810e2c7"; const string g = "aea5878740f1424d3c6ea9c6b4799615d2749298a17e26207f76cef340ddd390" + "e1b1ad6b6c0010ad015a103342ddd452cac024b36e42d9b8ed52fafae7a1d3ce" + "9e4b21f910d1356eb163a3e5a8184c781bf14492afa2e4b0a56d8884fd01a628" + "b9662739c42e5c5795ade2f5f27e6de1d963917ce8806fc40d021cd87aa3aa3a" + "9e4f0c2c4c45d2959b2578b2fb1a2229c37e181059b9d5e7b7862fa82e2377a4" + "9ed0f9dca820a5814079dd6610714efaf8b0cc683d8e72e4c884e6f9d4946b3e" + "8d4cbb92adbbe7d4c47cc30be7f8c37ca81883a1aac6860059ff4640a29ccae7" + "3de20b12e63b00a88b2ee9ba94b75eb40a656e15d9ec83731c85d0effcb9ef9f"; const string msg = "de3605dbefde353cbe05e0d6098647b6d041460dfd4c000312be1afe7551fd3b" + "93fed76a9763c34e004564b8f7dcacbd99e85030632c94e9b0a032046523b7aa" + "cdf934a2dbbdcfceefe66b4e3d1cb29e994ff3a4648a8edd9d58ed71f12399d9" + "0624789c4e0eebb0fbd5080f7d730f875a1f290749334cb405e9fd2ae1b4ed65"; const string x = "5a42e77248358f06ae980a2c64f6a22bea2bf7b4fc0015745053c432b7132a67"; const string y = "880e17c4ae8141750609d8251c0bbd7acf6d0b460ed3688e9a5f990e6c4b5b00" + "875da750e0228a04102a35f57e74b8d2f9b6950f0d1db8d302c5c90a5b8786a8" + "2c68ff5b17a57a758496c5f8053e4484a253d9942204d9a1109f4bd2a3ec311a" + "60cf69c685b586d986f565d33dbf5aab7091e31aa4102c4f4b53fbf872d70015" + "6465b6c075e7f778471a23502dc0fee41b271c837a1c26691699f3550d060a33" + "1099f64837cddec69caebf51bf4ec9f36f2a220fe773cb4d3c02d0446ddd4613" + "3532ef1c3c69d432e303502bd05a75279a7809a742ac4a7872b07f1908654049" + "419350e37a95f2ef33361d8d8736d4083dc14c0bb972e14d4c7b97f3ddfccaef"; const string r = "363e01c564f380a27d7d23b207af3f961d48fc0995487f60052775d724ab3d10"; const string s = "4916d91b2927294e429d537c06dd2463d1845018cca2873e90a6c837b445fdde"; Validate(p, q, g, x, y, msg, r, s, HashAlgorithmName.SHA1); } [ConditionalFact(nameof(SupportsFips186_3))] public static void Fips186_3_L2048_N256_SHA384_3() { // http://csrc.nist.gov/groups/STM/cavp/documents/dss/186-3dsatestvectors.zip // SigGen.txt // [mod = L=2048, N=256, SHA-384], third case (r=00...) const string p = "a6167c16fff74e29342b8586aed3cd896f7b1635a2286ff16fdff41a06317ca6" + "b05ca2ba7c060ad6db1561621ccb0c40b86a03619bfff32e204cbd90b79dcb5f" + "86ebb493e3bd1988d8097fa23fa4d78fb3cddcb00c466423d8fa719873c37645" + "fe4eecc57171bbedfe56fa9474c96385b8ba378c79972d7aaae69a2ba64cde8e" + "5654f0f7b74550cd3447e7a472a33b4037db468dde31c348aa25e82b7fc41b83" + "7f7fc226a6103966ecd8f9d14c2d3149556d43829f137451b8d20f8520b0ce8e" + "3d705f74d0a57ea872c2bdee9714e0b63906cddfdc28b6777d19325000f8ed52" + "78ec5d912d102109319cba3b6469d4672909b4f0dbeec0bbb634b551ba0cf213"; const string q = "8427529044d214c07574f7b359c2e01c23fd97701b328ac8c1385b81c5373895"; const string g = "6fc232415c31200cf523af3483f8e26ace808d2f1c6a8b863ab042cc7f6b7144" + "b2d39472c3cb4c7681d0732843503d8f858cbe476e6740324aaa295950105978" + "c335069b919ff9a6ff4b410581b80712fe5d3e04ddb4dfd26d5e7fbca2b0c52d" + "8d404343d57b2f9b2a26daa7ece30ceab9e1789f9751aaa9387049965af32650" + "c6ca5b374a5ae70b3f98e053f51857d6bbb17a670e6eaaf89844d641e1e13d5a" + "1b24d053dc6b8fd101c624786951927e426310aba9498a0042b3dc7bbc59d705" + "f80d9b807de415f7e94c5cf9d789992d3bb8336d1d808cb86b56dde09d934bb5" + "27033922de14bf307376ab7d22fbcd616f9eda479ab214a17850bdd0802a871c"; const string x = "6ba8f6638316dd804a24b7390f31023cd8b26e9325be90941b90d5fd3155115a"; const string y = "10e6f50fd6dbb1ca16f2df5132a4a4eabc51da4a58fe619b2225d7adab0cea3a" + "fc2db90b158b6231c8b0774e0f0d9074517f336ca053ae115671aee3c1de0f85" + "728cff99deebc07ffc9a63631989a9277e64c54d9c25a7e739ae92f706ee237b" + "98b8700a9df0de12d2124e2cfd81d9ec7b0469ee3a718ab15305de099d9a2f8c" + "ecb79527d016447c8f6fe4905c3718ce5234d13bf4edd7169b9d0db9a6b0fc77" + "b7d53bdd32b07dc15bc829620db085114581608ac9e0937752095951d289855d" + "0bcc9d421b945cc4f37f80b0cb25f1ffee9c61e567f49d21f889ecbc3f4ed337" + "bca666ba3ba684874c883fe228ac44952a8513e12d9f0c4ed43c9b60f35225b2"; const string msg = "4f1c0053984ab55a491f3618db1be2379174a4385974825fcbe584e2b6d0702a" + "bb8298dd9184eef1740b90a5eae850e9452b4e4ab219e187860f0fb4ad2be390" + "ef2ba7d76cdedcaf10aeaf4f25e497b4da951375b687a8d67012d3f99c7b5ca8" + "2e9bd0630dffcd635ecd8209cddb872da5bf4736309783345a35376b4fce4b91"; const string r = "006b759fb718c34f1a6e518f834053b9f1825dd3eb8d719465c7bcc830322f4b"; const string s = "47fa59852c9ae5e181381e3457a33b25420011d6f911efa90f3eaced1dee1329"; Validate(p, q, g, x, y, msg, r, s, HashAlgorithmName.SHA384); } [ConditionalFact(nameof(SupportsFips186_3))] public static void Fips186_3_L3072_N256_SHA256_1() { // http://csrc.nist.gov/groups/STM/cavp/documents/dss/186-3dsatestvectors.zip // SigGen.txt // [mod = L=3072, N=256, SHA-256], first case const string p = "c7b86d7044218e367453d210e76433e4e27a983db1c560bb9755a8fb7d819912" + "c56cfe002ab1ff3f72165b943c0b28ed46039a07de507d7a29f738603decd127" + "0380a41f971f2592661a64ba2f351d9a69e51a888a05156b7fe1563c4b77ee93" + "a44949138438a2ab8bdcfc49b4e78d1cde766e54984760057d76cd740c94a4dd" + "25a46aa77b18e9d707d6738497d4eac364f4792d9766a16a0e234807e96b8c64" + "d404bbdb876e39b5799ef53fe6cb9bab62ef19fdcc2bdd905beda13b9ef7ac35" + "f1f557cb0dc458c019e2bc19a9f5dfc1e4eca9e6d466564124304a31f038605a" + "3e342da01be1c2b545610edd2c1397a3c8396588c6329efeb4e165af5b368a39" + "a88e4888e39f40bb3de4eb1416672f999fead37aef1ca9643ff32cdbc0fcebe6" + "28d7e46d281a989d43dd21432151af68be3f6d56acfbdb6c97d87fcb5e6291bf" + "8b4ee1275ae0eb4383cc753903c8d29f4adb6a547e405decdff288c5f6c7aa30" + "dcb12f84d392493a70933317c0f5e6552601fae18f17e6e5bb6bf396d32d8ab9"; const string q = "876fa09e1dc62b236ce1c3155ba48b0ccfda29f3ac5a97f7ffa1bd87b68d2a4b"; const string g = "110afebb12c7f862b6de03d47fdbc3326e0d4d31b12a8ca95b2dee2123bcc667" + "d4f72c1e7209767d2721f95fbd9a4d03236d54174fbfaff2c4ff7deae4738b20" + "d9f37bf0a1134c288b420af0b5792e47a92513c0413f346a4edbab2c45bdca13" + "f5341c2b55b8ba54932b9217b5a859e553f14bb8c120fbb9d99909dff5ea68e1" + "4b379964fd3f3861e5ba5cc970c4a180eef54428703961021e7bd68cb637927b" + "8cbee6805fa27285bfee4d1ef70e02c1a18a7cd78bef1dd9cdad45dde9cd6907" + "55050fc4662937ee1d6f4db12807ccc95bc435f11b71e7086048b1dab5913c60" + "55012de82e43a4e50cf93feff5dcab814abc224c5e0025bd868c3fc592041bba" + "04747c10af513fc36e4d91c63ee5253422cf4063398d77c52fcb011427cbfcfa" + "67b1b2c2d1aa4a3da72645cb1c767036054e2f31f88665a54461c885fb3219d5" + "ad8748a01158f6c7c0df5a8c908ba8c3e536822428886c7b500bbc15b49df746" + "b9de5a78fe3b4f6991d0110c3cbff458039dc36261cf46af4bc2515368f4abb7"; const string x = "3470832055dade94e14cd8777171d18e5d06f66aeff4c61471e4eba74ee56164"; const string y = "456a105c713566234838bc070b8a751a0b57767cb75e99114a1a46641e11da1f" + "a9f22914d808ad7148612c1ea55d25301781e9ae0c9ae36a69d87ba039ec7cd8" + "64c3ad094873e6e56709fd10d966853d611b1cff15d37fdee424506c184d62c7" + "033358be78c2250943b6f6d043d63b317de56e5ad8d1fd97dd355abe96452f8e" + "435485fb3b907b51900aa3f24418df50b4fcdafbf6137548c39373b8bc4ba3da" + "bb4746ebd17b87fcd6a2f197c107b18ec5b465e6e4cb430d9c0ce78da5988441" + "054a370792b730da9aba41a3169af26176f74e6f7c0c9c9b55b62bbe7ce38d46" + "95d48157e660c2acb63f482f55418150e5fee43ace84c540c3ba7662ae80835c" + "1a2d51890ea96ba206427c41ef8c38aa07d2a365e7e58380d8f4782e22ac2101" + "af732ee22758337b253637838e16f50f56d313d07981880d685557f7d79a6db8" + "23c61f1bb3dbc5d50421a4843a6f29690e78aa0f0cff304231818b81fc4a243f" + "c00f09a54c466d6a8c73d32a55e1abd5ec8b4e1afa32a79b01df85a81f3f5cfe"; const string msg = "cb06e02234263c22b80e832d6dc5a1bee5ea8af3bc2da752441c04027f176158" + "bfe68372bd67f84d489c0d49b07d4025962976be60437be1a2d01d3be0992afa" + "5abe0980e26a9da4ae72f827b423665195cc4eed6fe85c335b32d9c03c945a86" + "e7fa99373f0a30c6eca938b3afb6dff67adb8bece6f8cfec4b6a12ea281e2323"; const string r = "53bae6c6f336e2eb311c1e92d95fc449a929444ef81ec4279660b200d59433de"; const string s = "49f3a74e953e77a7941af3aefeef4ed499be209976a0edb3fa5e7cb961b0c112"; Validate(p, q, g, x, y, msg, r, s, HashAlgorithmName.SHA256); } [ConditionalFact(nameof(SupportsFips186_3))] public static void Fips186_3_L3072_N256_SHA384_1() { // http://csrc.nist.gov/groups/STM/cavp/documents/dss/186-3dsatestvectors.zip // SigGen.txt // [mod = L=3072, N=256, SHA-384], first case const string p = "a410d23ed9ad9964d3e401cb9317a25213f75712acbc5c12191abf3f1c0e723e" + "2333b49eb1f95b0f9748d952f04a5ae358859d384403ce364aa3f58dd9769909" + "b45048548c55872a6afbb3b15c54882f96c20df1b2df164f0bac849ca17ad2df" + "63abd75c881922e79a5009f00b7d631622e90e7fa4e980618575e1d6bd1a72d5" + "b6a50f4f6a68b793937c4af95fc11541759a1736577d9448b87792dff0723241" + "5512e933755e12250d466e9cc8df150727d747e51fea7964158326b1365d580c" + "b190f4518291598221fdf36c6305c8b8a8ed05663dd7b006e945f592abbecae4" + "60f77c71b6ec649d3fd5394202ed7bbbd040f7b8fd57cb06a99be254fa25d71a" + "3760734046c2a0db383e02397913ae67ce65870d9f6c6f67a9d00497be1d763b" + "21937cf9cbf9a24ef97bbcaa07916f8894e5b7fb03258821ac46140965b23c54" + "09ca49026efb2bf95bce025c4183a5f659bf6aaeef56d7933bb29697d7d54134" + "8c871fa01f869678b2e34506f6dc0a4c132b689a0ed27dc3c8d53702aa584877"; const string q = "abc67417725cf28fc7640d5de43825f416ebfa80e191c42ee886303338f56045"; const string g = "867d5fb72f5936d1a14ed3b60499662f3124686ef108c5b3da6663a0e86197ec" + "2cc4c9460193a74ff16028ac9441b0c7d27c2272d483ac7cd794d598416c4ff9" + "099a61679d417d478ce5dd974bf349a14575afe74a88b12dd5f6d1cbd3f91ddd" + "597ed68e79eba402613130c224b94ac28714a1f1c552475a5d29cfcdd8e08a6b" + "1d65661e28ef313514d1408f5abd3e06ebe3a7d814d1ede316bf495273ca1d57" + "4f42b482eea30db53466f454b51a175a0b89b3c05dda006e719a2e6371669080" + "d768cc038cdfb8098e9aad9b8d83d4b759f43ac9d22b353ed88a33723550150d" + "e0361b7a376f37b45d437f71cb711f2847de671ad1059516a1d45755224a15d3" + "7b4aeada3f58c69a136daef0636fe38e3752064afe598433e80089fda24b144a" + "462734bef8f77638845b00e59ce7fa4f1daf487a2cada11eaba72bb23e1df6b6" + "6a183edd226c440272dd9b06bec0e57f1a0822d2e00212064b6dba64562085f5" + "a75929afa5fe509e0b78e630aaf12f91e4980c9b0d6f7e059a2ea3e23479d930"; const string x = "6d4c934391b7f6fb6e19e3141f8c0018ef5726118a11064358c7d35b37737377"; const string y = "1f0a5c75e7985d6e70e4fbfda51a10b925f6accb600d7c6510db90ec367b93bb" + "069bd286e8f979b22ef0702f717a8755c18309c87dae3fe82cc3dc8f4b7aa3d5" + "f3876f4d4b3eb68bfe910c43076d6cd0d39fc88dde78f09480db55234e6c8ca5" + "9fe2700efec04feee6b4e8ee2413721858be7190dbe905f456edcab55b2dc291" + "6dc1e8731988d9ef8b619abcf8955aa960ef02b3f02a8dc649369222af50f133" + "8ed28d667f3f10cae2a3c28a3c1d08df639c81ada13c8fd198c6dae3d62a3fe9" + "f04c985c65f610c06cb8faea68edb80de6cf07a8e89c00218185a952b23572e3" + "4df07ce5b4261e5de427eb503ee1baf5992db6d438b47434c40c22657bc163e7" + "953fa33eff39dc2734607039aadd6ac27e4367131041f845ffa1a13f556bfba2" + "307a5c78f2ccf11298c762e08871968e48dc3d1569d09965cd09da43cf0309a1" + "6af1e20fee7da3dc21b364c4615cd5123fa5f9b23cfc4ffd9cfdcea670623840" + "b062d4648d2eba786ad3f7ae337a4284324ace236f9f7174fbf442b99043002f"; const string msg = "ed9a64d3109ef8a9292956b946873ca4bd887ce624b81be81b82c69c67aaddf5" + "655f70fe4768114db2834c71787f858e5165da1a7fa961d855ad7e5bc4b7be31" + "b97dbe770798ef7966152b14b86ae35625a28aee5663b9ef3067cbdfbabd8719" + "7e5c842d3092eb88dca57c6c8ad4c00a19ddf2e1967b59bd06ccaef933bc28e7"; const string r = "7695698a14755db4206e850b4f5f19c540b07d07e08aac591e20081646e6eedc"; const string s = "3dae01154ecff7b19007a953f185f0663ef7f2537f0b15e04fb343c961f36de2"; Validate(p, q, g, x, y, msg, r, s, HashAlgorithmName.SHA384); } [ConditionalFact(nameof(SupportsFips186_3))] public static void Fips186_3_L3072_N256_SHA512_1() { // http://csrc.nist.gov/groups/STM/cavp/documents/dss/186-3dsatestvectors.zip // SigGen.txt // [mod = L=3072, N=256, SHA-512], first case const string p = "c1d0a6d0b5ed615dee76ac5a60dd35ecb000a202063018b1ba0a06fe7a00f765" + "db1c59a680cecfe3ad41475badb5ad50b6147e2596b88d34656052aca79486ea" + "6f6ec90b23e363f3ab8cdc8b93b62a070e02688ea877843a4685c2ba6db111e9" + "addbd7ca4bce65bb10c9ceb69bf806e2ebd7e54edeb7f996a65c907b50efdf8e" + "575bae462a219c302fef2ae81d73cee75274625b5fc29c6d60c057ed9e7b0d46" + "ad2f57fe01f823230f31422722319ce0abf1f141f326c00fbc2be4cdb8944b6f" + "d050bd300bdb1c5f4da72537e553e01d51239c4d461860f1fb4fd8fa79f5d526" + "3ff62fed7008e2e0a2d36bf7b9062d0d75db226c3464b67ba24101b085f2c670" + "c0f87ae530d98ee60c5472f4aa15fb25041e19106354da06bc2b1d322d40ed97" + "b21fd1cdad3025c69da6ce9c7ddf3dcf1ea4d56577bfdec23071c1f05ee4077b" + "5391e9a404eaffe12d1ea62d06acd6bf19e91a158d2066b4cd20e4c4e52ffb1d" + "5204cd022bc7108f2c799fb468866ef1cb09bce09dfd49e4740ff8140497be61"; const string q = "bf65441c987b7737385eadec158dd01614da6f15386248e59f3cddbefc8e9dd1"; const string g = "c02ac85375fab80ba2a784b94e4d145b3be0f92090eba17bd12358cf3e03f437" + "9584f8742252f76b1ede3fc37281420e74a963e4c088796ff2bab8db6e9a4530" + "fc67d51f88b905ab43995aab46364cb40c1256f0466f3dbce36203ef228b35e9" + "0247e95e5115e831b126b628ee984f349911d30ffb9d613b50a84dfa1f042ba5" + "36b82d5101e711c629f9f2096dc834deec63b70f2a2315a6d27323b995aa20d3" + "d0737075186f5049af6f512a0c38a9da06817f4b619b94520edfac85c4a6e2e1" + "86225c95a04ec3c3422b8deb284e98d24b31465802008a097c25969e826c2baa" + "59d2cba33d6c1d9f3962330c1fcda7cfb18508fea7d0555e3a169daed353f3ee" + "6f4bb30244319161dff6438a37ca793b24bbb1b1bc2194fc6e6ef60278157899" + "cb03c5dd6fc91a836eb20a25c09945643d95f7bd50d206684d6ffc14d16d82d5" + "f781225bff908392a5793b803f9b70b4dfcb394f9ed81c18e391a09eb3f93a03" + "2d81ba670cabfd6f64aa5e3374cb7c2029f45200e4f0bfd820c8bd58dc5eeb34"; const string x = "150b5c51ea6402276bc912322f0404f6d57ff7d32afcaa83b6dfde11abb48181"; const string y = "6da54f2b0ddb4dcce2da1edfa16ba84953d8429ce60cd111a5c65edcf7ba5b8d" + "9387ab6881c24880b2afbdb437e9ed7ffb8e96beca7ea80d1d90f24d54611262" + "9df5c9e9661742cc872fdb3d409bc77b75b17c7e6cfff86261071c4b5c9f9898" + "be1e9e27349b933c34fb345685f8fc6c12470d124cecf51b5d5adbf5e7a2490f" + "8d67aac53a82ed6a2110686cf631c348bcbc4cf156f3a6980163e2feca72a45f" + "6b3d68c10e5a2283b470b7292674490383f75fa26ccf93c0e1c8d0628ca35f2f" + "3d9b6876505d118988957237a2fc8051cb47b410e8b7a619e73b1350a9f6a260" + "c5f16841e7c4db53d8eaa0b4708d62f95b2a72e2f04ca14647bca6b5e3ee707f" + "cdf758b925eb8d4e6ace4fc7443c9bc5819ff9e555be098aa055066828e21b81" + "8fedc3aac517a0ee8f9060bd86e0d4cce212ab6a3a243c5ec0274563353ca710" + "3af085e8f41be524fbb75cda88903907df94bfd69373e288949bd0626d85c139" + "8b3073a139d5c747d24afdae7a3e745437335d0ee993eef36a3041c912f7eb58"; const string msg = "494180eed0951371bbaf0a850ef13679df49c1f13fe3770b6c13285bf3ad93dc" + "4ab018aab9139d74200808e9c55bf88300324cc697efeaa641d37f3acf72d8c9" + "7bff0182a35b940150c98a03ef41a3e1487440c923a988e53ca3ce883a2fb532" + "bb7441c122f1dc2f9d0b0bc07f26ba29a35cdf0da846a9d8eab405cbf8c8e77f"; const string r = "a40a6c905654c55fc58e99c7d1a3feea2c5be64823d4086ce811f334cfdc448d"; const string s = "6478050977ec585980454e0a2f26a03037b921ca588a78a4daff7e84d49a8a6c"; Validate(p, q, g, x, y, msg, r, s, HashAlgorithmName.SHA512); } [ConditionalFact(nameof(SupportsFips186_3))] public static void Fips186_3_L3072_N256_SHA512_12() { // http://csrc.nist.gov/groups/STM/cavp/documents/dss/186-3dsatestvectors.zip // SigGen.txt // [mod = L=3072, N=256, SHA-512], twelfth case (y=00...) const string p = "c1d0a6d0b5ed615dee76ac5a60dd35ecb000a202063018b1ba0a06fe7a00f765" + "db1c59a680cecfe3ad41475badb5ad50b6147e2596b88d34656052aca79486ea" + "6f6ec90b23e363f3ab8cdc8b93b62a070e02688ea877843a4685c2ba6db111e9" + "addbd7ca4bce65bb10c9ceb69bf806e2ebd7e54edeb7f996a65c907b50efdf8e" + "575bae462a219c302fef2ae81d73cee75274625b5fc29c6d60c057ed9e7b0d46" + "ad2f57fe01f823230f31422722319ce0abf1f141f326c00fbc2be4cdb8944b6f" + "d050bd300bdb1c5f4da72537e553e01d51239c4d461860f1fb4fd8fa79f5d526" + "3ff62fed7008e2e0a2d36bf7b9062d0d75db226c3464b67ba24101b085f2c670" + "c0f87ae530d98ee60c5472f4aa15fb25041e19106354da06bc2b1d322d40ed97" + "b21fd1cdad3025c69da6ce9c7ddf3dcf1ea4d56577bfdec23071c1f05ee4077b" + "5391e9a404eaffe12d1ea62d06acd6bf19e91a158d2066b4cd20e4c4e52ffb1d" + "5204cd022bc7108f2c799fb468866ef1cb09bce09dfd49e4740ff8140497be61"; const string q = "bf65441c987b7737385eadec158dd01614da6f15386248e59f3cddbefc8e9dd1"; const string g = "c02ac85375fab80ba2a784b94e4d145b3be0f92090eba17bd12358cf3e03f437" + "9584f8742252f76b1ede3fc37281420e74a963e4c088796ff2bab8db6e9a4530" + "fc67d51f88b905ab43995aab46364cb40c1256f0466f3dbce36203ef228b35e9" + "0247e95e5115e831b126b628ee984f349911d30ffb9d613b50a84dfa1f042ba5" + "36b82d5101e711c629f9f2096dc834deec63b70f2a2315a6d27323b995aa20d3" + "d0737075186f5049af6f512a0c38a9da06817f4b619b94520edfac85c4a6e2e1" + "86225c95a04ec3c3422b8deb284e98d24b31465802008a097c25969e826c2baa" + "59d2cba33d6c1d9f3962330c1fcda7cfb18508fea7d0555e3a169daed353f3ee" + "6f4bb30244319161dff6438a37ca793b24bbb1b1bc2194fc6e6ef60278157899" + "cb03c5dd6fc91a836eb20a25c09945643d95f7bd50d206684d6ffc14d16d82d5" + "f781225bff908392a5793b803f9b70b4dfcb394f9ed81c18e391a09eb3f93a03" + "2d81ba670cabfd6f64aa5e3374cb7c2029f45200e4f0bfd820c8bd58dc5eeb34"; const string x = "bd3006cf5d3ac04a8a5128140df6025d9942d78544e9b27efe28b2ca1f79e313"; const string y = "00728e23e74bb82de0e1315d58164a5cecc8951d89e88da702f5b878020fd8d2" + "a1791b3e8ab770e084ac2397d297971ca8708a30a4097d86740153ee2db6ab63" + "43c5b6cc2c8a7fa59082a8d659931cc48a0433a033dbb2fff3aa545686f922c7" + "063da1d52d9688142ec64a1002948e5da89165d9df8eed9aa469b61ee0210b40" + "33562333097ba8659944e5f7924e04a21bc3edc6d551e202e4c543e97518f91e" + "0cab49111029b29c3aa1bed5f35e5c90feb9d3c745953dbf859defce4537b4a0" + "9801fdc8fe6999fbde39908079811b4b992c2e8333b9f800ea0d9f0a5f53607e" + "308942e68efef01e03d7cca6f196872bf01f436d4a8e05fc59d8fbc6b88a166f" + "57a4e99d67ddaece844653be77819747dd2e07d581c518cb9779e9f7960c17ff" + "0bae710ecf575b09591b013b4805c88b235df262e61a4c94f46bf9a08284611d" + "f44eadd94f44cef6225a808e211e4d3af5e96bce64a90f8013874f10749a8382" + "a6026a855d90853440bfce31f258b3a258f7b5e659b43e702dee7c24c02d2284"; const string msg = "baeb12a1ebd8057a99a0137ee60f60eed10d26f1eab22ae2d9adbc3e5ffc3252" + "abf62b614707ad2546141bed779f0cfad9544a74e562da549e2f7b286efb6154" + "49b0946dc7c498d8f12150b2eacbd27157966f592ad5f3e43a24c60b7e06630b" + "82a4fdb699119dbd878b13a98bf22a7b3dc7efdd992ce6b8a950e61299c5663b"; const string r = "8d357b0b956fb90e8e0b9ff284cedc88a04d171a90c5997d8ee1e9bc4d0b35ff"; const string s = "ab37329c50145d146505015704fdc4fb0fd7207e0b11d8becbad934e6255c30c"; Validate(p, q, g, x, y, msg, r, s, HashAlgorithmName.SHA512); } private static void Validate( string p, string q, string g, string x, string y, string msg, string r, string s, HashAlgorithmName hashAlgorithm) { // Public+Private key using (DSA dsa = DSAFactory.Create()) { dsa.ImportParameters( new DSAParameters { P = p.HexToByteArray(), Q = q.HexToByteArray(), G = g.HexToByteArray(), X = x.HexToByteArray(), Y = y.HexToByteArray(), }); byte[] message = msg.HexToByteArray(); byte[] signature = (r + s).HexToByteArray(); Assert.True(dsa.VerifyData(message, signature, hashAlgorithm), "Public+Private Valid Signature"); signature[0] ^= 0xFF; Assert.False(dsa.VerifyData(message, signature, hashAlgorithm), "Public+Private Tampered Signature"); } // Public only using (DSA dsa = DSAFactory.Create()) { dsa.ImportParameters( new DSAParameters { P = p.HexToByteArray(), Q = q.HexToByteArray(), G = g.HexToByteArray(), X = null, Y = y.HexToByteArray(), }); byte[] message = msg.HexToByteArray(); byte[] signature = (r + s).HexToByteArray(); Assert.True(dsa.VerifyData(message, signature, hashAlgorithm), "Public-Only Valid Signature"); signature[0] ^= 0xFF; Assert.False(dsa.VerifyData(message, signature, hashAlgorithm), "Public-Only Tampered Signature"); } } } }
/* * Magix - A Web Application Framework for Humans * Copyright 2010 - 2014 - thomas@magixilluminate.com * Magix is licensed as MITx11, see enclosed License.txt File for Details. */ using System; using System.IO; using System.Web; using System.Threading; using System.Collections.Generic; using Magix.Core; namespace Magix.execute { /* * contains logic for loading, saving and loading files */ public class FilesCore : ActiveController { private static string _basePath; static FilesCore() { _basePath = HttpContext.Current.Server.MapPath("~"); } /* * returns base path for application */ [ActiveEvent(Name = "magix.file.get-base-path")] public static void magix_file_get_base_path(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params); if (ShouldInspect(e.Params)) { AppendInspectFromResource( ip["inspect"], "Magix.file", "Magix.file.hyperlisp.inspect.hl", "[magix.file.get-base-path-dox].value"); AppendCodeFromResource( ip, "Magix.file", "Magix.file.hyperlisp.inspect.hl", "[magix.file.get-base-path-sample]"); return; } ip["path"].Value = _basePath.Trim('/'); } /* * lists all files in directory */ [ActiveEvent(Name = "magix.file.list-files")] public static void magix_file_list_files(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params); if (ShouldInspect(e.Params)) { AppendInspectFromResource( ip["inspect"], "Magix.file", "Magix.file.hyperlisp.inspect.hl", "[magix.file.list-files-dox].value"); AppendCodeFromResource( ip, "Magix.file", "Magix.file.hyperlisp.inspect.hl", "[magix.file.list-files-sample]"); return; } Node dp = Dp(e.Params); string dir = ip.ContainsValue("directory") ? Expressions.GetFormattedExpression("directory", e.Params, "").TrimStart('/') : ""; string filter = ip.ContainsValue("filter") ? Expressions.GetExpressionValue<string>(ip["filter"].Get<string>(), dp, ip, false) : null; string[] files = null; bool absolutePath = true; if (!dir.Contains(":")) { dir = _basePath + dir; absolutePath = false; } if (string.IsNullOrEmpty(filter)) files = Directory.GetFiles(dir); else { List<string> searchPatterns = new List<string>(filter.Split(';')); List<string> filesList = new List<string>(); foreach (string idxPattern in searchPatterns) { filesList.AddRange(Directory.GetFiles(dir, idxPattern)); } files = filesList.ToArray(); } string rootDir = _basePath; foreach (string idxFile in files) { string fileName = idxFile; if (!absolutePath) fileName = idxFile.Substring(rootDir.Length); fileName = fileName.Replace("\\", "/"); ip["files"][fileName].Value = null; } } /* * loads a file from disc, relatively from the root of the web application */ [ActiveEvent(Name = "magix.file.load")] public static void magix_file_load(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params); if (ShouldInspect(ip)) { AppendInspectFromResource( ip["inspect"], "Magix.file", "Magix.file.hyperlisp.inspect.hl", "[magix.file.load-dox].value"); AppendCodeFromResource( ip, "Magix.file", "Magix.file.hyperlisp.inspect.hl", "[magix.file.load-sample]"); return; } Node dp = Dp(e.Params); if (!ip.ContainsValue("file")) throw new ArgumentException("you need to supply which file to load as the [file] parameter"); string filepath = Expressions.GetFormattedExpression("file", e.Params, ""); if (filepath.StartsWith("plugin:")) { string activeEvent = filepath.Substring(7); RaiseActiveEvent( activeEvent, e.Params); } else { using (TextReader reader = File.OpenText(_basePath + filepath)) { ip["value"].Value = reader.ReadToEnd(); } } } /* * saves a file to disc, relatively from the root of the web application */ [ActiveEvent(Name = "magix.file.save")] [ActiveEvent(Name = "magix.file.delete")] public static void magix_file_save(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params); if (ShouldInspect(ip)) { AppendInspectFromResource( ip["inspect"], "Magix.file", "Magix.file.hyperlisp.inspect.hl", "[magix.file.save-dox].value"); AppendCodeFromResource( ip, "Magix.file", "Magix.file.hyperlisp.inspect.hl", "[magix.file.save-sample]"); return; } Node dp = Dp(e.Params); string file = Expressions.GetFormattedExpression("file", e.Params, null); if (string.IsNullOrEmpty(file)) throw new ArgumentException("you need to define which file to save, as [file]"); if (!file.Contains(":")) file = _basePath + file; // changing its attributes before if it is read only if (File.Exists(file) && new FileInfo(file).IsReadOnly) File.SetAttributes(file, FileAttributes.Normal); if (ip.ContainsValue("value")) { string fileContent = Expressions.GetExpressionValue<string>(ip["value"].Get<string>(), dp, ip, false); using (Stream fileStream = File.Open(file, FileMode.Create)) { using (TextWriter writer = new StreamWriter(fileStream)) { writer.Write(fileContent); } } } else { // deletes an existing file File.Delete(file); } } /* * moves the given file */ [ActiveEvent(Name = "magix.file.move-file")] public static void magix_file_move_file(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params); if (ShouldInspect(ip)) { AppendInspectFromResource( ip["inspect"], "Magix.file", "Magix.file.hyperlisp.inspect.hl", "[magix.file.move-file-dox].value"); AppendCodeFromResource( ip, "Magix.file", "Magix.file.hyperlisp.inspect.hl", "[magix.file.move-file-sample]"); return; } Node dp = Dp(e.Params); if (!ip.ContainsValue("from")) throw new ArgumentException("you need to tell the engine which file to move as the value of the [from]"); string from = Expressions.GetFormattedExpression("from", e.Params, ""); if (!from.Contains(":")) from = _basePath + from; if (!ip.ContainsValue("to")) throw new ArgumentException("you need to define where to move file to, as [to] node"); string to = Expressions.GetFormattedExpression("to", e.Params, ""); if (!to.Contains(":")) to = _basePath + to; if (File.Exists(to)) { if (new FileInfo(to).IsReadOnly) File.SetAttributes(to, FileAttributes.Normal); File.Delete(to); } File.Move(from, to); } /* * moves the given file */ [ActiveEvent(Name = "magix.file.copy-file")] public static void magix_file_copy_file(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params); if (ShouldInspect(ip)) { AppendInspectFromResource( ip["inspect"], "Magix.file", "Magix.file.hyperlisp.inspect.hl", "[magix.file.copy-file-dox].value"); AppendCodeFromResource( ip, "Magix.file", "Magix.file.hyperlisp.inspect.hl", "[magix.file.copy-file-sample]"); return; } Node dp = Dp(e.Params); if (!ip.ContainsValue("from")) throw new ArgumentException("you need to tell the engine which file to copy as the value of the [from]"); string from = Expressions.GetFormattedExpression("from", e.Params, ""); if (!from.Contains(":")) from = _basePath + from; if (!ip.ContainsValue("to")) throw new ArgumentException("you need to define which file to copy to, as [to] node"); string to = Expressions.GetFormattedExpression("to", e.Params, ""); if (!to.Contains(":")) to = _basePath + to; File.Copy(from, to, true); } /* * return true if directory exists */ [ActiveEvent(Name = "magix.file.file-exist")] public static void magix_file_file_exist(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params); if (ShouldInspect(ip)) { AppendInspectFromResource( ip["inspect"], "Magix.file", "Magix.file.hyperlisp.inspect.hl", "[magix.file.file-exist-dox].value"); AppendCodeFromResource( ip, "Magix.file", "Magix.file.hyperlisp.inspect.hl", "[magix.file.file-exist-sample]"); return; } Node dp = Dp(e.Params); if (!ip.ContainsValue("file")) throw new ArgumentException("you didn't supply a [file] for [file-exist]"); string file = Expressions.GetFormattedExpression("file", e.Params, ""); if (!file.Contains(":")) file = _basePath + file; ip["value"].Value = File.Exists(file); } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.IO; using DiscUtils.Streams; namespace DiscUtils.Ntfs { internal class ClusterBitmap : IDisposable { private Bitmap _bitmap; private readonly File _file; private bool _fragmentedDiskMode; private long _nextDataCluster; public ClusterBitmap(File file) { _file = file; _bitmap = new Bitmap( _file.OpenStream(AttributeType.Data, null, FileAccess.ReadWrite), MathUtilities.Ceil(file.Context.BiosParameterBlock.TotalSectors64, file.Context.BiosParameterBlock.SectorsPerCluster)); } internal Bitmap Bitmap { get { return _bitmap; } } public void Dispose() { if (_bitmap != null) { _bitmap.Dispose(); _bitmap = null; } } /// <summary> /// Allocates clusters from the disk. /// </summary> /// <param name="count">The number of clusters to allocate.</param> /// <param name="proposedStart">The proposed start cluster (or -1).</param> /// <param name="isMft"><c>true</c> if this attribute is the $MFT\$DATA attribute.</param> /// <param name="total">The total number of clusters in the file, including this allocation.</param> /// <returns>The list of cluster allocations.</returns> public Tuple<long, long>[] AllocateClusters(long count, long proposedStart, bool isMft, long total) { List<Tuple<long, long>> result = new List<Tuple<long, long>>(); long numFound = 0; long totalClusters = _file.Context.RawStream.Length / _file.Context.BiosParameterBlock.BytesPerCluster; if (isMft) { // First, try to extend the existing cluster run (if available) if (proposedStart >= 0) { numFound += ExtendRun(count - numFound, result, proposedStart, totalClusters); } // The MFT grows sequentially across the disk if (numFound < count && !_fragmentedDiskMode) { numFound += FindClusters(count - numFound, result, 0, totalClusters, isMft, true, 0); } if (numFound < count) { numFound += FindClusters(count - numFound, result, 0, totalClusters, isMft, false, 0); } } else { // First, try to extend the existing cluster run (if available) if (proposedStart >= 0) { numFound += ExtendRun(count - numFound, result, proposedStart, totalClusters); } // Try to find a contiguous range if (numFound < count && !_fragmentedDiskMode) { numFound += FindClusters(count - numFound, result, totalClusters / 8, totalClusters, isMft, true, total / 4); } if (numFound < count) { numFound += FindClusters(count - numFound, result, totalClusters / 8, totalClusters, isMft, false, 0); } if (numFound < count) { numFound = FindClusters(count - numFound, result, totalClusters / 16, totalClusters / 8, isMft, false, 0); } if (numFound < count) { numFound = FindClusters(count - numFound, result, totalClusters / 32, totalClusters / 16, isMft, false, 0); } if (numFound < count) { numFound = FindClusters(count - numFound, result, 0, totalClusters / 32, isMft, false, 0); } } if (numFound < count) { FreeClusters(result.ToArray()); throw new IOException("Out of disk space"); } // If we found more than two clusters, or we have a fragmented result, // then switch out of trying to allocate contiguous ranges. Similarly, // switch back if we found a resonable quantity in a single span. if ((numFound > 4 && result.Count == 1) || result.Count > 1) { _fragmentedDiskMode = numFound / result.Count < 4; } return result.ToArray(); } internal void MarkAllocated(long first, long count) { _bitmap.MarkPresentRange(first, count); } internal void FreeClusters(params Tuple<long, long>[] runs) { foreach (Tuple<long, long> run in runs) { #if NET20 _bitmap.MarkAbsentRange(run.Item1, run.Item2); #else _bitmap.MarkAbsentRange(run.Item1, run.Item2); #endif } } internal void FreeClusters(params Range<long, long>[] runs) { foreach (Range<long, long> run in runs) { _bitmap.MarkAbsentRange(run.Offset, run.Count); } } /// <summary> /// Sets the total number of clusters managed in the volume. /// </summary> /// <param name="numClusters">Total number of clusters in the volume.</param> /// <remarks> /// Any clusters represented in the bitmap beyond the total number in the volume are marked as in-use. /// </remarks> internal void SetTotalClusters(long numClusters) { long actualClusters = _bitmap.SetTotalEntries(numClusters); if (actualClusters != numClusters) { MarkAllocated(numClusters, actualClusters - numClusters); } } private long ExtendRun(long count, List<Tuple<long, long>> result, long start, long end) { long focusCluster = start; while (!_bitmap.IsPresent(focusCluster) && focusCluster < end && focusCluster - start < count) { ++focusCluster; } long numFound = focusCluster - start; if (numFound > 0) { _bitmap.MarkPresentRange(start, numFound); result.Add(new Tuple<long, long>(start, numFound)); } return numFound; } /// <summary> /// Finds one or more free clusters in a range. /// </summary> /// <param name="count">The number of clusters required.</param> /// <param name="result">The list of clusters found (i.e. out param).</param> /// <param name="start">The first cluster in the range to look at.</param> /// <param name="end">The last cluster in the range to look at (exclusive).</param> /// <param name="isMft">Indicates if the clusters are for the MFT.</param> /// <param name="contiguous">Indicates if contiguous clusters are required.</param> /// <param name="headroom">Indicates how many clusters to skip before next allocation, to prevent fragmentation.</param> /// <returns>The number of clusters found in the range.</returns> private long FindClusters(long count, List<Tuple<long, long>> result, long start, long end, bool isMft, bool contiguous, long headroom) { long numFound = 0; long focusCluster; if (isMft) { focusCluster = start; } else { if (_nextDataCluster < start || _nextDataCluster >= end) { _nextDataCluster = start; } focusCluster = _nextDataCluster; } long numInspected = 0; while (numFound < count && focusCluster >= start && numInspected < end - start) { if (!_bitmap.IsPresent(focusCluster)) { // Start of a run... long runStart = focusCluster; ++focusCluster; while (!_bitmap.IsPresent(focusCluster) && focusCluster - runStart < count - numFound) { ++focusCluster; ++numInspected; } if (!contiguous || focusCluster - runStart == count - numFound) { _bitmap.MarkPresentRange(runStart, focusCluster - runStart); result.Add(new Tuple<long, long>(runStart, focusCluster - runStart)); numFound += focusCluster - runStart; } } else { ++focusCluster; } ++numInspected; if (focusCluster >= end) { focusCluster = start; } } if (!isMft) { _nextDataCluster = focusCluster + headroom; } return numFound; } } }
// // PictureTile.cs // // Author: // Stephane Delcroix <sdelcroix@novell.com> // Stephen Shaw <sshaw@decriptor.com> // // Copyright (C) 2008 Novell, Inc. // Copyright (C) 2008 Stephane Delcroix // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Collections; using System.Globalization; using System.Collections.Generic; using Gtk; using FSpot; using FSpot.Extensions; using FSpot.Widgets; using FSpot.Filters; using FSpot.UI.Dialog; using Hyena; using Mono.Unix; namespace PictureTileExtension { public class PictureTile: ICommand { [Glade.Widget] Gtk.Dialog picturetile_dialog; [Glade.Widget] Gtk.SpinButton x_max_size; [Glade.Widget] Gtk.SpinButton y_max_size; [Glade.Widget] Gtk.SpinButton space_between_images; [Glade.Widget] Gtk.SpinButton outside_border; [Glade.Widget] Gtk.ComboBox background_color; [Glade.Widget] Gtk.SpinButton image_scale; [Glade.Widget] Gtk.CheckButton uniform_images; [Glade.Widget] Gtk.RadioButton jpeg_radio; [Glade.Widget] Gtk.RadioButton tiff_radio; [Glade.Widget] Gtk.SpinButton pages; [Glade.Widget] Gtk.SpinButton jpeg_quality; string dir_tmp; string destfile_tmp; string [] colors = {"white", "black"}; Tag [] photo_tags; public void Run (object o, EventArgs e) { Log.Information ("Executing PictureTile extension"); if (App.Instance.Organizer.SelectedPhotos ().Length == 0) { InfoDialog (Catalog.GetString ("No selection available"), Catalog.GetString ("This tool requires an active selection. Please select one or more pictures and try again"), Gtk.MessageType.Error); return; } else { //Check for PictureTile executable string output = ""; try { System.Diagnostics.Process mp_check = new System.Diagnostics.Process (); mp_check.StartInfo.RedirectStandardOutput = true; mp_check.StartInfo.RedirectStandardError = true; mp_check.StartInfo.UseShellExecute = false; mp_check.StartInfo.FileName = "picturetile.pl"; mp_check.Start (); mp_check.WaitForExit (); StreamReader sroutput = mp_check.StandardError; output = sroutput.ReadLine (); } catch (System.Exception) { } if (!System.Text.RegularExpressions.Regex.IsMatch (output, "^picturetile")) { InfoDialog (Catalog.GetString ("PictureTile not available"), Catalog.GetString ("The picturetile.pl executable was not found in path. Please check that you have it installed and that you have permissions to execute it"), Gtk.MessageType.Error); return; } ShowDialog (); } } public void ShowDialog () { Glade.XML xml = new Glade.XML (null, "PictureTile.glade", "picturetile_dialog", "f-spot"); xml.Autoconnect (this); picturetile_dialog.Modal = true; picturetile_dialog.TransientFor = null; picturetile_dialog.Response += OnDialogReponse; jpeg_radio.Active = true; jpeg_radio.Toggled += HandleFormatRadioToggled; HandleFormatRadioToggled (null, null); PopulateCombo (); picturetile_dialog.ShowAll (); } void OnDialogReponse (object obj, ResponseArgs args) { if (args.ResponseId == ResponseType.Ok) { CreatePhotoWall (); } picturetile_dialog.Destroy (); } void CreatePhotoWall () { dir_tmp = System.IO.Path.GetTempFileName (); System.IO.File.Delete (dir_tmp); System.IO.Directory.CreateDirectory (dir_tmp); dir_tmp += "/"; //Prepare the pictures ProgressDialog progress_dialog = null; progress_dialog = new ProgressDialog (Catalog.GetString ("Preparing selected pictures"), ProgressDialog.CancelButtonType.Stop, App.Instance.Organizer.SelectedPhotos ().Length, picturetile_dialog); FilterSet filters = new FilterSet (); filters.Add (new JpegFilter ()); uint counter = 0; List<Tag> all_tags = new List<Tag> (); foreach (Photo p in App.Instance.Organizer.SelectedPhotos ()) { if (progress_dialog.Update (String.Format (Catalog.GetString ("Processing \"{0}\""), p.Name))) { progress_dialog.Destroy (); DeleteTmp (); return; } //Store photo tags, to attach them later on import foreach (Tag tag in p.Tags) { if (! all_tags.Contains (tag)) all_tags.Add (tag); } //FIXME should switch to retry/skip if (!GLib.FileFactory.NewForUri (p.DefaultVersion.Uri).Exists) { Log.WarningFormat ("Couldn't access photo {0} while creating mosaics", p.DefaultVersion.Uri.LocalPath); continue; } using (FilterRequest freq = new FilterRequest (p.DefaultVersion.Uri)) { filters.Convert (freq); File.Copy (freq.Current.LocalPath, String.Format ("{0}{1}.jpg", dir_tmp, counter ++)); } } if (progress_dialog != null) progress_dialog.Destroy (); photo_tags = all_tags.ToArray (); string uniform = ""; if (uniform_images.Active) uniform = "--uniform"; string output_format = "jpeg"; if (tiff_radio.Active) output_format = "tiff"; string scale = String.Format (CultureInfo.InvariantCulture, "{0,4}", (double) image_scale.Value / (double) 100); destfile_tmp = String.Format ("{0}.{1}", System.IO.Path.GetTempFileName (), output_format); //Execute picturetile string picturetile_command = String.Format ("--size {0}x{1} " + "--directory {2} " + "--scale {3} " + "--margin {4} " + "--border {5} " + "--background {6} " + "--pages {7} " + "{8} " + "{9}", x_max_size.Text, y_max_size.Text, dir_tmp, scale, space_between_images.Text, outside_border.Text, colors [background_color.Active], pages.Text, uniform, destfile_tmp); Log.Debug ("Executing: picturetile.pl " + picturetile_command); System.Diagnostics.Process pt_exe = System.Diagnostics.Process.Start ("picturetile.pl", picturetile_command); pt_exe.WaitForExit (); // Handle multiple files generation (pages). // If the user wants 2 pages (images), and the output filename is out.jpg, picturetile will create // /tmp/out1.jpg and /tmp/out2.jpg. System.IO.DirectoryInfo di = new System.IO.DirectoryInfo (System.IO.Path.GetDirectoryName (destfile_tmp)); string filemask = System.IO.Path.GetFileNameWithoutExtension (destfile_tmp) + "*" + System.IO.Path.GetExtension (destfile_tmp); FileInfo [] fi = di.GetFiles (filemask); // Move generated files to f-spot photodir string [] photo_import_list = new string [fi.Length]; counter = 0; foreach (FileInfo f in fi) { string orig = System.IO.Path.Combine (f.DirectoryName, f.Name); photo_import_list [counter ++] = MoveFile (orig); } //Add the pic(s) to F-Spot! Db db = App.Instance.Database; ImportCommand command = new ImportCommand (null); if (command.ImportFromPaths (db.Photos, photo_import_list, photo_tags) > 0) { InfoDialog (Catalog.GetString ("PhotoWall generated!"), Catalog.GetString ("Your photo wall have been generated and imported in F-Spot. Select the last roll to see it"), Gtk.MessageType.Info); } else { InfoDialog (Catalog.GetString ("Error importing photowall"), Catalog.GetString ("An error occurred while importing the newly generated photowall to F-Spot"), Gtk.MessageType.Error); } DeleteTmp (); } private void HandleFormatRadioToggled (object o, EventArgs e) { jpeg_quality.Sensitive = jpeg_radio.Active; } private void DeleteTmp () { //Clean temp workdir DirectoryInfo dir = new DirectoryInfo(dir_tmp); FileInfo[] tmpfiles = dir.GetFiles(); foreach (FileInfo f in tmpfiles) { if (System.IO.File.Exists(dir_tmp + f.Name)) { System.IO.File.Delete (dir_tmp + f.Name); } } if (System.IO.Directory.Exists(dir_tmp)) { System.IO.Directory.Delete(dir_tmp); } } private void PopulateCombo () { foreach (string c in colors) { background_color.AppendText (c); } background_color.Active = 0; } private string MoveFile (string orig) { string dest = FileImportBackend.ChooseLocation (orig); System.IO.File.Move (orig, dest); return dest; } private void InfoDialog (string title, string msg, Gtk.MessageType type) { HigMessageDialog md = new HigMessageDialog (App.Instance.Organizer.Window, DialogFlags.DestroyWithParent, type, ButtonsType.Ok, title, msg); md.Run (); md.Destroy (); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Internal.Runtime.CompilerServices; namespace System.Buffers.Text { /// <summary> /// Convert between binary data and UTF-8 encoded text that is represented in base 64. /// </summary> public static partial class Base64 { /// <summary> /// Encode the span of binary data into UTF-8 encoded text represented as base 64. /// </summary> /// <param name="bytes">The input span which contains binary data that needs to be encoded.</param> /// <param name="utf8">The output span which contains the result of the operation, i.e. the UTF-8 encoded text in base 64.</param> /// <param name="bytesConsumed">The number of input bytes consumed during the operation. This can be used to slice the input for subsequent calls, if necessary.</param> /// <param name="bytesWritten">The number of bytes written into the output span. This can be used to slice the output for subsequent calls, if necessary.</param> /// <param name="isFinalBlock">True (default) when the input span contains the entire data to encode. /// Set to false only if it is known that the input span contains partial data with more data to follow.</param> /// <returns>It returns the OperationStatus enum values: /// - Done - on successful processing of the entire input span /// - DestinationTooSmall - if there is not enough space in the output span to fit the encoded input /// - NeedMoreData - only if isFinalBlock is false, otherwise the output is padded if the input is not a multiple of 3 /// It does not return InvalidData since that is not possible for base 64 encoding. /// </returns> public static OperationStatus EncodeToUtf8(ReadOnlySpan<byte> bytes, Span<byte> utf8, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { ref byte srcBytes = ref MemoryMarshal.GetReference(bytes); ref byte destBytes = ref MemoryMarshal.GetReference(utf8); int srcLength = bytes.Length; int destLength = utf8.Length; int maxSrcLength = 0; if (srcLength <= MaximumEncodeLength && destLength >= GetMaxEncodedToUtf8Length(srcLength)) { maxSrcLength = srcLength - 2; } else { maxSrcLength = (destLength >> 2) * 3 - 2; } int sourceIndex = 0; int destIndex = 0; int result = 0; ref byte encodingMap = ref s_encodingMap[0]; while (sourceIndex < maxSrcLength) { result = Encode(ref Unsafe.Add(ref srcBytes, sourceIndex), ref encodingMap); Unsafe.WriteUnaligned(ref Unsafe.Add(ref destBytes, destIndex), result); destIndex += 4; sourceIndex += 3; } if (maxSrcLength != srcLength - 2) goto DestinationSmallExit; if (!isFinalBlock) goto NeedMoreDataExit; if (sourceIndex == srcLength - 1) { result = EncodeAndPadTwo(ref Unsafe.Add(ref srcBytes, sourceIndex), ref encodingMap); Unsafe.WriteUnaligned(ref Unsafe.Add(ref destBytes, destIndex), result); destIndex += 4; sourceIndex += 1; } else if (sourceIndex == srcLength - 2) { result = EncodeAndPadOne(ref Unsafe.Add(ref srcBytes, sourceIndex), ref encodingMap); Unsafe.WriteUnaligned(ref Unsafe.Add(ref destBytes, destIndex), result); destIndex += 4; sourceIndex += 2; } bytesConsumed = sourceIndex; bytesWritten = destIndex; return OperationStatus.Done; NeedMoreDataExit: bytesConsumed = sourceIndex; bytesWritten = destIndex; return OperationStatus.NeedMoreData; DestinationSmallExit: bytesConsumed = sourceIndex; bytesWritten = destIndex; return OperationStatus.DestinationTooSmall; } /// <summary> /// Returns the maximum length (in bytes) of the result if you were to encode binary data within a byte span of size "length". /// </summary> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="length"/> is less than 0 or larger than 1610612733 (since encode inflates the data by 4/3). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetMaxEncodedToUtf8Length(int length) { if ((uint)length > MaximumEncodeLength) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); return (((length + 2) / 3) * 4); } /// <summary> /// Encode the span of binary data (in-place) into UTF-8 encoded text represented as base 64. /// The encoded text output is larger than the binary data contained in the input (the operation inflates the data). /// </summary> /// <param name="buffer">The input span which contains binary data that needs to be encoded. /// It needs to be large enough to fit the result of the operation.</param> /// <param name="dataLength">The amount of binary data contained within the buffer that needs to be encoded /// (and needs to be smaller than the buffer length).</param> /// <param name="bytesWritten">The number of bytes written into the buffer.</param> /// <returns>It returns the OperationStatus enum values: /// - Done - on successful processing of the entire buffer /// - DestinationTooSmall - if there is not enough space in the buffer beyond dataLength to fit the result of encoding the input /// It does not return NeedMoreData since this method tramples the data in the buffer and hence can only be called once with all the data in the buffer. /// It does not return InvalidData since that is not possible for base 64 encoding. /// </returns> public static OperationStatus EncodeToUtf8InPlace(Span<byte> buffer, int dataLength, out int bytesWritten) { int encodedLength = GetMaxEncodedToUtf8Length(dataLength); if (buffer.Length < encodedLength) goto FalseExit; int leftover = dataLength - (dataLength / 3) * 3; // how many bytes after packs of 3 int destinationIndex = encodedLength - 4; int sourceIndex = dataLength - leftover; int result = 0; ref byte encodingMap = ref s_encodingMap[0]; ref byte bufferBytes = ref MemoryMarshal.GetReference(buffer); // encode last pack to avoid conditional in the main loop if (leftover != 0) { if (leftover == 1) { result = EncodeAndPadTwo(ref Unsafe.Add(ref bufferBytes, sourceIndex), ref encodingMap); Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferBytes, destinationIndex), result); destinationIndex -= 4; } else { result = EncodeAndPadOne(ref Unsafe.Add(ref bufferBytes, sourceIndex), ref encodingMap); Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferBytes, destinationIndex), result); destinationIndex -= 4; } } sourceIndex -= 3; while (sourceIndex >= 0) { result = Encode(ref Unsafe.Add(ref bufferBytes, sourceIndex), ref encodingMap); Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferBytes, destinationIndex), result); destinationIndex -= 4; sourceIndex -= 3; } bytesWritten = encodedLength; return OperationStatus.Done; FalseExit: bytesWritten = 0; return OperationStatus.DestinationTooSmall; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int Encode(ref byte threeBytes, ref byte encodingMap) { int i = (threeBytes << 16) | (Unsafe.Add(ref threeBytes, 1) << 8) | Unsafe.Add(ref threeBytes, 2); int i0 = Unsafe.Add(ref encodingMap, i >> 18); int i1 = Unsafe.Add(ref encodingMap, (i >> 12) & 0x3F); int i2 = Unsafe.Add(ref encodingMap, (i >> 6) & 0x3F); int i3 = Unsafe.Add(ref encodingMap, i & 0x3F); return i0 | (i1 << 8) | (i2 << 16) | (i3 << 24); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int EncodeAndPadOne(ref byte twoBytes, ref byte encodingMap) { int i = (twoBytes << 16) | (Unsafe.Add(ref twoBytes, 1) << 8); int i0 = Unsafe.Add(ref encodingMap, i >> 18); int i1 = Unsafe.Add(ref encodingMap, (i >> 12) & 0x3F); int i2 = Unsafe.Add(ref encodingMap, (i >> 6) & 0x3F); return i0 | (i1 << 8) | (i2 << 16) | (EncodingPad << 24); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int EncodeAndPadTwo(ref byte oneByte, ref byte encodingMap) { int i = (oneByte << 8); int i0 = Unsafe.Add(ref encodingMap, i >> 10); int i1 = Unsafe.Add(ref encodingMap, (i >> 4) & 0x3F); return i0 | (i1 << 8) | (EncodingPad << 16) | (EncodingPad << 24); } // Pre-computing this table using a custom string(s_characters) and GenerateEncodingMapAndVerify (found in tests) private static readonly byte[] s_encodingMap = { 65, 66, 67, 68, 69, 70, 71, 72, //A..H 73, 74, 75, 76, 77, 78, 79, 80, //I..P 81, 82, 83, 84, 85, 86, 87, 88, //Q..X 89, 90, 97, 98, 99, 100, 101, 102, //Y..Z, a..f 103, 104, 105, 106, 107, 108, 109, 110, //g..n 111, 112, 113, 114, 115, 116, 117, 118, //o..v 119, 120, 121, 122, 48, 49, 50, 51, //w..z, 0..3 52, 53, 54, 55, 56, 57, 43, 47 //4..9, +, / }; private const byte EncodingPad = (byte)'='; // '=', for padding private const int MaximumEncodeLength = (int.MaxValue / 4) * 3; // 1610612733 } }
// This file has been generated by the GUI designer. Do not modify. namespace MonoDevelop.VersionControl.Mercurial { public partial class MercurialConfigurationDialog { private global::Gtk.Notebook notebook1; private global::Gtk.VBox vbox2; private global::Gtk.HBox hbox1; private global::Gtk.ScrolledWindow GtkScrolledWindow; private global::Gtk.TreeView listBranches; private global::Gtk.VBox vbox3; private global::Gtk.Button buttonAddBranch; private global::Gtk.Button buttonEditBranch; private global::Gtk.Button buttonRemoveBranch; private global::Gtk.Button buttonSetDefaultBranch; private global::Gtk.Label label1; private global::Gtk.VBox vbox4; private global::Gtk.HBox hbox2; private global::Gtk.ScrolledWindow GtkScrolledWindow1; private global::Gtk.TreeView treeRemotes; private global::Gtk.VBox vbox5; private global::Gtk.Button buttonAddRemote; private global::Gtk.Button buttonEditRemote; private global::Gtk.Button buttonRemoveRemote; private global::Gtk.HSeparator hseparator2; private global::Gtk.Button buttonTrackRemote; private global::Gtk.Label label2; private global::Gtk.Button buttonOk; protected virtual void Build () { global::Stetic.Gui.Initialize (this); // Widget MonoDevelop.VersionControl.Mercurial.MercurialConfigurationDialog this.Name = "MonoDevelop.VersionControl.Mercurial.MercurialConfigurationDialog"; this.Title = global::Mono.Unix.Catalog.GetString ("Mercurial Repository Configuration"); this.WindowPosition = ((global::Gtk.WindowPosition)(4)); // Internal child MonoDevelop.VersionControl.Mercurial.MercurialConfigurationDialog.VBox global::Gtk.VBox w1 = this.VBox; w1.Name = "dialog1_VBox"; w1.BorderWidth = ((uint)(2)); // Container child dialog1_VBox.Gtk.Box+BoxChild this.notebook1 = new global::Gtk.Notebook (); this.notebook1.CanFocus = true; this.notebook1.Name = "notebook1"; this.notebook1.CurrentPage = 1; this.notebook1.BorderWidth = ((uint)(9)); // Container child notebook1.Gtk.Notebook+NotebookChild this.vbox2 = new global::Gtk.VBox (); this.vbox2.Name = "vbox2"; this.vbox2.Spacing = 6; this.vbox2.BorderWidth = ((uint)(9)); // Container child vbox2.Gtk.Box+BoxChild this.hbox1 = new global::Gtk.HBox (); this.hbox1.Name = "hbox1"; this.hbox1.Spacing = 6; // Container child hbox1.Gtk.Box+BoxChild this.GtkScrolledWindow = new global::Gtk.ScrolledWindow (); this.GtkScrolledWindow.Name = "GtkScrolledWindow"; this.GtkScrolledWindow.ShadowType = ((global::Gtk.ShadowType)(1)); // Container child GtkScrolledWindow.Gtk.Container+ContainerChild this.listBranches = new global::Gtk.TreeView (); this.listBranches.CanFocus = true; this.listBranches.Name = "listBranches"; this.GtkScrolledWindow.Add (this.listBranches); this.hbox1.Add (this.GtkScrolledWindow); global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.GtkScrolledWindow])); w3.Position = 0; // Container child hbox1.Gtk.Box+BoxChild this.vbox3 = new global::Gtk.VBox (); this.vbox3.Name = "vbox3"; this.vbox3.Spacing = 6; // Container child vbox3.Gtk.Box+BoxChild this.buttonAddBranch = new global::Gtk.Button (); this.buttonAddBranch.CanFocus = true; this.buttonAddBranch.Name = "buttonAddBranch"; this.buttonAddBranch.UseStock = true; this.buttonAddBranch.UseUnderline = true; this.buttonAddBranch.Label = "gtk-new"; this.vbox3.Add (this.buttonAddBranch); global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.buttonAddBranch])); w4.Position = 0; w4.Expand = false; w4.Fill = false; // Container child vbox3.Gtk.Box+BoxChild this.buttonEditBranch = new global::Gtk.Button (); this.buttonEditBranch.CanFocus = true; this.buttonEditBranch.Name = "buttonEditBranch"; this.buttonEditBranch.UseStock = true; this.buttonEditBranch.UseUnderline = true; this.buttonEditBranch.Label = "gtk-edit"; this.vbox3.Add (this.buttonEditBranch); global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.buttonEditBranch])); w5.Position = 1; w5.Expand = false; w5.Fill = false; // Container child vbox3.Gtk.Box+BoxChild this.buttonRemoveBranch = new global::Gtk.Button (); this.buttonRemoveBranch.CanFocus = true; this.buttonRemoveBranch.Name = "buttonRemoveBranch"; this.buttonRemoveBranch.UseStock = true; this.buttonRemoveBranch.UseUnderline = true; this.buttonRemoveBranch.Label = "gtk-delete"; this.vbox3.Add (this.buttonRemoveBranch); global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.buttonRemoveBranch])); w6.Position = 2; w6.Expand = false; w6.Fill = false; // Container child vbox3.Gtk.Box+BoxChild this.buttonSetDefaultBranch = new global::Gtk.Button (); this.buttonSetDefaultBranch.CanFocus = true; this.buttonSetDefaultBranch.Name = "buttonSetDefaultBranch"; this.buttonSetDefaultBranch.UseUnderline = true; this.buttonSetDefaultBranch.Label = global::Mono.Unix.Catalog.GetString ("Switch to Branch"); this.vbox3.Add (this.buttonSetDefaultBranch); global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.buttonSetDefaultBranch])); w7.Position = 3; w7.Expand = false; w7.Fill = false; this.hbox1.Add (this.vbox3); global::Gtk.Box.BoxChild w8 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.vbox3])); w8.Position = 1; w8.Expand = false; w8.Fill = false; this.vbox2.Add (this.hbox1); global::Gtk.Box.BoxChild w9 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.hbox1])); w9.Position = 0; this.notebook1.Add (this.vbox2); // Notebook tab this.label1 = new global::Gtk.Label (); this.label1.Name = "label1"; this.label1.LabelProp = global::Mono.Unix.Catalog.GetString ("Branches"); this.notebook1.SetTabLabel (this.vbox2, this.label1); this.label1.ShowAll (); // Container child notebook1.Gtk.Notebook+NotebookChild this.vbox4 = new global::Gtk.VBox (); this.vbox4.Name = "vbox4"; this.vbox4.Spacing = 6; this.vbox4.BorderWidth = ((uint)(9)); // Container child vbox4.Gtk.Box+BoxChild this.hbox2 = new global::Gtk.HBox (); this.hbox2.Name = "hbox2"; this.hbox2.Spacing = 6; // Container child hbox2.Gtk.Box+BoxChild this.GtkScrolledWindow1 = new global::Gtk.ScrolledWindow (); this.GtkScrolledWindow1.Name = "GtkScrolledWindow1"; this.GtkScrolledWindow1.ShadowType = ((global::Gtk.ShadowType)(1)); // Container child GtkScrolledWindow1.Gtk.Container+ContainerChild this.treeRemotes = new global::Gtk.TreeView (); this.treeRemotes.CanFocus = true; this.treeRemotes.Name = "treeRemotes"; this.GtkScrolledWindow1.Add (this.treeRemotes); this.hbox2.Add (this.GtkScrolledWindow1); global::Gtk.Box.BoxChild w12 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.GtkScrolledWindow1])); w12.Position = 0; // Container child hbox2.Gtk.Box+BoxChild this.vbox5 = new global::Gtk.VBox (); this.vbox5.Name = "vbox5"; this.vbox5.Spacing = 6; // Container child vbox5.Gtk.Box+BoxChild this.buttonAddRemote = new global::Gtk.Button (); this.buttonAddRemote.CanFocus = true; this.buttonAddRemote.Name = "buttonAddRemote"; this.buttonAddRemote.UseStock = true; this.buttonAddRemote.UseUnderline = true; this.buttonAddRemote.Label = "gtk-add"; this.vbox5.Add (this.buttonAddRemote); global::Gtk.Box.BoxChild w13 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.buttonAddRemote])); w13.Position = 0; w13.Expand = false; w13.Fill = false; // Container child vbox5.Gtk.Box+BoxChild this.buttonEditRemote = new global::Gtk.Button (); this.buttonEditRemote.CanFocus = true; this.buttonEditRemote.Name = "buttonEditRemote"; this.buttonEditRemote.UseStock = true; this.buttonEditRemote.UseUnderline = true; this.buttonEditRemote.Label = "gtk-edit"; this.vbox5.Add (this.buttonEditRemote); global::Gtk.Box.BoxChild w14 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.buttonEditRemote])); w14.Position = 1; w14.Expand = false; w14.Fill = false; // Container child vbox5.Gtk.Box+BoxChild this.buttonRemoveRemote = new global::Gtk.Button (); this.buttonRemoveRemote.CanFocus = true; this.buttonRemoveRemote.Name = "buttonRemoveRemote"; this.buttonRemoveRemote.UseStock = true; this.buttonRemoveRemote.UseUnderline = true; this.buttonRemoveRemote.Label = "gtk-remove"; this.vbox5.Add (this.buttonRemoveRemote); global::Gtk.Box.BoxChild w15 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.buttonRemoveRemote])); w15.Position = 2; w15.Expand = false; w15.Fill = false; // Container child vbox5.Gtk.Box+BoxChild this.hseparator2 = new global::Gtk.HSeparator (); this.hseparator2.Name = "hseparator2"; this.vbox5.Add (this.hseparator2); global::Gtk.Box.BoxChild w16 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.hseparator2])); w16.Position = 3; w16.Expand = false; w16.Fill = false; // Container child vbox5.Gtk.Box+BoxChild this.buttonTrackRemote = new global::Gtk.Button (); this.buttonTrackRemote.CanFocus = true; this.buttonTrackRemote.Name = "buttonTrackRemote"; this.buttonTrackRemote.UseUnderline = true; this.buttonTrackRemote.Label = global::Mono.Unix.Catalog.GetString ("Track in Local Branch"); this.vbox5.Add (this.buttonTrackRemote); global::Gtk.Box.BoxChild w17 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.buttonTrackRemote])); w17.Position = 4; w17.Expand = false; w17.Fill = false; this.hbox2.Add (this.vbox5); global::Gtk.Box.BoxChild w18 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.vbox5])); w18.Position = 1; w18.Expand = false; w18.Fill = false; this.vbox4.Add (this.hbox2); global::Gtk.Box.BoxChild w19 = ((global::Gtk.Box.BoxChild)(this.vbox4 [this.hbox2])); w19.Position = 0; this.notebook1.Add (this.vbox4); global::Gtk.Notebook.NotebookChild w20 = ((global::Gtk.Notebook.NotebookChild)(this.notebook1 [this.vbox4])); w20.Position = 1; // Notebook tab this.label2 = new global::Gtk.Label (); this.label2.Name = "label2"; this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("Remote Sources"); this.notebook1.SetTabLabel (this.vbox4, this.label2); this.label2.ShowAll (); w1.Add (this.notebook1); global::Gtk.Box.BoxChild w21 = ((global::Gtk.Box.BoxChild)(w1 [this.notebook1])); w21.Position = 0; // Internal child MonoDevelop.VersionControl.Mercurial.MercurialConfigurationDialog.ActionArea global::Gtk.HButtonBox w22 = this.ActionArea; w22.Name = "dialog1_ActionArea"; w22.Spacing = 10; w22.BorderWidth = ((uint)(5)); w22.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(4)); // Container child dialog1_ActionArea.Gtk.ButtonBox+ButtonBoxChild this.buttonOk = new global::Gtk.Button (); this.buttonOk.CanDefault = true; this.buttonOk.CanFocus = true; this.buttonOk.Name = "buttonOk"; this.buttonOk.UseStock = true; this.buttonOk.UseUnderline = true; this.buttonOk.Label = "gtk-close"; this.AddActionWidget (this.buttonOk, -7); global::Gtk.ButtonBox.ButtonBoxChild w23 = ((global::Gtk.ButtonBox.ButtonBoxChild)(w22 [this.buttonOk])); w23.Expand = false; w23.Fill = false; if ((this.Child != null)) { this.Child.ShowAll (); } this.DefaultWidth = 521; this.DefaultHeight = 372; this.buttonAddBranch.Hide (); this.vbox4.Hide (); this.Show (); this.buttonAddBranch.Clicked += new global::System.EventHandler (this.OnButtonAddBranchClicked); this.buttonEditBranch.Clicked += new global::System.EventHandler (this.OnButtonEditBranchClicked); this.buttonRemoveBranch.Clicked += new global::System.EventHandler (this.OnButtonRemoveBranchClicked); this.buttonSetDefaultBranch.Clicked += new global::System.EventHandler (this.OnButtonSetDefaultBranchClicked); } } }
namespace android.widget { [global::MonoJavaBridge.JavaClass(typeof(global::android.widget.AdapterView_))] public abstract partial class AdapterView : android.view.ViewGroup { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static AdapterView() { InitJNI(); } protected AdapterView(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public partial class AdapterContextMenuInfo : java.lang.Object, android.view.ContextMenu_ContextMenuInfo { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static AdapterContextMenuInfo() { InitJNI(); } protected AdapterContextMenuInfo(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _AdapterContextMenuInfo10849; public AdapterContextMenuInfo(android.view.View arg0, int arg1, long arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AdapterView.AdapterContextMenuInfo.staticClass, global::android.widget.AdapterView.AdapterContextMenuInfo._AdapterContextMenuInfo10849, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _targetView10850; public global::android.view.View targetView { get { return default(global::android.view.View); } set { } } internal static global::MonoJavaBridge.FieldId _position10851; public int position { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _id10852; public long id { get { return default(long); } set { } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.AdapterView.AdapterContextMenuInfo.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AdapterView$AdapterContextMenuInfo")); global::android.widget.AdapterView.AdapterContextMenuInfo._AdapterContextMenuInfo10849 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.AdapterContextMenuInfo.staticClass, "<init>", "(Landroid/view/View;IJ)V"); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.AdapterView.OnItemClickListener_))] public interface OnItemClickListener : global::MonoJavaBridge.IJavaObject { void onItemClick(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.AdapterView.OnItemClickListener))] public sealed partial class OnItemClickListener_ : java.lang.Object, OnItemClickListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static OnItemClickListener_() { InitJNI(); } internal OnItemClickListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onItemClick10853; void android.widget.AdapterView.OnItemClickListener.onItemClick(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView.OnItemClickListener_._onItemClick10853, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.OnItemClickListener_.staticClass, global::android.widget.AdapterView.OnItemClickListener_._onItemClick10853, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.AdapterView.OnItemClickListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AdapterView$OnItemClickListener")); global::android.widget.AdapterView.OnItemClickListener_._onItemClick10853 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.OnItemClickListener_.staticClass, "onItemClick", "(Landroid/widget/AdapterView;Landroid/view/View;IJ)V"); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.AdapterView.OnItemLongClickListener_))] public interface OnItemLongClickListener : global::MonoJavaBridge.IJavaObject { bool onItemLongClick(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.AdapterView.OnItemLongClickListener))] public sealed partial class OnItemLongClickListener_ : java.lang.Object, OnItemLongClickListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static OnItemLongClickListener_() { InitJNI(); } internal OnItemLongClickListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onItemLongClick10854; bool android.widget.AdapterView.OnItemLongClickListener.onItemLongClick(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AdapterView.OnItemLongClickListener_._onItemLongClick10854, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AdapterView.OnItemLongClickListener_.staticClass, global::android.widget.AdapterView.OnItemLongClickListener_._onItemLongClick10854, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.AdapterView.OnItemLongClickListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AdapterView$OnItemLongClickListener")); global::android.widget.AdapterView.OnItemLongClickListener_._onItemLongClick10854 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.OnItemLongClickListener_.staticClass, "onItemLongClick", "(Landroid/widget/AdapterView;Landroid/view/View;IJ)Z"); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.AdapterView.OnItemSelectedListener_))] public interface OnItemSelectedListener : global::MonoJavaBridge.IJavaObject { void onItemSelected(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3); void onNothingSelected(android.widget.AdapterView arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.AdapterView.OnItemSelectedListener))] public sealed partial class OnItemSelectedListener_ : java.lang.Object, OnItemSelectedListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static OnItemSelectedListener_() { InitJNI(); } internal OnItemSelectedListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onItemSelected10855; void android.widget.AdapterView.OnItemSelectedListener.onItemSelected(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView.OnItemSelectedListener_._onItemSelected10855, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.OnItemSelectedListener_.staticClass, global::android.widget.AdapterView.OnItemSelectedListener_._onItemSelected10855, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _onNothingSelected10856; void android.widget.AdapterView.OnItemSelectedListener.onNothingSelected(android.widget.AdapterView arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView.OnItemSelectedListener_._onNothingSelected10856, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.OnItemSelectedListener_.staticClass, global::android.widget.AdapterView.OnItemSelectedListener_._onNothingSelected10856, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.AdapterView.OnItemSelectedListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AdapterView$OnItemSelectedListener")); global::android.widget.AdapterView.OnItemSelectedListener_._onItemSelected10855 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.OnItemSelectedListener_.staticClass, "onItemSelected", "(Landroid/widget/AdapterView;Landroid/view/View;IJ)V"); global::android.widget.AdapterView.OnItemSelectedListener_._onNothingSelected10856 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.OnItemSelectedListener_.staticClass, "onNothingSelected", "(Landroid/widget/AdapterView;)V"); } } internal static global::MonoJavaBridge.MethodId _dispatchPopulateAccessibilityEvent10857; public override bool dispatchPopulateAccessibilityEvent(android.view.accessibility.AccessibilityEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AdapterView._dispatchPopulateAccessibilityEvent10857, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._dispatchPopulateAccessibilityEvent10857, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _addView10858; public override void addView(android.view.View arg0, int arg1, android.view.ViewGroup.LayoutParams arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView._addView10858, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._addView10858, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _addView10859; public override void addView(android.view.View arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView._addView10859, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._addView10859, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _addView10860; public override void addView(android.view.View arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView._addView10860, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._addView10860, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _addView10861; public override void addView(android.view.View arg0, android.view.ViewGroup.LayoutParams arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView._addView10861, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._addView10861, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _removeView10862; public override void removeView(android.view.View arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView._removeView10862, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._removeView10862, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setOnClickListener10863; public override void setOnClickListener(android.view.View.OnClickListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView._setOnClickListener10863, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._setOnClickListener10863, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setFocusable10864; public override void setFocusable(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView._setFocusable10864, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._setFocusable10864, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setFocusableInTouchMode10865; public override void setFocusableInTouchMode(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView._setFocusableInTouchMode10865, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._setFocusableInTouchMode10865, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _dispatchSaveInstanceState10866; protected override void dispatchSaveInstanceState(android.util.SparseArray arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView._dispatchSaveInstanceState10866, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._dispatchSaveInstanceState10866, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _dispatchRestoreInstanceState10867; protected override void dispatchRestoreInstanceState(android.util.SparseArray arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView._dispatchRestoreInstanceState10867, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._dispatchRestoreInstanceState10867, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onLayout10868; protected override void onLayout(bool arg0, int arg1, int arg2, int arg3, int arg4) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView._onLayout10868, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._onLayout10868, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } internal static global::MonoJavaBridge.MethodId _getCount10869; public virtual int getCount() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AdapterView._getCount10869); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._getCount10869); } internal static global::MonoJavaBridge.MethodId _removeViewAt10870; public override void removeViewAt(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView._removeViewAt10870, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._removeViewAt10870, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _removeAllViews10871; public override void removeAllViews() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView._removeAllViews10871); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._removeAllViews10871); } internal static global::MonoJavaBridge.MethodId _canAnimate10872; protected override bool canAnimate() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AdapterView._canAnimate10872); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._canAnimate10872); } internal static global::MonoJavaBridge.MethodId _setAdapter10873; public abstract void setAdapter(android.widget.Adapter arg0); internal static global::MonoJavaBridge.MethodId _setOnItemSelectedListener10874; public virtual void setOnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView._setOnItemSelectedListener10874, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._setOnItemSelectedListener10874, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setOnItemClickListener10875; public virtual void setOnItemClickListener(android.widget.AdapterView.OnItemClickListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView._setOnItemClickListener10875, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._setOnItemClickListener10875, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getOnItemClickListener10876; public virtual global::android.widget.AdapterView.OnItemClickListener getOnItemClickListener() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.AdapterView.OnItemClickListener>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AdapterView._getOnItemClickListener10876)) as android.widget.AdapterView.OnItemClickListener; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.AdapterView.OnItemClickListener>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._getOnItemClickListener10876)) as android.widget.AdapterView.OnItemClickListener; } internal static global::MonoJavaBridge.MethodId _performItemClick10877; public virtual bool performItemClick(android.view.View arg0, int arg1, long arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AdapterView._performItemClick10877, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._performItemClick10877, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _setOnItemLongClickListener10878; public virtual void setOnItemLongClickListener(android.widget.AdapterView.OnItemLongClickListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView._setOnItemLongClickListener10878, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._setOnItemLongClickListener10878, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getOnItemLongClickListener10879; public virtual global::android.widget.AdapterView.OnItemLongClickListener getOnItemLongClickListener() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.AdapterView.OnItemLongClickListener>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AdapterView._getOnItemLongClickListener10879)) as android.widget.AdapterView.OnItemLongClickListener; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.AdapterView.OnItemLongClickListener>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._getOnItemLongClickListener10879)) as android.widget.AdapterView.OnItemLongClickListener; } internal static global::MonoJavaBridge.MethodId _getOnItemSelectedListener10880; public virtual global::android.widget.AdapterView.OnItemSelectedListener getOnItemSelectedListener() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.AdapterView.OnItemSelectedListener>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AdapterView._getOnItemSelectedListener10880)) as android.widget.AdapterView.OnItemSelectedListener; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.AdapterView.OnItemSelectedListener>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._getOnItemSelectedListener10880)) as android.widget.AdapterView.OnItemSelectedListener; } internal static global::MonoJavaBridge.MethodId _getAdapter10881; public abstract global::android.widget.Adapter getAdapter(); internal static global::MonoJavaBridge.MethodId _getSelectedItemPosition10882; public virtual int getSelectedItemPosition() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AdapterView._getSelectedItemPosition10882); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._getSelectedItemPosition10882); } internal static global::MonoJavaBridge.MethodId _getSelectedItemId10883; public virtual long getSelectedItemId() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.widget.AdapterView._getSelectedItemId10883); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._getSelectedItemId10883); } internal static global::MonoJavaBridge.MethodId _getSelectedView10884; public abstract global::android.view.View getSelectedView(); internal static global::MonoJavaBridge.MethodId _getSelectedItem10885; public virtual global::java.lang.Object getSelectedItem() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AdapterView._getSelectedItem10885)) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._getSelectedItem10885)) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _getPositionForView10886; public virtual int getPositionForView(android.view.View arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AdapterView._getPositionForView10886, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._getPositionForView10886, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getFirstVisiblePosition10887; public virtual int getFirstVisiblePosition() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AdapterView._getFirstVisiblePosition10887); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._getFirstVisiblePosition10887); } internal static global::MonoJavaBridge.MethodId _getLastVisiblePosition10888; public virtual int getLastVisiblePosition() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AdapterView._getLastVisiblePosition10888); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._getLastVisiblePosition10888); } internal static global::MonoJavaBridge.MethodId _setSelection10889; public abstract void setSelection(int arg0); internal static global::MonoJavaBridge.MethodId _setEmptyView10890; public virtual void setEmptyView(android.view.View arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView._setEmptyView10890, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._setEmptyView10890, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getEmptyView10891; public virtual global::android.view.View getEmptyView() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AdapterView._getEmptyView10891)) as android.view.View; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._getEmptyView10891)) as android.view.View; } internal static global::MonoJavaBridge.MethodId _getItemAtPosition10892; public virtual global::java.lang.Object getItemAtPosition(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AdapterView._getItemAtPosition10892, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._getItemAtPosition10892, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _getItemIdAtPosition10893; public virtual long getItemIdAtPosition(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.widget.AdapterView._getItemIdAtPosition10893, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.widget.AdapterView.staticClass, global::android.widget.AdapterView._getItemIdAtPosition10893, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _AdapterView10894; public AdapterView(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AdapterView.staticClass, global::android.widget.AdapterView._AdapterView10894, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _AdapterView10895; public AdapterView(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AdapterView.staticClass, global::android.widget.AdapterView._AdapterView10895, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _AdapterView10896; public AdapterView(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AdapterView.staticClass, global::android.widget.AdapterView._AdapterView10896, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } public static int ITEM_VIEW_TYPE_IGNORE { get { return -1; } } public static int ITEM_VIEW_TYPE_HEADER_OR_FOOTER { get { return -2; } } public static int INVALID_POSITION { get { return -1; } } public static long INVALID_ROW_ID { get { return -9223372036854775808L; } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.AdapterView.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AdapterView")); global::android.widget.AdapterView._dispatchPopulateAccessibilityEvent10857 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "dispatchPopulateAccessibilityEvent", "(Landroid/view/accessibility/AccessibilityEvent;)Z"); global::android.widget.AdapterView._addView10858 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "addView", "(Landroid/view/View;ILandroid/view/ViewGroup$LayoutParams;)V"); global::android.widget.AdapterView._addView10859 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "addView", "(Landroid/view/View;)V"); global::android.widget.AdapterView._addView10860 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "addView", "(Landroid/view/View;I)V"); global::android.widget.AdapterView._addView10861 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "addView", "(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V"); global::android.widget.AdapterView._removeView10862 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "removeView", "(Landroid/view/View;)V"); global::android.widget.AdapterView._setOnClickListener10863 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "setOnClickListener", "(Landroid/view/View$OnClickListener;)V"); global::android.widget.AdapterView._setFocusable10864 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "setFocusable", "(Z)V"); global::android.widget.AdapterView._setFocusableInTouchMode10865 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "setFocusableInTouchMode", "(Z)V"); global::android.widget.AdapterView._dispatchSaveInstanceState10866 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "dispatchSaveInstanceState", "(Landroid/util/SparseArray;)V"); global::android.widget.AdapterView._dispatchRestoreInstanceState10867 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "dispatchRestoreInstanceState", "(Landroid/util/SparseArray;)V"); global::android.widget.AdapterView._onLayout10868 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "onLayout", "(ZIIII)V"); global::android.widget.AdapterView._getCount10869 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "getCount", "()I"); global::android.widget.AdapterView._removeViewAt10870 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "removeViewAt", "(I)V"); global::android.widget.AdapterView._removeAllViews10871 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "removeAllViews", "()V"); global::android.widget.AdapterView._canAnimate10872 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "canAnimate", "()Z"); global::android.widget.AdapterView._setAdapter10873 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "setAdapter", "(Landroid/widget/Adapter;)V"); global::android.widget.AdapterView._setOnItemSelectedListener10874 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "setOnItemSelectedListener", "(Landroid/widget/AdapterView$OnItemSelectedListener;)V"); global::android.widget.AdapterView._setOnItemClickListener10875 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "setOnItemClickListener", "(Landroid/widget/AdapterView$OnItemClickListener;)V"); global::android.widget.AdapterView._getOnItemClickListener10876 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "getOnItemClickListener", "()Landroid/widget/AdapterView$OnItemClickListener;"); global::android.widget.AdapterView._performItemClick10877 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "performItemClick", "(Landroid/view/View;IJ)Z"); global::android.widget.AdapterView._setOnItemLongClickListener10878 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "setOnItemLongClickListener", "(Landroid/widget/AdapterView$OnItemLongClickListener;)V"); global::android.widget.AdapterView._getOnItemLongClickListener10879 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "getOnItemLongClickListener", "()Landroid/widget/AdapterView$OnItemLongClickListener;"); global::android.widget.AdapterView._getOnItemSelectedListener10880 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "getOnItemSelectedListener", "()Landroid/widget/AdapterView$OnItemSelectedListener;"); global::android.widget.AdapterView._getAdapter10881 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "getAdapter", "()Landroid/widget/Adapter;"); global::android.widget.AdapterView._getSelectedItemPosition10882 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "getSelectedItemPosition", "()I"); global::android.widget.AdapterView._getSelectedItemId10883 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "getSelectedItemId", "()J"); global::android.widget.AdapterView._getSelectedView10884 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "getSelectedView", "()Landroid/view/View;"); global::android.widget.AdapterView._getSelectedItem10885 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "getSelectedItem", "()Ljava/lang/Object;"); global::android.widget.AdapterView._getPositionForView10886 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "getPositionForView", "(Landroid/view/View;)I"); global::android.widget.AdapterView._getFirstVisiblePosition10887 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "getFirstVisiblePosition", "()I"); global::android.widget.AdapterView._getLastVisiblePosition10888 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "getLastVisiblePosition", "()I"); global::android.widget.AdapterView._setSelection10889 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "setSelection", "(I)V"); global::android.widget.AdapterView._setEmptyView10890 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "setEmptyView", "(Landroid/view/View;)V"); global::android.widget.AdapterView._getEmptyView10891 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "getEmptyView", "()Landroid/view/View;"); global::android.widget.AdapterView._getItemAtPosition10892 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "getItemAtPosition", "(I)Ljava/lang/Object;"); global::android.widget.AdapterView._getItemIdAtPosition10893 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "getItemIdAtPosition", "(I)J"); global::android.widget.AdapterView._AdapterView10894 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::android.widget.AdapterView._AdapterView10895 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V"); global::android.widget.AdapterView._AdapterView10896 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "<init>", "(Landroid/content/Context;)V"); } } [global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.AdapterView))] public sealed partial class AdapterView_ : android.widget.AdapterView { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static AdapterView_() { InitJNI(); } internal AdapterView_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _setAdapter10897; public override void setAdapter(android.widget.Adapter arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView_._setAdapter10897, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView_.staticClass, global::android.widget.AdapterView_._setAdapter10897, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getAdapter10898; public override global::android.widget.Adapter getAdapter() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.Adapter>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AdapterView_._getAdapter10898)) as android.widget.Adapter; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.Adapter>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AdapterView_.staticClass, global::android.widget.AdapterView_._getAdapter10898)) as android.widget.Adapter; } internal static global::MonoJavaBridge.MethodId _getSelectedView10899; public override global::android.view.View getSelectedView() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AdapterView_._getSelectedView10899)) as android.view.View; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AdapterView_.staticClass, global::android.widget.AdapterView_._getSelectedView10899)) as android.view.View; } internal static global::MonoJavaBridge.MethodId _setSelection10900; public override void setSelection(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.AdapterView_._setSelection10900, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AdapterView_.staticClass, global::android.widget.AdapterView_._setSelection10900, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.AdapterView_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AdapterView")); global::android.widget.AdapterView_._setAdapter10897 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView_.staticClass, "setAdapter", "(Landroid/widget/Adapter;)V"); global::android.widget.AdapterView_._getAdapter10898 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView_.staticClass, "getAdapter", "()Landroid/widget/Adapter;"); global::android.widget.AdapterView_._getSelectedView10899 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView_.staticClass, "getSelectedView", "()Landroid/view/View;"); global::android.widget.AdapterView_._setSelection10900 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView_.staticClass, "setSelection", "(I)V"); } } }
// This is a collection of .NET concurrency utilities, inspired by the classes // available in java. This utilities are written by Iulian Margarintescu as described here // https://github.com/etishor/ConcurrencyUtilities // // // Striped64 & LongAdder classes were ported from Java and had this copyright: // // Written by Doug Lea with assistance from members of JCP JSR-166 // Expert Group and released to the public domain, as explained at // http://creativecommons.org/publicdomain/zero/1.0/ // // Source: http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/Striped64.java?revision=1.8 // // By default all added classes are internal to your assembly. // To make them public define you have to define the conditional compilation symbol CONCURRENCY_UTILS_PUBLIC in your project properties. // #pragma warning disable 1591 // ReSharper disable All using System; using System.Collections.Generic; using System.Threading; namespace Metrics.ConcurrencyUtilities { /// <summary> /// Array of longs which provides atomic operations on the array elements. /// </summary> #if CONCURRENCY_UTILS_PUBLIC public #else internal #endif struct AtomicLongArray { private readonly long[] array; public AtomicLongArray(int length) { if (length < 0) { throw new ArgumentException("Length must be positive", "length"); } this.array = new long[length]; } public AtomicLongArray(IReadOnlyList<long> source) { var clone = new long[source.Count]; for (var i = 0; i < source.Count; i++) { clone[i] = source[i]; } this.array = clone; } public int Length { get { return this.array.Length; } } /// <summary> /// Returns the latest value of this instance written by any processor. /// </summary> /// <param name="index">index in the array</param> /// <returns>The latest written value of this instance.</returns> public long GetValue(int index) { return Volatile.Read(ref this.array[index]); } /// <summary> /// Write a new value to this instance. The value is immediately seen by all processors. /// </summary> /// <param name="index">index in the array</param> /// <param name="value">The new value for this instance.</param> public void SetValue(int index, long value) { Volatile.Write(ref this.array[index], value); } /// <summary> /// Add <paramref name="value"/> to this instance and return the resulting value. /// </summary> /// <param name="index">index in the array</param> /// <param name="value">The amount to add.</param> /// <returns>The value of this instance + the amount added.</returns> public long Add(int index, long value) { return Interlocked.Add(ref this.array[index], value); } /// <summary> /// Add <paramref name="value"/> to this instance and return the value this instance had before the add operation. /// </summary> /// <param name="index">index in the array</param> /// <param name="value">The amount to add.</param> /// <returns>The value of this instance before the amount was added.</returns> public long GetAndAdd(int index, long value) { return Add(index, value) - value; } /// <summary> /// Increment this instance and return the value the instance had before the increment. /// </summary> /// <param name="index">index in the array</param> /// <returns>The value of the instance *before* the increment.</returns> public long GetAndIncrement(int index) { return Increment(index) - 1; } /// <summary> /// Increment this instance with <paramref name="value"/> and return the value the instance had before the increment. /// </summary> /// <param name="index">index in the array</param> /// <param name="value">value to increment with</param> /// <returns>The value of the instance *before* the increment.</returns> public long GetAndIncrement(int index, long value) { return Increment(index, value) - value; } /// <summary> /// Decrement this instance and return the value the instance had before the decrement. /// </summary> /// <param name="index">index in the array</param> /// <returns>The value of the instance *before* the decrement.</returns> public long GetAndDecrement(int index) { return Decrement(index) + 1; } /// <summary> /// Decrement this instance with <paramref name="value"/> and return the value the instance had before the decrement. /// </summary> /// <param name="index">index in the array</param> /// <param name="value">value to decrement with</param> /// <returns>The value of the instance *before* the decrement.</returns> public long GetAndDecrement(int index, long value) { return Decrement(index, value) + value; } /// <summary> /// Increment this instance and return the value after the increment. /// </summary> /// <param name="index">index in the array</param> /// <returns>The value of the instance *after* the increment.</returns> public long Increment(int index) { return Interlocked.Increment(ref this.array[index]); } /// <summary> /// Increment this instance with <paramref name="value"/> and return the value after the increment. /// </summary> /// <param name="index">index in the array</param> /// <param name="value">value to increment with</param> /// <returns>The value of the instance *after* the increment.</returns> public long Increment(int index, long value) { return Add(index, value); } /// <summary> /// Decrement this instance and return the value after the decrement. /// </summary> /// <param name="index">index in the array</param> /// <returns>The value of the instance *after* the decrement.</returns> public long Decrement(int index) { return Interlocked.Decrement(ref this.array[index]); } /// <summary> /// Decrement this instance with <paramref name="value"/> and return the value after the decrement. /// </summary> /// <param name="index">index in the array</param> /// <param name="value">value to decrement with</param> /// <returns>The value of the instance *after* the decrement.</returns> public long Decrement(int index, long value) { return Add(index, -value); } /// <summary> /// Returns the current value of the instance and sets it to zero as an atomic operation. /// </summary> /// <param name="index">index in the array</param> /// <returns>The current value of the instance.</returns> public long GetAndReset(int index) { return GetAndSet(index, 0L); } /// <summary> /// Returns the current value of the instance and sets it to <paramref name="newValue"/> as an atomic operation. /// </summary> /// <param name="index">index in the array</param> /// <param name="newValue">value that will be set in the array at <paramref name="index"/></param> /// <returns>The current value of the instance.</returns> public long GetAndSet(int index, long newValue) { return Interlocked.Exchange(ref this.array[index], newValue); } /// <summary> /// Replace the value of this instance, if the current value is equal to the <paramref name="expected"/> value. /// </summary> /// <param name="index">index in the array</param> /// <param name="expected">Value this instance is expected to be equal with.</param> /// <param name="updated">Value to set this instance to, if the current value is equal to the expected value</param> /// <returns>True if the update was made, false otherwise.</returns> public bool CompareAndSwap(int index, long expected, long updated) { return Interlocked.CompareExchange(ref this.array[index], updated, expected) == expected; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using Microsoft.CookiecutterTools.Infrastructure; using Microsoft.CookiecutterTools.Model; using Microsoft.CookiecutterTools.Telemetry; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.CookiecutterTools { /// <summary> /// This is the class that implements the package exposed by this assembly. /// /// The minimum requirement for a class to be considered a valid package for Visual Studio /// is to implement the IVsPackage interface and register itself with the shell. /// This package uses the helper classes defined inside the Managed Package Framework (MPF) /// to do it: it derives from the Package class that provides the implementation of the /// IVsPackage interface and uses the registration attributes defined in the framework to /// register itself and its components with the shell. /// </summary> // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is // a package. [PackageRegistration(UseManagedResourcesOnly = true)] // This attribute is used to register the informations needed to show the this package // in the Help/About dialog of Visual Studio. [InstalledProductRegistration("#110", "#112", AssemblyVersionInfo.Version, IconResourceID = 400)] // This attribute is needed to let the shell know that this package exposes some menus. [ProvideMenuResource("Menus.ctmenu", 1)] [ProvideToolWindow(typeof(CookiecutterToolWindow), Style = VsDockStyle.Linked, Window = ToolWindowGuids80.ServerExplorer)] [ProvideOptionPage(typeof(CookiecutterOptionPage), "Cookiecutter", "General", 113, 114, true)] [ProvideProfileAttribute(typeof(CookiecutterOptionPage), "Cookiecutter", "General", 113, 114, isToolsOptionPage: true, DescriptionResourceID = 115)] [Guid(PackageGuids.guidCookiecutterPkgString)] public sealed class CookiecutterPackage : Package, IOleCommandTarget { internal static CookiecutterPackage Instance; private static readonly object _commandsLock = new object(); private static readonly Dictionary<Command, MenuCommand> _commands = new Dictionary<Command, MenuCommand>(); private ProjectSystemClient _projectSystem; /// <summary> /// Default constructor of the package. /// Inside this method you can place any initialization code that does not require /// any Visual Studio service because at this point the package object is created but /// not sited yet inside Visual Studio environment. The place to do all the other /// initialization is the Initialize method. /// </summary> public CookiecutterPackage() { Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString())); Instance = this; } ///////////////////////////////////////////////////////////////////////////// // Overriden Package Implementation #region Package Members /// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initilaization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString())); base.Initialize(); UIThread.EnsureService(this); _projectSystem = new ProjectSystemClient(DTE); CookiecutterTelemetry.Initialize(); } protected override void Dispose(bool disposing) { CookiecutterTelemetry.Current.Dispose(); base.Dispose(disposing); } #endregion #region IOleCommandTarget int IOleCommandTarget.Exec(ref Guid commandGroup, uint commandId, uint commandExecOpt, IntPtr variantIn, IntPtr variantOut) { if (commandGroup != PackageGuids.guidCookiecutterCmdSet) { return VSConstants.E_FAIL; } // Commands that support parameters cannot be implemented via IMenuCommandService var hr = VSConstants.S_OK; switch (commandId) { case PackageIds.cmdidViewExternalWebBrowser: hr = ViewExternalBrowser(variantIn, variantOut, commandExecOpt); break; case PackageIds.cmdidCookiecutterExplorer: ShowWindowPane(typeof(CookiecutterToolWindow), true); break; case PackageIds.cmdidCreateFromCookiecutter: NewCookiecutterSession(); break; case PackageIds.cmdidAddFromCookiecutter: NewCookiecutterSession(_projectSystem.GetSelectedFolderProjectLocation()); break; default: Debug.Assert(false); break; } return hr; } int IOleCommandTarget.QueryStatus(ref Guid commandGroup, uint commandsCount, OLECMD[] commands, IntPtr pCmdText) { if (commandGroup == PackageGuids.guidCookiecutterCmdSet && commandsCount == 1) { switch (commands[0].cmdID) { case PackageIds.cmdidAddFromCookiecutter: var location = _projectSystem.GetSelectedFolderProjectLocation() != null ? (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED) : 0; break; default: commands[0].cmdf = 0; break; } return VSConstants.S_OK; } return VSConstants.E_FAIL; } #endregion private string GetStringArgument(IntPtr variantIn) { if (variantIn == IntPtr.Zero) { return null; } var obj = Marshal.GetObjectForNativeVariant(variantIn); return obj as string; } /// <summary> /// Used to determine if the shell is querying for the parameter list of our command. /// </summary> private static bool IsQueryParameterList(IntPtr variantIn, IntPtr variantOut, uint nCmdexecopt) { ushort lo = (ushort)(nCmdexecopt & (uint)0xffff); ushort hi = (ushort)(nCmdexecopt >> 16); if (lo == (ushort)OLECMDEXECOPT.OLECMDEXECOPT_SHOWHELP) { if (hi == VsMenus.VSCmdOptQueryParameterList) { if (variantOut != IntPtr.Zero) { return true; } } } return false; } public static T GetGlobalService<S, T>() where T : class { object service = Package.GetGlobalService(typeof(S)); return service as T; } internal new object GetService(Type serviceType) { return base.GetService(serviceType); } public EnvDTE80.DTE2 DTE { get { return GetGlobalService<EnvDTE.DTE, EnvDTE80.DTE2>(); } } internal static void ShowContextMenu(CommandID commandId, int x, int y, IOleCommandTarget commandTarget) { var shell = CookiecutterPackage.GetGlobalService(typeof(SVsUIShell)) as IVsUIShell; var pts = new POINTS[1]; pts[0].x = (short)x; pts[0].y = (short)y; shell.ShowContextMenu(0, commandId.Guid, commandId.ID, pts, commandTarget); } internal WindowPane ShowWindowPane(Type windowType, bool focus) { var window = FindWindowPane(windowType, 0, true) as ToolWindowPane; if (window != null) { var frame = window.Frame as IVsWindowFrame; if (frame != null) { ErrorHandler.ThrowOnFailure(frame.Show()); } if (focus) { var content = window.Content as System.Windows.UIElement; if (content != null) { content.Focus(); } } } return window; } internal void NewCookiecutterSession(ProjectLocation location = null) { var pane = ShowWindowPane(typeof(CookiecutterToolWindow), true) as CookiecutterToolWindow; pane.NewSession(location); } private int ViewExternalBrowser(IntPtr variantIn, IntPtr variantOut, uint commandExecOpt) { if (IsQueryParameterList(variantIn, variantOut, commandExecOpt)) { Marshal.GetNativeVariantForObject("url", variantOut); return VSConstants.S_OK; } var name = GetStringArgument(variantIn) ?? ""; var uri = name.Trim('"'); if (File.Exists(uri)) { var ext = Path.GetExtension(uri); if (string.Compare(ext, ".htm", StringComparison.CurrentCultureIgnoreCase) == 0 || string.Compare(ext, ".html", StringComparison.CurrentCultureIgnoreCase) == 0) { Process.Start(uri)?.Dispose(); } } else { Uri u; if (Uri.TryCreate(uri, UriKind.Absolute, out u)) { if (u.Scheme == Uri.UriSchemeHttp || u.Scheme == Uri.UriSchemeHttps) { Process.Start(uri)?.Dispose(); } } } return VSConstants.S_OK; } internal string RecommendedFeed { get { var page = (CookiecutterOptionPage)GetDialogPage(typeof(CookiecutterOptionPage)); return page.FeedUrl; } } internal bool ShowHelp { get { var page = (CookiecutterOptionPage)GetDialogPage(typeof(CookiecutterOptionPage)); return page.ShowHelp; } set { var page = (CookiecutterOptionPage)GetDialogPage(typeof(CookiecutterOptionPage)); page.ShowHelp = value; page.SaveSettingsToStorage(); } } internal bool CheckForTemplateUpdate { get { var page = (CookiecutterOptionPage)GetDialogPage(typeof(CookiecutterOptionPage)); return page.CheckForTemplateUpdate; } set { var page = (CookiecutterOptionPage)GetDialogPage(typeof(CookiecutterOptionPage)); page.CheckForTemplateUpdate = value; page.SaveSettingsToStorage(); } } } }
/* * ColumnHeader.cs - Implementation of the * "System.Windows.Forms.ColumnHeader" class. * * Copyright (C) 2003 Neil Cawse. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Windows.Forms { using System; using System.Reflection; using System.ComponentModel; #if CONFIG_COMPONENT_MODEL [DefaultProperty("Text")] [DesignTimeVisible(false)] [ToolboxItem(false)] public class ColumnHeader : Component, ICloneable #else public class ColumnHeader : ICloneable, IDisposable #endif { internal ListView listView; internal int width; internal HorizontalAlignment textAlign; internal string text; internal int index; public ColumnHeader() { width = 60; textAlign = HorizontalAlignment.Left; index = -1; } #if !CONFIG_COMPONENT_MODEL // Destuctor. ~ColumnHeader() { Dispose(false); } #endif #if CONFIG_COMPONENT_MODEL [Browsable(false)] #endif public ListView ListView { get { return listView; } } #if CONFIG_COMPONENT_MODEL [Browsable(false)] #endif public int Index { get { return index; } } #if CONFIG_COMPONENT_MODEL [Localizable(true)] [DefaultValue(HorizontalAlignment.Left)] #endif [TODO] public HorizontalAlignment TextAlign { get { return textAlign; } set { if (value == textAlign) { return; } if (index == 0) { textAlign = HorizontalAlignment.Left; } else { textAlign = value; } if (listView != null) { // Fix: Update ListView } } } #if CONFIG_COMPONENT_MODEL [Localizable(true)] [DefaultValue(60)] #endif [TODO] public int Width { get { return width; } set { if (value == width) { return; } width = value; if (listView != null) { // Fix: Set Column width // Fix: Update ListView } } } public virtual object Clone() { ColumnHeader columnHeader = null; Type type = base.GetType(); if (type == typeof(ColumnHeader)) { columnHeader = new ColumnHeader(); } #if !ECMA_COMPAT else { columnHeader = Activator.CreateInstance(type) as ColumnHeader; } #else else columnHeader = type.InvokeMember (String.Empty, BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance, null, null, null, null, null, null) as ColumnHeader; #endif columnHeader.textAlign = TextAlign; columnHeader.text = text; columnHeader.Width = width; return columnHeader; } #if CONFIG_COMPONENT_MODEL [Localizable(true)] #endif [TODO] public string Text { get { if (text == null) { return "ColumnHeader"; } else { return text; } } set { if (value == text) { return; } if (value == null) { text = string.Empty; } else { text = value; } if (listView != null) { // Fix: Update ListView } } } public override string ToString() { return "ColumnHeader: Text: " + Text; } #if !CONFIG_COMPONENT_MODEL // Implement the IDisposable interface. public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endif protected #if CONFIG_COMPONENT_MODEL override #else virtual #endif void Dispose(bool disposing) { if (disposing && listView != null) { if (index != -1) { listView.Columns.RemoveAt(index); } listView = null; } #if CONFIG_COMPONENT_MODEL base.Dispose(disposing); #endif } } }
// 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 gagvr = Google.Ads.GoogleAds.V10.Resources; using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>CarrierConstant</c> resource.</summary> public sealed partial class CarrierConstantName : gax::IResourceName, sys::IEquatable<CarrierConstantName> { /// <summary>The possible contents of <see cref="CarrierConstantName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>carrierConstants/{criterion_id}</c>.</summary> Criterion = 1, } private static gax::PathTemplate s_criterion = new gax::PathTemplate("carrierConstants/{criterion_id}"); /// <summary>Creates a <see cref="CarrierConstantName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="CarrierConstantName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CarrierConstantName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CarrierConstantName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CarrierConstantName"/> with the pattern <c>carrierConstants/{criterion_id}</c>. /// </summary> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="CarrierConstantName"/> constructed from the provided ids.</returns> public static CarrierConstantName FromCriterion(string criterionId) => new CarrierConstantName(ResourceNameType.Criterion, criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CarrierConstantName"/> with pattern /// <c>carrierConstants/{criterion_id}</c>. /// </summary> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CarrierConstantName"/> with pattern /// <c>carrierConstants/{criterion_id}</c>. /// </returns> public static string Format(string criterionId) => FormatCriterion(criterionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CarrierConstantName"/> with pattern /// <c>carrierConstants/{criterion_id}</c>. /// </summary> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CarrierConstantName"/> with pattern /// <c>carrierConstants/{criterion_id}</c>. /// </returns> public static string FormatCriterion(string criterionId) => s_criterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))); /// <summary> /// Parses the given resource name string into a new <see cref="CarrierConstantName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>carrierConstants/{criterion_id}</c></description></item></list> /// </remarks> /// <param name="carrierConstantName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CarrierConstantName"/> if successful.</returns> public static CarrierConstantName Parse(string carrierConstantName) => Parse(carrierConstantName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CarrierConstantName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>carrierConstants/{criterion_id}</c></description></item></list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="carrierConstantName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="CarrierConstantName"/> if successful.</returns> public static CarrierConstantName Parse(string carrierConstantName, bool allowUnparsed) => TryParse(carrierConstantName, allowUnparsed, out CarrierConstantName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CarrierConstantName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>carrierConstants/{criterion_id}</c></description></item></list> /// </remarks> /// <param name="carrierConstantName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CarrierConstantName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string carrierConstantName, out CarrierConstantName result) => TryParse(carrierConstantName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CarrierConstantName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>carrierConstants/{criterion_id}</c></description></item></list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="carrierConstantName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="CarrierConstantName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string carrierConstantName, bool allowUnparsed, out CarrierConstantName result) { gax::GaxPreconditions.CheckNotNull(carrierConstantName, nameof(carrierConstantName)); gax::TemplatedResourceName resourceName; if (s_criterion.TryParseName(carrierConstantName, out resourceName)) { result = FromCriterion(resourceName[0]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(carrierConstantName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private CarrierConstantName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string criterionId = null) { Type = type; UnparsedResource = unparsedResourceName; CriterionId = criterionId; } /// <summary> /// Constructs a new instance of a <see cref="CarrierConstantName"/> class from the component parts of pattern /// <c>carrierConstants/{criterion_id}</c> /// </summary> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> public CarrierConstantName(string criterionId) : this(ResourceNameType.Criterion, criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CriterionId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.Criterion: return s_criterion.Expand(CriterionId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as CarrierConstantName); /// <inheritdoc/> public bool Equals(CarrierConstantName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CarrierConstantName a, CarrierConstantName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CarrierConstantName a, CarrierConstantName b) => !(a == b); } public partial class CarrierConstant { /// <summary> /// <see cref="gagvr::CarrierConstantName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> internal CarrierConstantName ResourceNameAsCarrierConstantName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::CarrierConstantName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagvr::CarrierConstantName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> internal CarrierConstantName CarrierConstantName { get => string.IsNullOrEmpty(Name) ? null : gagvr::CarrierConstantName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.IO; using NUnit.Framework; using Raksha.Asn1; using Raksha.Asn1.Pkcs; using Raksha.Asn1.X509; using Raksha.Utilities; using Raksha.Utilities.Encoders; using Raksha.Tests.Utilities; namespace Raksha.Tests.Asn1 { [TestFixture] public class Pkcs12Test : SimpleTest { private static byte[] pkcs12 = Base64.Decode( "MIACAQMwgAYJKoZIhvcNAQcBoIAkgASCA+gwgDCABgkqhkiG9w0BBwGggCSA" + "BIIDRDCCA0AwggM8BgsqhkiG9w0BDAoBAqCCArEwggKtMCcGCiqGSIb3DQEM" + "AQMwGQQUFlnNVpQoEHc+J3UEGxARipkHu5kCAWQEggKAAH9tmy40lly6QDoc" + "1TfmY9y2qysD+lrgk+dnxP04RfoJfycTRDeaz2sPLImZtio9nsqCFqtzU/sl" + "eWigbH34BpKU1sC0Gq1cyik0GO65sW95S6YjKtGcGOBfQCPk1oQjfiqnfU3G" + "oeOaG3COQJukMFj8unv55u0xbX1hwO8SsZmr9RjPzLrVaeY6BP5+CCzOKBaj" + "GxneIDqnQW7/kBIVWK7M+JXGdgQyiKhD6NvXL/zD8oKEne0nIX7IokQuWEn6" + "8Sglv5OSclsSdvHTk57bCuV5lVzoIzczA4J/LZWdrtITeVefBLQSalBzpRde" + "rSTMj485z2x5ChizhjE627/KQ5vkKQkQVqXYYXVyeTvKZRpL7vz13C4DUCwN" + "im1XvNSCNebXS1yHJRtcONDhGJN3UsrVjHr+2kCfE5SCEeSU/dqgNLuLa1tk" + "5+jwZFNj/HjO88wlOwPCol1uuJjDpaEW7dxu5qsVSfZhEXWHs8rZAMttFMzi" + "yxsEkZe8kqngRbNJOY6KpppYedsMWDusUJGfIHo+8zymiw3gv/z+lmFOlDGt" + "CKMk9Es/MgfjpbfhbTVYHOBKS6Qyrz7LdTuBMI8XdsZMuN+Uf73690ggLmKW" + "IELUg8h1RX0ra2n6jOc/1rnebAifMhiMkL1ABQvqOobfOrG/9h9XcXoi64Qr" + "htc3T7yMAHafBX5KUcNkbcn6kssYhpvd8bPADoLBnbx3GxGh/uziB0zKQEI0" + "GnaY4SL7aR4C5xNNi41lYtsR6ohKyfPEGslhrhd4axx0cKxC2sHgVl0k+r8B" + "8Vu44XHbW8LqdspjOHN9qg2erES1Dvgj05SfHDup+V6a3ogJo2YKXOiu3DF4" + "MFEGCSqGSIb3DQEJFDFEHkIARABhAHYAaQBkACAARwAuACAASABvAG8AawAn" + "AHMAIABWAGUAcgBpAFMAaQBnAG4ALAAgAEkAbgBjAC4AIABJAEQwIwYJKoZI" + "hvcNAQkVMRYEFKEcMJ798oZLFkH0OnpbUBnrTLgWAAAAAAAAMIAGCSqGSIb3" + "DQEHBqCAMIACAQAwgAYJKoZIhvcNAQcBMCcGCiqGSIb3DQEMAQYwGQQUTErH" + "kWZ8nBXZYWO53FH4yqRZZsECAWSggASCDGCreuCr6/azcOv5w04bN3jkg4G2" + "dsvTPAjL8bichaEOQCykhuNPt1dv3FsjUsdFC550K0+Y48RyBIID6JTiN9Gj" + "K+a5aLPaXgTRdY74Toof1hYtZ4DIcVyq25LezVQHoe/++pAgEpWjqHTxVDIv" + "YFAgT2oDB+2vkeXM61XnNWOjwCY3pXpk/VGjyN4USkD7Q/Y6tPjQOywvQE7c" + "Ab1z62k9iMia7Yk/qmh+zJu4SSneo0/RLLdMZOlGZv89MResVG038TC8MTA9" + "Uf+wDRcS20d7XDbTaBAgju8TpFIw5/lbDi0feUVlk6L+jkT1ktaTc1Pwtxn7" + "psXMFW6HAWB4exOi09297R9BCOQX6vcetK/iA/3jIC6NuTdizYof0DWetdGy" + "haIkMiEnERYE3unJocH4fq585Rw6mE+BYssPVPkVWZZInF3l69bKduuxsQt+" + "pcApgBVsTjsU+1FOiUxuW2wWKi70RcQprPv5Ef1A5FRNxPFp+7IzLNlE4qCo" + "wvC6NTpeuRw3aGsXSfqHmSddrHugNPmghNgG5lv1Ef7A8MUuyp8fyjAgxCDk" + "4Hpb8PCHGj5t//Fr6Cd0MygJMIFQmv4kUd2LVHxQ9A9WFNCqTz/nBe+ZRLJL" + "NghTv6gGpjGJiBnXYv6Sod2fs+5J2GIvex4qbdh6gzZIU2YTAwpj6Aca3SjA" + "X8+m8AXt2SC3Z6T5+m8SxyiNp2P511paV/TZKtLWXQGKeEX1JXhQkaM6Q5W/" + "IhSgC8/gppk1gbIraBqrW8bEnGBnC03wi0OnMz3ohM4CVHyaW3dQquT2+u6F" + "8VeGXAYHU022NkrpPl/VlfNNEAyisU2+oJqpPZkqL6FsDWF3k6Fq2jXBLL+/" + "a0WA82jIpgjNeXze/cgoHtU023V9E9Qcu+5nPBYdCTR4sRxvHLANii0W8lPv" + "tvU5XO1UsEjHDfKL4E1bhGzGpb/OU5yg/98EN95r/xdFL5G+XVyHeR0UtkcB" + "IuvyBdhkwoprCjkcgLZe8FPIBNw84HRe7Ye6f2gDW/F5uej6rBehJS1VFvCh" + "DXzkajGmK40Gc2APS1/1vZqPu68polgw9dT84rem36PLEOq4KuU7n4QE0g7T" + "YR2G8+4FNgQTjjg/qw3lX+sj6yLn1lYt1dOVvkiM8i8tdZg/3pCKKAW1uV7a" + "astlBxVSkFfn1BrFTc2oFGkTrlUg90a+parOfGHTfDiaHX8ouEg63fk0+Xdi" + "FCarXsqHNPDbpmWLKw8TAmdeneGipyScntJJk4ajy+jROQBgGew3ofOmfkqm" + "oJFNwUvKOXN2ucViLZgsdK/7YgV1OR7oiTh8knQNPk3d5fRYSMFf9GJTjQRV" + "y2CLdICAVzvrUXf9k7miWYkjIp2/HGD7pOH018sX9MrpfJKqvdPFOssZiFd0" + "I2FUbgcEggPotvnT0XoabEiurTm8EPPpw66NKmK/H1kQL0hEtdIazPxfLmm/" + "ZUDokwa7d4bE3BwFh0weQfEvMzJu6Y5E7ir2MqD33XaGMOGys1nst1SPPyDB" + "WpOWD9w7Ng3yU1JVzqFWuVXaXDYbfnlG7AGevKF5PYNZj/RIQBBf5Xle9hTd" + "c9CtxPkrsJwA8DeAwKl2WIfbXGzAYLSnXoYUcoTkWn/O81BlUFgAXv80gLe8" + "NUrH7bhsnyGaPY953NyDk8IWUYrsn/sXvxTy5B0/7/WGMh3CSZrLX3p7TcFY" + "yBrL6SRas4q9rrcwuhBq0tUUbbgWi92nhZl4bOGmx7ehHnwuUId2HWXyVGoB" + "qToee/2E4PZFxSZwKCY6dahswFq5QGDrQKN2/qpOLZcJib6SvSGyEZl2pqr0" + "lqk7tVPzBkN/4uP0qrcbZCDbGW6IXwu3RGMRehqj/HEJcs92lZKfVrk/U07X" + "MBAiQHqV+kLw7kStECR/MGJG1c0xhqqBrf0W74+LpJiv/Q9iFNdWbXvE/cAk" + "G7+OTUABd2kI88uA43T0UoRuPOi5KnLuD3AG+7IuyGyP69Xncd4u0srMg2fn" + "DiLLZUy6vWmxwRFsSMCEfQNLtZaggukoPIihQvbX3mQS9izwLs6D89WtEcZ5" + "6DVbIlUqUinnNKsT8vW1DZo5FMJkUxB666YIPVmkQbbJOEUU89dZg5Gw0og6" + "rn4irEr4xHFdx+S7iqJXhzs9THg/9e4/k8KQ136z7LALOqDookcSdBzW6H8c" + "STjs4qKQyNimsLB90mEuIEApzhseAaLFl+kgORGJv/2a+uoukZchMsJ98MVo" + "sEPS1oBXJl2m9AshkWfON2GDeJatgcw6CyC1mSx++Gg602ZKUZZUaWxkz1Sw" + "zTj3nhiJe+SZsdfxhsojNq7zfxqgY/Rq7BwvphU3StjnxvkB4rTkbmbiGOBO" + "cvTFg4yOtQGRcifk2/XH/bgYiPqQrYSXpO3WRASV005RaSGufcpTtj3YlHGe" + "8FUgZfDtfiGezhNET9KO3/Q0i34bGEpoIb/9uOWH4ZHULIlfdSm1ynV50nE4" + "mJTXccrF6BE80KZI5GWGhqXdfPFaHTK1S20+XCw7bRJCGeiwVxvGfB+C0SZ4" + "ndtqx165dKG5JwFukcygiIZN6foh0/PhwzmFxmPtZuPQt9dtuIQ35Y7PSDsy" + "IH2Ot0Hh0YIN99lHJ6n9HomSjpwcgDXGssEuevbpz27u/MI/Uhq4Gfx0k5RF" + "0pcRYtk1dYSx44a+8WgqZLF8DUNtyjSE/H8P5iGa6tqOl7kNyeeEkfoTtKst" + "asGFwL4Qxxus4GC7repyVi7IJgSCA+iopiqKQJ2IqUHvoIEuD//sZooDx0Je" + "oFRO5VakkTO6WHd8JpOOEU2f6Zjg++HdIl0QK7xcUaRH075LzEfqgn1vyw6J" + "N6ex8D76sf/nAy01NvDPij48Z50XDwXu4kJGJvv0AJwId8BpjziBF0j3K/DI" + "YOOpd6nW4EvdivCgaCnxqlIU/u1OP4BwpO+AUjJh6RKlKviGihQpi103DFhR" + "yXNDhh55pqgCCCuNeEB+ovRt7UxzlGAVRSxJh1Zbjp/+iQun0E32RlSR4Diz" + "p5vDk8NBZpIiKRqI+8GWZc3G1igp7dvViTLw4OdWMKwhccV5+3Ll/W72aNVm" + "azYUoYOVn+OYS1NJkER0tjFOCozRGm5hfkxGlP+02wbH5uu/AQoJMqWIxT6l" + "46IWC24lmAnDCXuM+gWmwUvyXLwuBdejVK8iG1Lnfg1qztoLpYRbBROgRdpt" + "2cbPRm+9seqrth3eJbtmxCvuh3bZ3pR2e0/r5Tob/fDcOc5Kp+j4ndXWkwpa" + "OuH1yxam7zNJR+mcYp1Wiujia5qIeY1QCAEY5QgAWaSHtjlEprwUuootA2Xm" + "V7D8Vsr9BValhm9zMKj6IzsPmM+HZJWlhHcoucuAmPK6Lnys3Kv/mbkSgNOq" + "fJDY901veFfKeqiCbAm6hZjNWoQDNJKFhjXUALrcOv9VCFPA3bMW3Xul/sB4" + "Mq595e+x/1HkNOgZorBv97C6X7ENVDaAFcyZvrRU/ZeDnvFhisfxS4EJhzxl" + "cWWnQhzD+ur1FTTlkmUFzgoB/rW+i3XigiHOuRRnkcoMy1uV17rwH8eELHJu" + "Yni5vu2QUaD4jNEhliE2XCsn8Sm6bcXnfzBa7FXC39QvAcdJHzqcD6iIwjIz" + "hKLu+/XoWFMFFNsgV78AwzPAn6TRya8LLCYPoIZkEP4qBoeZtUZ8PIS/Y7M9" + "QStMwa/NI9SPswb3iScTGvor/obUEQS4QM6mVxFMpQWfwJfyU6jingX4EHRE" + "mqvZ3ehzU8ZLOdKzRKuk022YDT7hwEQ+VL0Fg0Ld9oexqT96nQpUTHZtDRMV" + "iTuJoUYTneDs2c9tsY4mWBqamZQSfTegj4sLMZagkuSUp/SpPM2zSGuD3nY6" + "u3553gIM9jYhvLBEXwjGudVCwMd3bqo/4EhnKb2PcwUzdaMkipQlNteHZjBT" + "1ici63xjJva+di0qTV+W9cyYyHwg1927X2qcMh06BhbHlcXQKbgmbL18KJEt" + "K+GGhGNkP7mtPyHHgBb6vref/z8p7oxT2CG+oBuN/z+xQoYfe9c4IC3e/kNN" + "DIoyYvPyEzAdfMS2aL8qDxzc5GH9UE9kcusJ/2dNEFTzBH2GK1CItL3IACv/" + "LwX1SkI0w7oIQTL127CSnuTrUUkvJ/+rOYScQTMD/ntZPdLdu2ffszg3SzhN" + "ELgojK8ss1OBlruWRHw/fP736Nx8MNsuOvXMnO8lruz+uyuEhF3BLv96oTcg" + "XVHdWhPmOoqNdBQdRgAAAAAAAAAAAAAAAAAAAAAAADA8MCEwCQYFKw4DAhoF" + "AAQUJMZn7MEKv4vW/+voCVyHBa6B0EMEFJOzH/BEjRtNNsZWlo/4L840aE5r" + "AgFkAAA="); public override void PerformTest() { Asn1Sequence obj = (Asn1Sequence) Asn1Object.FromByteArray(pkcs12); Pfx bag = new Pfx(obj); ContentInfo info = bag.AuthSafe; MacData mData = bag.MacData; DigestInfo dInfo = mData.Mac; AlgorithmIdentifier algId = dInfo.AlgorithmID; byte[] salt = mData.GetSalt(); int itCount = mData.IterationCount.IntValue; byte[] octets = ((Asn1OctetString) info.Content).GetOctets(); AuthenticatedSafe authSafe = new AuthenticatedSafe( (Asn1Sequence) Asn1Object.FromByteArray(octets)); ContentInfo[] c = authSafe.GetContentInfo(); // // private key section // if (!c[0].ContentType.Equals(PkcsObjectIdentifiers.Data)) { Fail("Failed comparison data test"); } octets = ((Asn1OctetString)c[0].Content).GetOctets(); Asn1Sequence seq = (Asn1Sequence) Asn1Object.FromByteArray(octets); SafeBag b = new SafeBag((Asn1Sequence)seq[0]); if (!b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { Fail("Failed comparison shroudedKeyBag test"); } EncryptedPrivateKeyInfo encInfo = EncryptedPrivateKeyInfo.GetInstance(b.BagValue); encInfo = new EncryptedPrivateKeyInfo(encInfo.EncryptionAlgorithm, encInfo.GetEncryptedData()); b = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, encInfo.ToAsn1Object(), b.BagAttributes); byte[] encodedBytes = new DerSequence(b).GetEncoded(); c[0] = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(encodedBytes)); // // certificates // if (!c[1].ContentType.Equals(PkcsObjectIdentifiers.EncryptedData)) { Fail("Failed comparison encryptedData test"); } EncryptedData eData = EncryptedData.GetInstance(c[1].Content); c[1] = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, eData); // // create an octet stream to represent the BER encoding of authSafe // authSafe = new AuthenticatedSafe(c); info = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(authSafe.GetEncoded())); mData = new MacData(new DigestInfo(algId, dInfo.GetDigest()), salt, itCount); bag = new Pfx(info, mData); // // comparison test // if (!Arrays.AreEqual(bag.GetEncoded(), pkcs12)) { Fail("Failed comparison test"); } } public override string Name { get { return "Pkcs12"; } } public static void Main( string[] args) { RunTest(new Pkcs12Test()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.ActionConstraints; using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Cors; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.AspNetCore.Mvc.Razor.TagHelpers; using Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Mvc.TagHelpers; using Microsoft.AspNetCore.Mvc.ViewComponents; using Microsoft.AspNetCore.Mvc.ViewEngines; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Mvc.ViewFeatures.Filters; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using Moq; using Xunit; namespace Microsoft.AspNetCore.Mvc { public class MvcServiceCollectionExtensionsTest { // Some MVC services can be registered multiple times, for example, 'IConfigureOptions<MvcOptions>' can // be registered by calling 'ConfigureMvc(...)' before the call to 'AddMvc()' in which case the options // configuration is run in the order they were registered. // // For these kind of multi registration service types, we want to make sure that MVC will still add its // services if the implementation type is different. [Fact] public void AddMvc_MultiRegistrationServiceTypes_AreRegistered_MultipleTimes() { // Arrange var services = new ServiceCollection(); services.AddSingleton<IWebHostEnvironment>(GetHostingEnvironment()); RegisterMockMultiRegistrationServices(services); // Act services.AddMvc(); // Assert VerifyMultiRegistrationServices(services); } private void RegisterMockMultiRegistrationServices(IServiceCollection services) { // Register a mock implementation of each service, AddMvcServices should add another implementation. foreach (var serviceType in MultiRegistrationServiceTypes) { var mockType = typeof(Mock<>).MakeGenericType(serviceType.Key); services.Add(ServiceDescriptor.Transient(serviceType.Key, mockType)); } } private void VerifyMultiRegistrationServices(IServiceCollection services) { foreach (var serviceType in MultiRegistrationServiceTypes) { AssertServiceCountEquals(services, serviceType.Key, serviceType.Value.Length + 1); foreach (var implementationType in serviceType.Value) { AssertContainsSingle(services, serviceType.Key, implementationType); } } } [Fact] public void AddMvc_SingleRegistrationServiceTypes_AreNotRegistered_MultipleTimes() { // Arrange var services = new ServiceCollection(); services.AddSingleton<IWebHostEnvironment>(GetHostingEnvironment()); RegisterMockSingleRegistrationServices(services); // Act services.AddMvc(); // Assert VerifySingleRegistrationServices(services); } [Fact] public void AddControllers_AddRazorPages_SingleRegistrationServiceTypes_AreNotRegistered_MultipleTimes() { // Arrange var services = new ServiceCollection(); services.AddSingleton<IWebHostEnvironment>(GetHostingEnvironment()); RegisterMockSingleRegistrationServices(services); // Act services.AddControllers(); services.AddRazorPages(); // Assert VerifySingleRegistrationServices(services); } [Fact] public void AddControllersWithViews_SingleRegistrationServiceTypes_AreNotRegistered_MultipleTimes() { // Arrange var services = new ServiceCollection(); services.AddSingleton<IWebHostEnvironment>(GetHostingEnvironment()); RegisterMockSingleRegistrationServices(services); // Act services.AddControllers(); // Assert VerifySingleRegistrationServices(services); } [Fact] public void AddRazorPages_SingleRegistrationServiceTypes_AreNotRegistered_MultipleTimes() { // Arrange var services = new ServiceCollection(); services.AddSingleton<IWebHostEnvironment>(GetHostingEnvironment()); RegisterMockSingleRegistrationServices(services); // Act services.AddRazorPages(); // Assert VerifySingleRegistrationServices(services); } private void RegisterMockSingleRegistrationServices(IServiceCollection services) { // Register a mock implementation of each service, AddMvcServices should not replace it. foreach (var serviceType in SingleRegistrationServiceTypes) { var mockType = typeof(Mock<>).MakeGenericType(serviceType); services.Add(ServiceDescriptor.Transient(serviceType, mockType)); } } private void VerifySingleRegistrationServices(IServiceCollection services) { foreach (var singleRegistrationType in SingleRegistrationServiceTypes) { AssertServiceCountEquals(services, singleRegistrationType, 1); } } [Fact] public void AddMvc_Twice_DoesNotAddDuplicates() { // Arrange var services = new ServiceCollection(); services.AddSingleton<IWebHostEnvironment>(GetHostingEnvironment()); // Act services.AddMvc(); services.AddMvc(); // Assert VerifyAllServices(services); } [Fact] public void AddControllersAddRazorPages_Twice_DoesNotAddDuplicates() { // Arrange var services = new ServiceCollection(); services.AddSingleton<IWebHostEnvironment>(GetHostingEnvironment()); // Act services.AddControllers(); services.AddRazorPages(); services.AddControllers(); services.AddRazorPages(); // Assert VerifyAllServices(services); } [Fact] public void AddControllersWithViews_Twice_DoesNotAddDuplicates() { // Arrange var services = new ServiceCollection(); services.AddSingleton<IWebHostEnvironment>(GetHostingEnvironment()); // Act services.AddControllersWithViews(); services.AddControllersWithViews(); // Assert VerifyAllServices(services); } [Fact] public void AddRazorPages_Twice_DoesNotAddDuplicates() { // Arrange var services = new ServiceCollection(); services.AddSingleton<IWebHostEnvironment>(GetHostingEnvironment()); // Act services.AddRazorPages(); services.AddRazorPages(); // Assert VerifyAllServices(services); } [Fact] public void AddControllersWithViews_AddsDocumentedServices() { // Arrange var services = new ServiceCollection(); services.AddControllersWithViews(); // Assert // Adds controllers Assert.Contains(services, s => s.ServiceType == typeof(IActionInvokerProvider) && s.ImplementationType == typeof(ControllerActionInvokerProvider)); // Adds ApiExplorer Assert.Contains(services, s => s.ServiceType == typeof(IApiDescriptionGroupCollectionProvider)); // Adds CORS Assert.Contains(services, s => s.ServiceType == typeof(CorsAuthorizationFilter)); // Adds DataAnnotations Assert.Contains(services, s => s.ServiceType == typeof(IConfigureOptions<MvcOptions>) && s.ImplementationType == typeof(MvcDataAnnotationsMvcOptionsSetup)); // Adds FormatterMappings Assert.Contains(services, s => s.ServiceType == typeof(FormatFilter)); // Adds Views Assert.Contains(services, s => s.ServiceType == typeof(IHtmlHelper)); // Adds Razor Assert.Contains(services, s => s.ServiceType == typeof(IRazorViewEngine)); // Adds CacheTagHelper Assert.Contains(services, s => s.ServiceType == typeof(CacheTagHelperMemoryCacheFactory)); // No Razor Pages Assert.Empty(services.Where(s => s.ServiceType == typeof(IActionInvokerProvider) && s.ImplementationType == typeof(PageActionInvokerProvider))); } private void VerifyAllServices(IServiceCollection services) { var singleRegistrationServiceTypes = SingleRegistrationServiceTypes; foreach (var service in services) { if (singleRegistrationServiceTypes.Contains(service.ServiceType)) { // 'single-registration' services should only have one implementation registered. AssertServiceCountEquals(services, service.ServiceType, 1); } else if (service.ImplementationType != null && !service.ImplementationType.Assembly.FullName.Contains("Mvc")) { // Ignore types that don't come from MVC } else { // 'multi-registration' services should only have one *instance* of each implementation registered. AssertContainsSingle(services, service.ServiceType, service.ImplementationType); } } } [Fact] public void AddMvc_AddsAssemblyPartsForFrameworkTagHelpers() { // Arrange var mvcRazorAssembly = typeof(UrlResolutionTagHelper).Assembly; var mvcTagHelpersAssembly = typeof(InputTagHelper).Assembly; var services = new ServiceCollection(); var providers = new IApplicationFeatureProvider[] { new ControllerFeatureProvider(), new ViewComponentFeatureProvider() }; // Act services.AddMvc(); // Assert var descriptor = Assert.Single(services, d => d.ServiceType == typeof(ApplicationPartManager)); Assert.Equal(ServiceLifetime.Singleton, descriptor.Lifetime); Assert.NotNull(descriptor.ImplementationInstance); var manager = Assert.IsType<ApplicationPartManager>(descriptor.ImplementationInstance); Assert.Equal(2, manager.ApplicationParts.Count); Assert.Single(manager.ApplicationParts.OfType<AssemblyPart>(), p => p.Assembly == mvcRazorAssembly); Assert.Single(manager.ApplicationParts.OfType<AssemblyPart>(), p => p.Assembly == mvcTagHelpersAssembly); } [Fact] public void AddMvcTwice_DoesNotAddDuplicateFrameworkParts() { // Arrange var mvcRazorAssembly = typeof(UrlResolutionTagHelper).Assembly; var mvcTagHelpersAssembly = typeof(InputTagHelper).Assembly; var services = new ServiceCollection(); var providers = new IApplicationFeatureProvider[] { new ControllerFeatureProvider(), new ViewComponentFeatureProvider() }; // Act services.AddMvc(); services.AddMvc(); // Assert var descriptor = Assert.Single(services, d => d.ServiceType == typeof(ApplicationPartManager)); Assert.Equal(ServiceLifetime.Singleton, descriptor.Lifetime); Assert.NotNull(descriptor.ImplementationInstance); var manager = Assert.IsType<ApplicationPartManager>(descriptor.ImplementationInstance); Assert.Equal(2, manager.ApplicationParts.Count); Assert.Single(manager.ApplicationParts.OfType<AssemblyPart>(), p => p.Assembly == mvcRazorAssembly); Assert.Single(manager.ApplicationParts.OfType<AssemblyPart>(), p => p.Assembly == mvcTagHelpersAssembly); } [Fact] public void AddMvcTwice_DoesNotAddApplicationFeatureProvidersTwice() { // Arrange var services = new ServiceCollection(); var providers = new IApplicationFeatureProvider[] { new ControllerFeatureProvider(), new ViewComponentFeatureProvider() }; // Act services.AddMvc(); services.AddMvc(); // Assert var descriptor = Assert.Single(services, d => d.ServiceType == typeof(ApplicationPartManager)); Assert.Equal(ServiceLifetime.Singleton, descriptor.Lifetime); Assert.NotNull(descriptor.ImplementationInstance); var manager = Assert.IsType<ApplicationPartManager>(descriptor.ImplementationInstance); Assert.Collection(manager.FeatureProviders, feature => Assert.IsType<ControllerFeatureProvider>(feature), feature => Assert.IsType<ViewComponentFeatureProvider>(feature), feature => Assert.IsType<TagHelperFeatureProvider>(feature), feature => Assert.IsType<RazorCompiledItemFeatureProvider>(feature)); } [Fact] public void AddMvcCore_ReusesExistingApplicationPartManagerInstance_IfFoundOnServiceCollection() { // Arrange var services = new ServiceCollection(); var manager = new ApplicationPartManager(); services.AddSingleton(manager); // Act services.AddMvc(); // Assert var descriptor = Assert.Single(services, d => d.ServiceType == typeof(ApplicationPartManager)); Assert.Same(manager, descriptor.ImplementationInstance); } [Fact] public void AddMvc_NoScopedServiceIsReferredToByASingleton() { // Arrange var services = new ServiceCollection(); var hostEnvironment = GetHostingEnvironment(); services.AddSingleton<IWebHostEnvironment>(hostEnvironment); services.AddSingleton<IHostEnvironment>(hostEnvironment); var diagnosticListener = new DiagnosticListener("Microsoft.AspNet"); services.AddSingleton<DiagnosticSource>(diagnosticListener); services.AddSingleton<DiagnosticListener>(diagnosticListener); services.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); services.AddLogging(); services.AddOptions(); services.AddMvc(); var root = services.BuildServiceProvider(validateScopes: true); var scopeFactory = root.GetRequiredService<IServiceScopeFactory>(); // Act & Assert using (var scope = scopeFactory.CreateScope()) { foreach (var serviceType in services.Select(d => d.ServiceType).Where(t => !t.IsGenericTypeDefinition).Distinct()) { // This will throw if something is invalid. scope.ServiceProvider.GetService(typeof(IEnumerable<>).MakeGenericType(serviceType)); } } } [Fact] public void AddMvc_RegistersExpectedTempDataProvider() { // Arrange var services = new ServiceCollection(); // Act services.AddMvc(); // Assert var descriptor = Assert.Single(services, item => item.ServiceType == typeof(ITempDataProvider)); Assert.Equal(typeof(CookieTempDataProvider), descriptor.ImplementationType); } [Fact] public void AddMvc_DoesNotRegisterCookieTempDataOptionsConfiguration() { // Arrange var services = new ServiceCollection(); // Act var builder = services.AddMvc(); // Assert Assert.DoesNotContain( services, item => item.ServiceType == typeof(IConfigureOptions<CookieTempDataProviderOptions>)); } private IEnumerable<Type> SingleRegistrationServiceTypes { get { var services = new ServiceCollection(); services.AddSingleton<IWebHostEnvironment>(GetHostingEnvironment()); services.AddMvc(); var multiRegistrationServiceTypes = MultiRegistrationServiceTypes; return services .Where(sd => !multiRegistrationServiceTypes.ContainsKey(sd.ServiceType)) .Where(sd => sd.ServiceType.Assembly.FullName.Contains("Mvc")) .Select(sd => sd.ServiceType); } } private Dictionary<Type, Type[]> MultiRegistrationServiceTypes { get { return new Dictionary<Type, Type[]>() { { typeof(IConfigureOptions<MvcOptions>), new Type[] { typeof(MvcCoreMvcOptionsSetup), typeof(MvcDataAnnotationsMvcOptionsSetup), typeof(TempDataMvcOptionsSetup), } }, { typeof(IConfigureOptions<RouteOptions>), new Type[] { typeof(MvcCoreRouteOptionsSetup), typeof(MvcCoreRouteOptionsSetup), } }, { typeof(IConfigureOptions<ApiBehaviorOptions>), new Type[] { typeof(ApiBehaviorOptionsSetup), } }, { typeof(IConfigureOptions<MvcViewOptions>), new Type[] { typeof(MvcViewOptionsSetup), typeof(MvcRazorMvcViewOptionsSetup), } }, { typeof(IConfigureOptions<RazorViewEngineOptions>), new[] { typeof(RazorViewEngineOptionsSetup), typeof(RazorPagesRazorViewEngineOptionsSetup), } }, { typeof(IPostConfigureOptions<MvcOptions>), new[] { typeof(MvcCoreMvcOptionsSetup), } }, { typeof(IActionConstraintProvider), new Type[] { typeof(DefaultActionConstraintProvider), } }, { typeof(IActionDescriptorProvider), new Type[] { typeof(ControllerActionDescriptorProvider), typeof(CompiledPageActionDescriptorProvider), } }, { typeof(IActionInvokerProvider), new Type[] { typeof(ControllerActionInvokerProvider), typeof(PageActionInvokerProvider), } }, { typeof(IRequestDelegateFactory), new Type[] { typeof(PageRequestDelegateFactory), typeof(ControllerRequestDelegateFactory) } }, { typeof(IFilterProvider), new Type[] { typeof(DefaultFilterProvider), } }, { typeof(IControllerPropertyActivator), new Type[] { typeof(DefaultControllerPropertyActivator), typeof(ViewDataDictionaryControllerPropertyActivator), } }, { typeof(IApplicationModelProvider), new Type[] { typeof(DefaultApplicationModelProvider), typeof(CorsApplicationModelProvider), typeof(AuthorizationApplicationModelProvider), typeof(TempDataApplicationModelProvider), typeof(ViewDataAttributeApplicationModelProvider), typeof(ApiBehaviorApplicationModelProvider), } }, { typeof(IApiDescriptionProvider), new Type[] { typeof(DefaultApiDescriptionProvider), } }, { typeof(IPageRouteModelProvider), new[] { typeof(CompiledPageRouteModelProvider), } }, { typeof(IPageApplicationModelProvider), new[] { typeof(AuthorizationPageApplicationModelProvider), typeof(AuthorizationPageApplicationModelProvider), typeof(DefaultPageApplicationModelProvider), typeof(TempDataFilterPageApplicationModelProvider), typeof(ViewDataAttributePageApplicationModelProvider), typeof(ResponseCacheFilterApplicationModelProvider), } }, }; } } private void AssertServiceCountEquals( IServiceCollection services, Type serviceType, int expectedServiceRegistrationCount) { var serviceDescriptors = services.Where(serviceDescriptor => serviceDescriptor.ServiceType == serviceType); var actual = serviceDescriptors.Count(); Assert.True( (expectedServiceRegistrationCount == actual), $"Expected service type '{serviceType}' to be registered {expectedServiceRegistrationCount}" + $" time(s) but was actually registered {actual} time(s)." + string.Join(Environment.NewLine, serviceDescriptors.Select(sd => sd.ImplementationType))); } private void AssertContainsSingle( IServiceCollection services, Type serviceType, Type implementationType) { var matches = services .Where(sd => sd.ServiceType == serviceType && sd.ImplementationType == implementationType) .ToArray(); if (matches.Length == 0) { Assert.True( false, $"Could not find an instance of {implementationType} registered as {serviceType}"); } else if (matches.Length > 1) { Assert.True( false, $"Found multiple instances of {implementationType} registered as {serviceType}"); } } private IWebHostEnvironment GetHostingEnvironment() { var environment = new Mock<IWebHostEnvironment>(); environment .Setup(e => e.ApplicationName) .Returns(typeof(MvcServiceCollectionExtensionsTest).Assembly.GetName().Name); return environment.Object; } } }
using System; using System.ComponentModel; using System.Web.UI; using System.Web.UI.WebControls; using Nucleo.Collections; using Nucleo.Newsletters; using Nucleo.Web.DataboundControls; using Nucleo.EventArguments; namespace Nucleo.Web.Newsletters { public class NewsletterAdministration : CompositeDataBoundControl, IPostBackEventHandler { private CollectionBase<DataboundItem> _items = null; private TextBox _newsletterName = null; private TextBox _newsletterDescription = null; #region " Events " public event DataEventHandler<DataboundItem> ItemCreated; public event DataEventHandler<DataboundItem> ItemDataBound; #endregion #region " Properties " new private object DataSource { get { return null; } set { throw new NotImplementedException(); } } new private string DataSourceID { get { return string.Empty; } set { throw new NotImplementedException(); } } [ DefaultValue("Delete"), Localizable(true) ] public string DeleteButtonText { get { object o = ViewState["DeleteButtonText"]; return (o == null) ? "Delete" : (string)o; } set { ViewState["DeleteButtonText"] = value; } } [ DefaultValue("Insert"), Localizable(true) ] public string InsertButtonText { get { object o = ViewState["InsertButtonText"]; return (o == null) ? "Insert" : (string)o; } set { ViewState["InsertButtonText"] = value; } } public CollectionBase<DataboundItem> Items { get { if (_items == null) _items = new CollectionBase<DataboundItem>(); return _items; } } #endregion #region " Methods " protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding) { int itemCount = 0; if (dataBinding) { if (!this.DesignMode) dataSource = Newsletter.GetAllNewsletters(); else dataSource = new string[] { "Data Bound 1", "Data Bound 2", "Data Bound 3" }; } Table table = new Table(); this.Controls.Add(table); this.Items.Clear(); foreach (object o in dataSource) this.Items.Add(this.CreateItem(table, o, itemCount++, dataBinding)); this.CreateFooter(table); return itemCount; } private void CreateFooter(Table table) { TableRow row = new TableRow(); table.Rows.Add(row); row.Cells.Add(new TableCell()); row.Cells[0].VerticalAlign = VerticalAlign.Top; row.Cells.Add(new TableCell()); row.Cells[1].VerticalAlign = VerticalAlign.Top; _newsletterName = new TextBox(); _newsletterName.ID = "txtNewsletterName"; _newsletterName.ValidationGroup = "NewsletterAdministration_Add"; row.Cells[0].Controls.Add(_newsletterName); row.Cells[0].Controls.Add(new LiteralControl("<br />")); _newsletterDescription = new TextBox(); _newsletterDescription.ID = "txtNewsletterDescription"; _newsletterDescription.ValidationGroup = "NewsletterAdministration_Add"; _newsletterDescription.TextMode = TextBoxMode.MultiLine; _newsletterDescription.Rows = 3; _newsletterDescription.Columns = 30; row.Cells[0].Controls.Add(_newsletterDescription); LinkButton button = new LinkButton(); button.Text = this.InsertButtonText; button.ValidationGroup = "NewsletterAdministration_Add"; button.CommandName = "insert"; row.Cells[1].Controls.Add(button); } protected virtual DataboundItem CreateItem(Table table, object dataItem, int index, bool dataBinding) { DataboundItem item = new DataboundItem(dataItem, index); table.Rows.Add(item); TableCell newsletterCell = new TableCell(); item.Cells.Add(newsletterCell); TableCell buttonCell = new TableCell(); item.Cells.Add(buttonCell); this.OnItemCreated(new DataEventArgs<DataboundItem>(item)); if (dataBinding) { newsletterCell.Text = (string)dataItem; this.OnItemDatabound(new DataEventArgs<DataboundItem>(item)); } LinkButton button = new LinkButton(); buttonCell.Controls.Add(button); button.Text = this.DeleteButtonText; button.CommandName = "delete"; button.CommandArgument = this.Items.Count.ToString(); return item; } private bool HandleEvent(CommandEventArgs args) { if (args.CommandName == "insert") { Page.Validate("NewsletterAdministration_Add"); if (Page.IsValid) { string name = _newsletterName.Text; string description = _newsletterDescription.Text; Newsletter.AddNewsletter(name, description); } } else if (args.CommandName == "delete") Newsletter.RemoveNewsletter(this.Items[int.Parse(args.CommandArgument.ToString())].Cells[0].Text); else return false; base.RequiresDataBinding = true; this.DataBind(); return true; } protected override bool OnBubbleEvent(object source, EventArgs args) { CommandEventArgs commandArgs = args as CommandEventArgs; if (commandArgs != null) return this.HandleEvent(commandArgs); return false; } protected virtual void OnItemCreated(DataEventArgs<DataboundItem> e) { if (ItemCreated != null) ItemCreated(this, e); } protected virtual void OnItemDatabound(DataEventArgs<DataboundItem> e) { if (ItemDataBound != null) ItemDataBound(this, e); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!Page.IsPostBack) this.DataBind(); } public void RaisePostBackEvent(string eventArgument) { if (eventArgument.Contains("$")) { string[] parts = eventArgument.Split('$'); CommandEventArgs args = new CommandEventArgs(parts[0], parts[1]); this.HandleEvent(args); } } #endregion } }
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com> using System; using System.IO; using System.Text; namespace HtmlAgilityPack { /// <summary> /// Represents a document with mixed code and text. ASP, ASPX, JSP, are good example of such documents. /// </summary> public class MixedCodeDocument { #region Fields private int _c; internal MixedCodeDocumentFragmentList _codefragments; private MixedCodeDocumentFragment _currentfragment; internal MixedCodeDocumentFragmentList _fragments; private int _index; private int _line; private int _lineposition; private ParseState _state; private Encoding _streamencoding; internal string _text; internal MixedCodeDocumentFragmentList _textfragments; /// <summary> /// Gets or sets the token representing code end. /// </summary> public string TokenCodeEnd = "%>"; /// <summary> /// Gets or sets the token representing code start. /// </summary> public string TokenCodeStart = "<%"; /// <summary> /// Gets or sets the token representing code directive. /// </summary> public string TokenDirective = "@"; /// <summary> /// Gets or sets the token representing response write directive. /// </summary> public string TokenResponseWrite = "Response.Write "; private string TokenTextBlock = "TextBlock({0})"; #endregion #region Constructors /// <summary> /// Creates a mixed code document instance. /// </summary> public MixedCodeDocument() { _codefragments = new MixedCodeDocumentFragmentList(this); _textfragments = new MixedCodeDocumentFragmentList(this); _fragments = new MixedCodeDocumentFragmentList(this); } #endregion #region Properties /// <summary> /// Gets the code represented by the mixed code document seen as a template. /// </summary> public string Code { get { string s = ""; int i = 0; foreach (MixedCodeDocumentFragment frag in _fragments) { switch (frag._type) { case MixedCodeDocumentFragmentType.Text: s += TokenResponseWrite + string.Format(TokenTextBlock, i) + "\n"; i++; break; case MixedCodeDocumentFragmentType.Code: s += ((MixedCodeDocumentCodeFragment) frag).Code + "\n"; break; } } return s; } } /// <summary> /// Gets the list of code fragments in the document. /// </summary> public MixedCodeDocumentFragmentList CodeFragments { get { return _codefragments; } } /// <summary> /// Gets the list of all fragments in the document. /// </summary> public MixedCodeDocumentFragmentList Fragments { get { return _fragments; } } /// <summary> /// Gets the encoding of the stream used to read the document. /// </summary> public Encoding StreamEncoding { get { return _streamencoding; } } /// <summary> /// Gets the list of text fragments in the document. /// </summary> public MixedCodeDocumentFragmentList TextFragments { get { return _textfragments; } } #endregion #region Public Methods /// <summary> /// Create a code fragment instances. /// </summary> /// <returns>The newly created code fragment instance.</returns> public MixedCodeDocumentCodeFragment CreateCodeFragment() { return (MixedCodeDocumentCodeFragment) CreateFragment(MixedCodeDocumentFragmentType.Code); } /// <summary> /// Create a text fragment instances. /// </summary> /// <returns>The newly created text fragment instance.</returns> public MixedCodeDocumentTextFragment CreateTextFragment() { return (MixedCodeDocumentTextFragment) CreateFragment(MixedCodeDocumentFragmentType.Text); } /// <summary> /// Loads a mixed code document from a stream. /// </summary> /// <param name="stream">The input stream.</param> public void Load(Stream stream) { Load(new StreamReader(stream)); } /// <summary> /// Loads a mixed code document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public void Load(Stream stream, bool detectEncodingFromByteOrderMarks) { Load(new StreamReader(stream, detectEncodingFromByteOrderMarks)); } /// <summary> /// Loads a mixed code document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> public void Load(Stream stream, Encoding encoding) { Load(new StreamReader(stream, encoding)); } /// <summary> /// Loads a mixed code document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public void Load(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks) { Load(new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks)); } /// <summary> /// Loads a mixed code document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> /// <param name="buffersize">The minimum buffer size.</param> public void Load(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize) { Load(new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks, buffersize)); } /// <summary> /// Loads a mixed code document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> public void Load(string path) { Load(new StreamReader(path)); } /// <summary> /// Loads a mixed code document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public void Load(string path, bool detectEncodingFromByteOrderMarks) { Load(new StreamReader(path, detectEncodingFromByteOrderMarks)); } /// <summary> /// Loads a mixed code document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> public void Load(string path, Encoding encoding) { Load(new StreamReader(path, encoding)); } /// <summary> /// Loads a mixed code document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public void Load(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks) { Load(new StreamReader(path, encoding, detectEncodingFromByteOrderMarks)); } /// <summary> /// Loads a mixed code document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> /// <param name="buffersize">The minimum buffer size.</param> public void Load(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize) { Load(new StreamReader(path, encoding, detectEncodingFromByteOrderMarks, buffersize)); } /// <summary> /// Loads the mixed code document from the specified TextReader. /// </summary> /// <param name="reader">The TextReader used to feed the HTML data into the document.</param> public void Load(TextReader reader) { _codefragments.Clear(); _textfragments.Clear(); // all pseudo constructors get down to this one StreamReader sr = reader as StreamReader; if (sr != null) { _streamencoding = sr.CurrentEncoding; } _text = reader.ReadToEnd(); reader.Close(); Parse(); } /// <summary> /// Loads a mixed document from a text /// </summary> /// <param name="html">The text to load.</param> public void LoadHtml(string html) { Load(new StringReader(html)); } /// <summary> /// Saves the mixed document to the specified stream. /// </summary> /// <param name="outStream">The stream to which you want to save.</param> public void Save(Stream outStream) { StreamWriter sw = new StreamWriter(outStream, GetOutEncoding()); Save(sw); } /// <summary> /// Saves the mixed document to the specified stream. /// </summary> /// <param name="outStream">The stream to which you want to save.</param> /// <param name="encoding">The character encoding to use.</param> public void Save(Stream outStream, Encoding encoding) { StreamWriter sw = new StreamWriter(outStream, encoding); Save(sw); } /// <summary> /// Saves the mixed document to the specified file. /// </summary> /// <param name="filename">The location of the file where you want to save the document.</param> public void Save(string filename) { StreamWriter sw = new StreamWriter(filename, false, GetOutEncoding()); Save(sw); } /// <summary> /// Saves the mixed document to the specified file. /// </summary> /// <param name="filename">The location of the file where you want to save the document.</param> /// <param name="encoding">The character encoding to use.</param> public void Save(string filename, Encoding encoding) { StreamWriter sw = new StreamWriter(filename, false, encoding); Save(sw); } /// <summary> /// Saves the mixed document to the specified StreamWriter. /// </summary> /// <param name="writer">The StreamWriter to which you want to save.</param> public void Save(StreamWriter writer) { Save((TextWriter) writer); } /// <summary> /// Saves the mixed document to the specified TextWriter. /// </summary> /// <param name="writer">The TextWriter to which you want to save.</param> public void Save(TextWriter writer) { writer.Flush(); } #endregion #region Internal Methods internal MixedCodeDocumentFragment CreateFragment(MixedCodeDocumentFragmentType type) { switch (type) { case MixedCodeDocumentFragmentType.Text: return new MixedCodeDocumentTextFragment(this); case MixedCodeDocumentFragmentType.Code: return new MixedCodeDocumentCodeFragment(this); default: throw new NotSupportedException(); } } internal Encoding GetOutEncoding() { if (_streamencoding != null) return _streamencoding; return Encoding.UTF8; } #endregion #region Private Methods private void IncrementPosition() { _index++; if (_c == 10) { _lineposition = 1; _line++; } else _lineposition++; } private void Parse() { _state = ParseState.Text; _index = 0; _currentfragment = CreateFragment(MixedCodeDocumentFragmentType.Text); while (_index < _text.Length) { _c = _text[_index]; IncrementPosition(); switch (_state) { case ParseState.Text: if (_index + TokenCodeStart.Length < _text.Length) { if (_text.Substring(_index - 1, TokenCodeStart.Length) == TokenCodeStart) { _state = ParseState.Code; _currentfragment.Length = _index - 1 - _currentfragment.Index; _currentfragment = CreateFragment(MixedCodeDocumentFragmentType.Code); SetPosition(); continue; } } break; case ParseState.Code: if (_index + TokenCodeEnd.Length < _text.Length) { if (_text.Substring(_index - 1, TokenCodeEnd.Length) == TokenCodeEnd) { _state = ParseState.Text; _currentfragment.Length = _index + TokenCodeEnd.Length - _currentfragment.Index; _index += TokenCodeEnd.Length; _lineposition += TokenCodeEnd.Length; _currentfragment = CreateFragment(MixedCodeDocumentFragmentType.Text); SetPosition(); continue; } } break; } } _currentfragment.Length = _index - _currentfragment.Index; } private void SetPosition() { _currentfragment.Line = _line; _currentfragment._lineposition = _lineposition; _currentfragment.Index = _index - 1; _currentfragment.Length = 0; } #endregion #region Nested type: ParseState private enum ParseState { Text, Code } #endregion } }
using System; using System.Data; using Codentia.Test.Helper; using NUnit.Framework; namespace Codentia.Common.MSOffice.Test { /// <summary> /// This class acts as the unit testing fixture for the static class ExcelOleDb /// <see cref="ExcelOleDb"/> /// </summary> [TestFixture] public class ExcelOleDbTest { /// <summary> /// Perform any activities required prior to unit testing (e.g. prepare test data) /// </summary> [TestFixtureSetUp] public void TextFixtureSetUp() { } /// <summary> /// Scenario: Invalid path or a path to a non-existant file specified /// Expected: Exception (Unable to open the specified file) /// </summary> [Test] public void _001_GetWorkSheetNames_InvalidFilePath() { // null Assert.That(delegate { ExcelOleDb.GetWorkSheetNames(OfficeFileFormat.Excel97_2003, null); }, Throws.InstanceOf<Exception>().With.Message.EqualTo("Unable to open the specified file")); // empty Assert.That(delegate { ExcelOleDb.GetWorkSheetNames(OfficeFileFormat.Excel97_2003, string.Empty); }, Throws.InstanceOf<Exception>().With.Message.EqualTo("Unable to open the specified file")); // non-existant Assert.That(delegate { ExcelOleDb.GetWorkSheetNames(OfficeFileFormat.Excel97_2003, @"Z:\ThisXLSDoesNotExist.xls"); }, Throws.InstanceOf<Exception>().With.Message.EqualTo("Unable to open the specified file - NOTE that 'enable 32bit' is required in IIS7/64bit!")); // not am xls Assert.That(delegate { ExcelOleDb.GetWorkSheetNames(OfficeFileFormat.Excel97_2003, @"TestData\TextFile1.txt"); }, Throws.InstanceOf<Exception>().With.Message.EqualTo("Unable to open the specified file - NOTE that 'enable 32bit' is required in IIS7/64bit!")); } /// <summary> /// Scenario: Work Sheet names retrieved for a workbook containing a single sheet /// Expected: string array of length 1 returned containing the expected name /// </summary> [Test] public void _002_GetWorkSheetNames_XLS_SingleSheet() { string[] names = ExcelOleDb.GetWorkSheetNames(OfficeFileFormat.Excel97_2003, @"TestData\xls1"); Assert.That(names.Length, Is.EqualTo(1), "Expected 1"); Assert.That(names[0], Is.EqualTo("Sheet1"), "Incorrect value"); } /// <summary> /// Scenario: Work sheet names retrieved for a workbook containing more than one sheets /// Expected: string array of appropriate length containing the correct names /// </summary> [Test] public void _003_GetWorkSheetNames_XLS_ManySheets() { string[] names = ExcelOleDb.GetWorkSheetNames(OfficeFileFormat.Excel97_2003, @"TestData\xls2"); Assert.That(names.Length, Is.EqualTo(3), "Expected 3"); Assert.That(names[0], Is.EqualTo("first"), "Incorrect value"); Assert.That(names[1], Is.EqualTo("second"), "Incorrect value"); Assert.That(names[2], Is.EqualTo("third"), "Incorrect value"); } /// <summary> /// Scenario: Invalid path or a path to a non-existant file specified /// Expected: Exception (Unable to open the specified file) /// </summary> [Test] public void _004_GetWorkSheet_InvalidFilePath() { // null Assert.That(delegate { ExcelOleDb.GetWorkSheet(OfficeFileFormat.Excel97_2003, null, "Sheet 1"); }, Throws.InstanceOf<Exception>().With.Message.EqualTo("Unable to open the specified file")); // empty Assert.That(delegate { ExcelOleDb.GetWorkSheet(OfficeFileFormat.Excel97_2003, string.Empty, "Sheet 1"); }, Throws.InstanceOf<Exception>().With.Message.EqualTo("Unable to open the specified file")); // non-existant Assert.That(delegate { ExcelOleDb.GetWorkSheet(OfficeFileFormat.Excel97_2003, @"Z:\ThisXLSDoesNotExist.xls", "Sheet 1"); }, Throws.InstanceOf<Exception>().With.Message.EqualTo("Unable to open the specified file - NOTE that 'enable 32bit' is required in IIS7/64bit!")); // not am xls Assert.That(delegate { ExcelOleDb.GetWorkSheet(OfficeFileFormat.Excel97_2003, @"TestData\TextFile1.txt", "Sheet 1"); }, Throws.InstanceOf<Exception>().With.Message.EqualTo("Unable to open the specified file - NOTE that 'enable 32bit' is required in IIS7/64bit!")); } /// <summary> /// Scenario: Attempt made to retrieve a worksheet from a valid workbook - sheet does not exist /// Expected: Exception (Unable to open the specified worksheet) /// </summary> [Test] public void _007_GetWorkSheet_XLS_NonExistant() { Assert.That(delegate { ExcelOleDb.GetWorkSheet(OfficeFileFormat.Excel97_2003, @"TestData\xls1.xls", "wibble"); }, Throws.InstanceOf<Exception>().With.Message.EqualTo("Unable to open the specified worksheet")); } /// <summary> /// Scenario: Existing worksheet within a valid workbook retrieved /// Expected: DataTable accurately representing the data within the XLS sheet /// </summary> [Test] public void _008_GetWorkSheet_XLS_Valid() { DataTable method = ExcelOleDb.GetWorkSheet(OfficeFileFormat.Excel97_2003, @"TestData\xls1.xls", "Sheet1"); DataTable check = ExcelHelper.LoadXLSSheetToDataTable(@"TestData\xls1.xls", "Sheet1", true); Assert.That(SqlHelper.CompareDataTables(check, method), Is.True, "Data does not match"); } /// <summary> /// Scenario: Invalid path or a path to a non-existant file specified /// Expected: Exception (Unable to open the specified file) /// </summary> [Test] public void _009_GetWorkBook_InvalidFilePath() { // null Assert.That(delegate { ExcelOleDb.GetWorkBook(OfficeFileFormat.Excel97_2003, null); }, Throws.InstanceOf<Exception>().With.Message.EqualTo("Unable to open the specified file")); // empty Assert.That(delegate { ExcelOleDb.GetWorkBook(OfficeFileFormat.Excel97_2003, string.Empty); }, Throws.InstanceOf<Exception>().With.Message.EqualTo("Unable to open the specified file")); // non-existant Assert.That(delegate { ExcelOleDb.GetWorkBook(OfficeFileFormat.Excel97_2003, @"Z:\ThisXLSDoesNotExist.xls"); }, Throws.InstanceOf<Exception>().With.Message.EqualTo("Unable to open the specified file - NOTE that 'enable 32bit' is required in IIS7/64bit!")); // not am xls Assert.That(delegate { ExcelOleDb.GetWorkBook(OfficeFileFormat.Excel97_2003, @"TestData\TextFile1.txt"); }, Throws.InstanceOf<Exception>().With.Message.EqualTo("Unable to open the specified file - NOTE that 'enable 32bit' is required in IIS7/64bit!")); } /// <summary> /// Scenario: Workbook containing a single sheet opened /// Expected: DataSet containing a single (appropriately named) DataTable which in turn contains the data from the worksheet /// </summary> [Test] public void _011_GetWorkBook_XLS_SingleSheet() { DataSet dsMethod = ExcelOleDb.GetWorkBook(OfficeFileFormat.Excel97_2003, @"TestData\xls1.xls"); Assert.That(dsMethod.Tables.Count, Is.EqualTo(1), "Incorrect count"); Assert.That(dsMethod.Tables[0].TableName, Is.EqualTo("Sheet1"), "Incorrect TableName"); DataTable check = ExcelHelper.LoadXLSSheetToDataTable(@"TestData\xls1.xls", "Sheet1", true); Assert.That(SqlHelper.CompareDataTables(check, dsMethod.Tables[0]), Is.True, "Data does not match"); } /// <summary> /// Scenario: Workbook containing more than one sheet opened /// Expected: DataSet contains one DataTable for each sheet in the workbook, each with the appropriate data /// </summary> [Test] public void _012_GetWorkBook_XLS_ManySheets() { DataSet dsMethod = ExcelOleDb.GetWorkBook(OfficeFileFormat.Excel97_2003, @"TestData\xls2.xls"); Assert.That(dsMethod.Tables.Count, Is.EqualTo(3), "Incorrect count"); Assert.That(dsMethod.Tables[0].TableName, Is.EqualTo("first"), "Incorrect TableName"); Assert.That(dsMethod.Tables[1].TableName, Is.EqualTo("second"), "Incorrect TableName"); Assert.That(dsMethod.Tables[2].TableName, Is.EqualTo("third"), "Incorrect TableName"); DataTable check1 = ExcelHelper.LoadXLSSheetToDataTable(@"TestData\xls2.xls", "first", true); DataTable check2 = ExcelHelper.LoadXLSSheetToDataTable(@"TestData\xls2.xls", "second", true); DataTable check3 = ExcelHelper.LoadXLSSheetToDataTable(@"TestData\xls2.xls", "third", true); Assert.That(SqlHelper.CompareDataTables(check1, dsMethod.Tables[0]), Is.True, "Data does not match"); Assert.That(SqlHelper.CompareDataTables(check2, dsMethod.Tables[1]), Is.True, "Data does not match"); Assert.That(SqlHelper.CompareDataTables(check3, dsMethod.Tables[2]), Is.True, "Data does not match"); } /// <summary> /// Scenario: Work Sheet names retrieved for a workbook containing a single sheet /// Expected: string array of length 1 returned containing the expected name /// </summary> [Test] public void _013_GetWorkSheetNames_XLSX_SingleSheet() { string[] names = ExcelOleDb.GetWorkSheetNames(OfficeFileFormat.Excel2007, @"TestData\xls1.xlsx"); Assert.That(names.Length, Is.EqualTo(1), "Expected 1"); Assert.That(names[0], Is.EqualTo("Sheet1"), "Incorrect value"); } /// <summary> /// Scenario: Work sheet names retrieved for a workbook containing more than one sheets /// Expected: string array of appropriate length containing the correct names /// </summary> [Test] public void _014_GetWorkSheetNames_XLSX_ManySheets() { string[] names = ExcelOleDb.GetWorkSheetNames(OfficeFileFormat.Excel2007, @"TestData\xls2.xlsx"); Assert.That(names.Length, Is.EqualTo(3), "Expected 3"); Assert.That(names[0], Is.EqualTo("first"), "Incorrect value"); Assert.That(names[1], Is.EqualTo("second"), "Incorrect value"); Assert.That(names[2], Is.EqualTo("third"), "Incorrect value"); } /// <summary> /// Scenario: Attempt made to retrieve a worksheet from a valid workbook - sheet does not exist /// Expected: Exception (Unable to open the specified worksheet) /// </summary> [Test] public void _015_GetWorkSheet_XLSX_NonExistant() { Assert.That(delegate { ExcelOleDb.GetWorkSheet(OfficeFileFormat.Excel2007, @"TestData\xls1.xlsx", "wibble"); }, Throws.InstanceOf<Exception>().With.Message.EqualTo("Unable to open the specified worksheet")); } /// <summary> /// Scenario: Existing worksheet within a valid workbook retrieved /// Expected: DataTable accurately representing the data within the XLS sheet /// </summary> [Test] public void _016_GetWorkSheet_XLSX_Valid() { DataTable method = ExcelOleDb.GetWorkSheet(OfficeFileFormat.Excel2007, @"TestData\xls1.xlsx", "Sheet1"); DataTable check = ExcelHelper.LoadXLSSheetToDataTable(@"TestData\xls1.xls", "Sheet1", true); Assert.That(SqlHelper.CompareDataTables(check, method), Is.True, "Data does not match"); } /// <summary> /// Scenario: Workbook containing a single sheet opened /// Expected: DataSet containing a single (appropriately named) DataTable which in turn contains the data from the worksheet /// </summary> [Test] public void _017_GetWorkBook_XLSX_SingleSheet() { DataSet dsMethod = ExcelOleDb.GetWorkBook(OfficeFileFormat.Excel2007, @"TestData\xls1.xlsx"); Assert.That(dsMethod.Tables.Count, Is.EqualTo(1), "Incorrect count"); Assert.That(dsMethod.Tables[0].TableName, Is.EqualTo("Sheet1"), "Incorrect TableName"); DataTable check = ExcelHelper.LoadXLSSheetToDataTable(@"TestData\xls1.xls", "Sheet1", true); Assert.That(SqlHelper.CompareDataTables(check, dsMethod.Tables[0]), Is.True, "Data does not match"); } /// <summary> /// Scenario: Workbook containing more than one sheet opened /// Expected: DataSet contains one DataTable for each sheet in the workbook, each with the appropriate data /// </summary> [Test] public void _018_GetWorkBook_XLSX_ManySheets() { DataSet dsMethod = ExcelOleDb.GetWorkBook(OfficeFileFormat.Excel2007, @"TestData\xls2.xlsx"); Assert.That(dsMethod.Tables.Count, Is.EqualTo(3), "Incorrect count"); Assert.That(dsMethod.Tables[0].TableName, Is.EqualTo("first"), "Incorrect TableName"); Assert.That(dsMethod.Tables[1].TableName, Is.EqualTo("second"), "Incorrect TableName"); Assert.That(dsMethod.Tables[2].TableName, Is.EqualTo("third"), "Incorrect TableName"); DataTable check1 = ExcelHelper.LoadXLSSheetToDataTable(@"TestData\xls2.xls", "first", true); DataTable check2 = ExcelHelper.LoadXLSSheetToDataTable(@"TestData\xls2.xls", "second", true); DataTable check3 = ExcelHelper.LoadXLSSheetToDataTable(@"TestData\xls2.xls", "third", true); Assert.That(SqlHelper.CompareDataTables(check1, dsMethod.Tables[0]), Is.True, "Data does not match"); Assert.That(SqlHelper.CompareDataTables(check2, dsMethod.Tables[1]), Is.True, "Data does not match"); Assert.That(SqlHelper.CompareDataTables(check3, dsMethod.Tables[2]), Is.True, "Data does not match"); } } }
using UnityEngine; using System.Collections; using System; namespace RootMotion.FinalIK { /// <summary> /// Forward and Backward Reaching Inverse Kinematics solver. /// /// This class is based on the "FABRIK: A fast, iterative solver for the inverse kinematics problem." paper by Aristidou, A., Lasenby, J. /// </summary> [System.Serializable] public class IKSolverFABRIK : IKSolverHeuristic { #region Main Interface /// <summary> /// Solving stage 1 of the %FABRIK algorithm. /// </summary> public void SolveForward(Vector3 position) { if (!initiated) { if (!Warning.logged) LogWarning("Trying to solve uninitiated FABRIK chain."); return; } OnPreSolve(); ForwardReach(position); } /// <summary> /// Solving stage 2 of the %FABRIK algorithm. /// </summary> public void SolveBackward(Vector3 position) { if (!initiated) { if (!Warning.logged) LogWarning("Trying to solve uninitiated FABRIK chain."); return; } BackwardReach(position); OnPostSolve(); } /// <summary> /// Called before each iteration of the solver. /// </summary> public IterationDelegate OnPreIteration; #endregion Main Interface private bool[] limitedBones = new bool[0]; private Vector3[] solverLocalPositions = new Vector3[0]; protected override void OnInitiate() { if (firstInitiation || !Application.isPlaying) IKPosition = bones[bones.Length - 1].transform.position; for (int i = 0; i < bones.Length; i++) { bones[i].solverPosition = bones[i].transform.position; bones[i].solverRotation = bones[i].transform.rotation; } limitedBones = new bool[bones.Length]; solverLocalPositions = new Vector3[bones.Length]; InitiateBones(); for (int i = 0; i < bones.Length; i++) { solverLocalPositions[i] = Quaternion.Inverse(GetParentSolverRotation(i)) * (bones[i].transform.position - GetParentSolverPosition(i)); } } protected override void OnUpdate() { if (IKPositionWeight <= 0) return; IKPositionWeight = Mathf.Clamp(IKPositionWeight, 0f, 1f); OnPreSolve(); if (target != null) IKPosition = target.position; if (XY) IKPosition.z = bones[0].transform.position.z; Vector3 singularityOffset = maxIterations > 1? GetSingularityOffset(): Vector3.zero; // Iterating the solver for (int i = 0; i < maxIterations; i++) { // Optimizations if (singularityOffset == Vector3.zero && i >= 1 && tolerance > 0 && positionOffset < tolerance * tolerance) break; lastLocalDirection = localDirection; if (OnPreIteration != null) OnPreIteration(i); Solve(IKPosition + (i == 0? singularityOffset: Vector3.zero)); } OnPostSolve(); } /* * If true, the solver will work with 0 length bones * */ protected override bool boneLengthCanBeZero { get { return false; }} // Returning false here also ensures that the bone lengths will be calculated /* * Interpolates the joint position to match the bone's length */ private Vector3 SolveJoint(Vector3 pos1, Vector3 pos2, float length) { if (XY) pos1.z = pos2.z; return pos2 + (pos1 - pos2).normalized * length; } /* * Check if bones have moved from last solved positions * */ private void OnPreSolve() { for (int i = 0; i < bones.Length; i++) { bones[i].solverPosition = bones[i].transform.position; bones[i].solverRotation = bones[i].transform.rotation; chainLength = 0; if (i < bones.Length - 1) { bones[i].length = (bones[i].transform.position - bones[i + 1].transform.position).magnitude; bones[i].axis = Quaternion.Inverse(bones[i].transform.rotation) * (bones[i + 1].transform.position - bones[i].transform.position); chainLength += bones[i].length; } if (useRotationLimits) solverLocalPositions[i] = Quaternion.Inverse(GetParentSolverRotation(i)) * (bones[i].transform.position - GetParentSolverPosition(i)); } } /* * After solving the chain * */ private void OnPostSolve() { // Rotating bones to match the solver positions if (!useRotationLimits) MapToSolverPositions(); else MapToSolverPositionsLimited(); lastLocalDirection = localDirection; } private void Solve(Vector3 targetPosition) { // Forward reaching ForwardReach(targetPosition); // Backward reaching BackwardReach(bones[0].transform.position); } /* * Stage 1 of FABRIK algorithm * */ private void ForwardReach(Vector3 position) { // Lerp last bone's solverPosition to position bones[bones.Length - 1].solverPosition = Vector3.Lerp(bones[bones.Length - 1].solverPosition, position, IKPositionWeight); for (int i = 0; i < limitedBones.Length; i++) limitedBones[i] = false; for (int i = bones.Length - 2; i > -1; i--) { // Finding joint positions bones[i].solverPosition = SolveJoint(bones[i].solverPosition, bones[i + 1].solverPosition, bones[i].length); // Limiting bone rotation forward LimitForward(i, i + 1); } // Limiting the first bone's rotation LimitForward(0, 0); } private void SolverMove(int index, Vector3 offset) { for (int i = index; i < bones.Length; i++) { bones[i].solverPosition += offset; } } private void SolverRotate(int index, Quaternion rotation, bool recursive) { for (int i = index; i < bones.Length; i++) { bones[i].solverRotation = rotation * bones[i].solverRotation; if (!recursive) return; } } private void SolverRotateChildren(int index, Quaternion rotation) { for (int i = index + 1; i < bones.Length; i++) { bones[i].solverRotation = rotation * bones[i].solverRotation; } } private void SolverMoveChildrenAroundPoint(int index, Quaternion rotation) { for (int i = index + 1; i < bones.Length; i++) { Vector3 dir = bones[i].solverPosition - bones[index].solverPosition; bones[i].solverPosition = bones[index].solverPosition + rotation * dir; } } private Quaternion GetParentSolverRotation(int index) { if (index > 0) return bones[index - 1].solverRotation; if (bones[0].transform.parent == null) return Quaternion.identity; return bones[0].transform.parent.rotation; } private Vector3 GetParentSolverPosition(int index) { if (index > 0) return bones[index - 1].solverPosition; if (bones[0].transform.parent == null) return Vector3.zero; return bones[0].transform.parent.position; } private Quaternion GetLimitedRotation(int index, Quaternion q, out bool changed) { changed = false; Quaternion parentRotation = GetParentSolverRotation(index); Quaternion localRotation = Quaternion.Inverse(parentRotation) * q; Quaternion limitedLocalRotation = bones[index].rotationLimit.GetLimitedLocalRotation(localRotation, out changed); if (!changed) return q; return parentRotation * limitedLocalRotation; } /* * Applying rotation limit to a bone in stage 1 in a more stable way * */ private void LimitForward(int rotateBone, int limitBone) { if (!useRotationLimits) return; if (bones[limitBone].rotationLimit == null) return; // Storing last bone's position before applying the limit Vector3 lastBoneBeforeLimit = bones[bones.Length - 1].solverPosition; // Moving and rotating this bone and all its children to their solver positions for (int i = rotateBone; i < bones.Length - 1; i++) { if (limitedBones[i]) break; Quaternion fromTo = Quaternion.FromToRotation(bones[i].solverRotation * bones[i].axis, bones[i + 1].solverPosition - bones[i].solverPosition); SolverRotate(i, fromTo, false); } // Limit the bone's rotation bool changed = false; Quaternion afterLimit = GetLimitedRotation(limitBone, bones[limitBone].solverRotation, out changed); if (changed) { // Rotating and positioning the hierarchy so that the last bone's position is maintained if (limitBone < bones.Length - 1) { Quaternion change = QuaTools.FromToRotation(bones[limitBone].solverRotation, afterLimit); bones[limitBone].solverRotation = afterLimit; SolverRotateChildren(limitBone, change); SolverMoveChildrenAroundPoint(limitBone, change); // Rotating to compensate for the limit Quaternion fromTo = Quaternion.FromToRotation(bones[bones.Length - 1].solverPosition - bones[rotateBone].solverPosition, lastBoneBeforeLimit - bones[rotateBone].solverPosition); SolverRotate(rotateBone, fromTo, true); SolverMoveChildrenAroundPoint(rotateBone, fromTo); // Moving the bone so that last bone maintains it's initial position SolverMove(rotateBone, lastBoneBeforeLimit - bones[bones.Length - 1].solverPosition); } else { // last bone bones[limitBone].solverRotation = afterLimit; } } limitedBones[limitBone] = true; } /* * Stage 2 of FABRIK algorithm * */ private void BackwardReach(Vector3 position) { if (useRotationLimits) BackwardReachLimited(position); else BackwardReachUnlimited(position); } /* * Stage 2 of FABRIK algorithm without rotation limits * */ private void BackwardReachUnlimited(Vector3 position) { // Move first bone to position bones[0].solverPosition = position; // Finding joint positions for (int i = 1; i < bones.Length; i++) { bones[i].solverPosition = SolveJoint(bones[i].solverPosition, bones[i - 1].solverPosition, bones[i - 1].length); } } /* * Stage 2 of FABRIK algorithm with limited rotations * */ private void BackwardReachLimited(Vector3 position) { // Move first bone to position bones[0].solverPosition = position; // Applying rotation limits bone by bone for (int i = 0; i < bones.Length - 1; i++) { // Rotating bone to look at the solved joint position Vector3 nextPosition = SolveJoint(bones[i + 1].solverPosition, bones[i].solverPosition, bones[i].length); Quaternion swing = Quaternion.FromToRotation(bones[i].solverRotation * bones[i].axis, nextPosition - bones[i].solverPosition); Quaternion targetRotation = swing * bones[i].solverRotation; // Rotation Constraints if (bones[i].rotationLimit != null) { bool changed = false; targetRotation = GetLimitedRotation(i, targetRotation, out changed); } Quaternion fromTo = QuaTools.FromToRotation(bones[i].solverRotation, targetRotation); bones[i].solverRotation = targetRotation; SolverRotateChildren(i, fromTo); // Positioning the next bone to its default local position bones[i + 1].solverPosition = bones[i].solverPosition + bones[i].solverRotation * solverLocalPositions[i + 1]; } // Reconstruct solver rotations to protect from invalid Quaternions for (int i = 0; i < bones.Length; i++) { bones[i].solverRotation = Quaternion.LookRotation(bones[i].solverRotation * Vector3.forward, bones[i].solverRotation * Vector3.up); } } /* * Rotate bones to match the solver positions when not using Rotation Limits * */ private void MapToSolverPositions() { bones[0].transform.position = bones[0].solverPosition; for (int i = 0; i < bones.Length - 1; i++) { if (XY) { bones[i].Swing2D(bones[i + 1].solverPosition); } else { bones[i].Swing(bones[i + 1].solverPosition); } } } /* * Rotate bones to match the solver positions when using Rotation Limits * */ private void MapToSolverPositionsLimited() { for (int i = 0; i < bones.Length; i++) { bones[i].transform.position = bones[i].solverPosition; if (i < bones.Length - 1) bones[i].transform.rotation = bones[i].solverRotation; } } } }
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using ZXing.Common; namespace ZXing.Datamatrix.Internal { /// <summary> /// <p>Data Matrix Codes can encode text as bits in one of several modes, and can use multiple modes /// in one Data Matrix Code. This class decodes the bits back into text.</p> /// /// <p>See ISO 16022:2006, 5.2.1 - 5.2.9.2</p> /// /// <author>bbrown@google.com (Brian Brown)</author> /// <author>Sean Owen</author> /// </summary> internal static class DecodedBitStreamParser { private enum Mode { PAD_ENCODE, // Not really a mode ASCII_ENCODE, C40_ENCODE, TEXT_ENCODE, ANSIX12_ENCODE, EDIFACT_ENCODE, BASE256_ENCODE } /// <summary> /// See ISO 16022:2006, Annex C Table C.1 /// The C40 Basic Character Set (*'s used for placeholders for the shift values) /// </summary> private static readonly char[] C40_BASIC_SET_CHARS = { '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; private static readonly char[] C40_SHIFT2_SET_CHARS = { '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_' }; /// <summary> /// See ISO 16022:2006, Annex C Table C.2 /// The Text Basic Character Set (*'s used for placeholders for the shift values) /// </summary> private static readonly char[] TEXT_BASIC_SET_CHARS = { '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; private static readonly char[] TEXT_SHIFT3_SET_CHARS = { '`', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '~', (char) 127 }; internal static DecoderResult decode(byte[] bytes) { BitSource bits = new BitSource(bytes); StringBuilder result = new StringBuilder(100); StringBuilder resultTrailer = new StringBuilder(0); List<byte[]> byteSegments = new List<byte[]>(1); Mode mode = Mode.ASCII_ENCODE; do { if (mode == Mode.ASCII_ENCODE) { if (!decodeAsciiSegment(bits, result, resultTrailer, out mode)) return null; } else { switch (mode) { case Mode.C40_ENCODE: if (!decodeC40Segment(bits, result)) return null; break; case Mode.TEXT_ENCODE: if (!decodeTextSegment(bits, result)) return null; break; case Mode.ANSIX12_ENCODE: if (!decodeAnsiX12Segment(bits, result)) return null; break; case Mode.EDIFACT_ENCODE: if (!decodeEdifactSegment(bits, result)) return null; break; case Mode.BASE256_ENCODE: if (!decodeBase256Segment(bits, result, byteSegments)) return null; break; default: return null; } mode = Mode.ASCII_ENCODE; } } while (mode != Mode.PAD_ENCODE && bits.available() > 0); if (resultTrailer.Length > 0) { result.Append(resultTrailer.ToString()); } return new DecoderResult(bytes, result.ToString(), byteSegments.Count == 0 ? null : byteSegments, null); } /// <summary> /// See ISO 16022:2006, 5.2.3 and Annex C, Table C.2 /// </summary> private static bool decodeAsciiSegment(BitSource bits, StringBuilder result, StringBuilder resultTrailer, out Mode mode) { bool upperShift = false; mode = Mode.ASCII_ENCODE; do { int oneByte = bits.readBits(8); if (oneByte == 0) { return false; } else if (oneByte <= 128) { // ASCII data (ASCII value + 1) if (upperShift) { oneByte += 128; //upperShift = false; } result.Append((char)(oneByte - 1)); mode = Mode.ASCII_ENCODE; return true; } else if (oneByte == 129) { // Pad mode = Mode.PAD_ENCODE; return true; } else if (oneByte <= 229) { // 2-digit data 00-99 (Numeric Value + 130) int value = oneByte - 130; if (value < 10) { // padd with '0' for single digit values result.Append('0'); } result.Append(value); } else if (oneByte == 230) { // Latch to C40 encodation mode = Mode.C40_ENCODE; return true; } else if (oneByte == 231) { // Latch to Base 256 encodation mode = Mode.BASE256_ENCODE; return true; } else if (oneByte == 232) { // FNC1 result.Append((char)29); // translate as ASCII 29 } else if (oneByte == 233 || oneByte == 234) { // Structured Append, Reader Programming // Ignore these symbols for now //throw ReaderException.Instance; } else if (oneByte == 235) { // Upper Shift (shift to Extended ASCII) upperShift = true; } else if (oneByte == 236) { // 05 Macro result.Append("[)>\u001E05\u001D"); resultTrailer.Insert(0, "\u001E\u0004"); } else if (oneByte == 237) { // 06 Macro result.Append("[)>\u001E06\u001D"); resultTrailer.Insert(0, "\u001E\u0004"); } else if (oneByte == 238) { // Latch to ANSI X12 encodation mode = Mode.ANSIX12_ENCODE; return true; } else if (oneByte == 239) { // Latch to Text encodation mode = Mode.TEXT_ENCODE; return true; } else if (oneByte == 240) { // Latch to EDIFACT encodation mode = Mode.EDIFACT_ENCODE; return true; } else if (oneByte == 241) { // ECI Character // TODO(bbrown): I think we need to support ECI //throw ReaderException.Instance; // Ignore this symbol for now } else if (oneByte >= 242) { // Not to be used in ASCII encodation // ... but work around encoders that end with 254, latch back to ASCII if (oneByte != 254 || bits.available() != 0) { return false; } } } while (bits.available() > 0); mode = Mode.ASCII_ENCODE; return true; } /// <summary> /// See ISO 16022:2006, 5.2.5 and Annex C, Table C.1 /// </summary> private static bool decodeC40Segment(BitSource bits, StringBuilder result) { // Three C40 values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 // TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time bool upperShift = false; int[] cValues = new int[3]; int shift = 0; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return true; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return true; } parseTwoBytes(firstByte, bits.readBits(8), cValues); for (int i = 0; i < 3; i++) { int cValue = cValues[i]; switch (shift) { case 0: if (cValue < 3) { shift = cValue + 1; } else if (cValue < C40_BASIC_SET_CHARS.Length) { char c40char = C40_BASIC_SET_CHARS[cValue]; if (upperShift) { result.Append((char)(c40char + 128)); upperShift = false; } else { result.Append(c40char); } } else { return false; } break; case 1: if (upperShift) { result.Append((char)(cValue + 128)); upperShift = false; } else { result.Append((char)cValue); } shift = 0; break; case 2: if (cValue < C40_SHIFT2_SET_CHARS.Length) { char c40char = C40_SHIFT2_SET_CHARS[cValue]; if (upperShift) { result.Append((char)(c40char + 128)); upperShift = false; } else { result.Append(c40char); } } else if (cValue == 27) { // FNC1 result.Append((char)29); // translate as ASCII 29 } else if (cValue == 30) { // Upper Shift upperShift = true; } else { return false; } shift = 0; break; case 3: if (upperShift) { result.Append((char)(cValue + 224)); upperShift = false; } else { result.Append((char)(cValue + 96)); } shift = 0; break; default: return false; } } } while (bits.available() > 0); return true; } /// <summary> /// See ISO 16022:2006, 5.2.6 and Annex C, Table C.2 /// </summary> private static bool decodeTextSegment(BitSource bits, StringBuilder result) { // Three Text values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 // TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time bool upperShift = false; int[] cValues = new int[3]; int shift = 0; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return true; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return true; } parseTwoBytes(firstByte, bits.readBits(8), cValues); for (int i = 0; i < 3; i++) { int cValue = cValues[i]; switch (shift) { case 0: if (cValue < 3) { shift = cValue + 1; } else if (cValue < TEXT_BASIC_SET_CHARS.Length) { char textChar = TEXT_BASIC_SET_CHARS[cValue]; if (upperShift) { result.Append((char)(textChar + 128)); upperShift = false; } else { result.Append(textChar); } } else { return false; } break; case 1: if (upperShift) { result.Append((char)(cValue + 128)); upperShift = false; } else { result.Append((char)cValue); } shift = 0; break; case 2: // Shift 2 for Text is the same encoding as C40 if (cValue < C40_SHIFT2_SET_CHARS.Length) { char c40char = C40_SHIFT2_SET_CHARS[cValue]; if (upperShift) { result.Append((char)(c40char + 128)); upperShift = false; } else { result.Append(c40char); } } else if (cValue == 27) { // FNC1 result.Append((char)29); // translate as ASCII 29 } else if (cValue == 30) { // Upper Shift upperShift = true; } else { return false; } shift = 0; break; case 3: if (cValue < TEXT_SHIFT3_SET_CHARS.Length) { char textChar = TEXT_SHIFT3_SET_CHARS[cValue]; if (upperShift) { result.Append((char)(textChar + 128)); upperShift = false; } else { result.Append(textChar); } shift = 0; } else { return false; } break; default: return false; } } } while (bits.available() > 0); return true; } /// <summary> /// See ISO 16022:2006, 5.2.7 /// </summary> private static bool decodeAnsiX12Segment(BitSource bits, StringBuilder result) { // Three ANSI X12 values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 int[] cValues = new int[3]; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return true; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return true; } parseTwoBytes(firstByte, bits.readBits(8), cValues); for (int i = 0; i < 3; i++) { int cValue = cValues[i]; if (cValue == 0) { // X12 segment terminator <CR> result.Append('\r'); } else if (cValue == 1) { // X12 segment separator * result.Append('*'); } else if (cValue == 2) { // X12 sub-element separator > result.Append('>'); } else if (cValue == 3) { // space result.Append(' '); } else if (cValue < 14) { // 0 - 9 result.Append((char)(cValue + 44)); } else if (cValue < 40) { // A - Z result.Append((char)(cValue + 51)); } else { return false; } } } while (bits.available() > 0); return true; } private static void parseTwoBytes(int firstByte, int secondByte, int[] result) { int fullBitValue = (firstByte << 8) + secondByte - 1; int temp = fullBitValue / 1600; result[0] = temp; fullBitValue -= temp * 1600; temp = fullBitValue / 40; result[1] = temp; result[2] = fullBitValue - temp * 40; } /// <summary> /// See ISO 16022:2006, 5.2.8 and Annex C Table C.3 /// </summary> private static bool decodeEdifactSegment(BitSource bits, StringBuilder result) { do { // If there is only two or less bytes left then it will be encoded as ASCII if (bits.available() <= 16) { return true; } for (int i = 0; i < 4; i++) { int edifactValue = bits.readBits(6); // Check for the unlatch character if (edifactValue == 0x1F) { // 011111 // Read rest of byte, which should be 0, and stop int bitsLeft = 8 - bits.BitOffset; if (bitsLeft != 8) { bits.readBits(bitsLeft); } return true; } if ((edifactValue & 0x20) == 0) { // no 1 in the leading (6th) bit edifactValue |= 0x40; // Add a leading 01 to the 6 bit binary value } result.Append((char)edifactValue); } } while (bits.available() > 0); return true; } /// <summary> /// See ISO 16022:2006, 5.2.9 and Annex B, B.2 /// </summary> private static bool decodeBase256Segment(BitSource bits, StringBuilder result, IList<byte[]> byteSegments) { // Figure out how long the Base 256 Segment is. int codewordPosition = 1 + bits.ByteOffset; // position is 1-indexed int d1 = unrandomize255State(bits.readBits(8), codewordPosition++); int count; if (d1 == 0) { // Read the remainder of the symbol count = bits.available() / 8; } else if (d1 < 250) { count = d1; } else { count = 250 * (d1 - 249) + unrandomize255State(bits.readBits(8), codewordPosition++); } // We're seeing NegativeArraySizeException errors from users. if (count < 0) { return false; } byte[] bytes = new byte[count]; for (int i = 0; i < count; i++) { // Have seen this particular error in the wild, such as at // http://www.bcgen.com/demo/IDAutomationStreamingDataMatrix.aspx?MODE=3&D=Fred&PFMT=3&PT=F&X=0.3&O=0&LM=0.2 if (bits.available() < 8) { return false; } bytes[i] = (byte)unrandomize255State(bits.readBits(8), codewordPosition++); } byteSegments.Add(bytes); try { #if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || WINDOWS_PHONE80 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || WindowsCE || PORTABLE) #if WindowsCE result.Append(Encoding.GetEncoding(1252).GetString(bytes, 0, bytes.Length)); #else result.Append(Encoding.GetEncoding("ISO-8859-1").GetString(bytes, 0, bytes.Length)); #endif #else result.Append(Encoding.GetEncoding("ISO-8859-1").GetString(bytes)); #endif } catch (Exception uee) { throw new InvalidOperationException("Platform does not support required encoding: " + uee); } return true; } /// <summary> /// See ISO 16022:2006, Annex B, B.2 /// </summary> private static int unrandomize255State(int randomizedBase256Codeword, int base256CodewordPosition) { int pseudoRandomNumber = ((149 * base256CodewordPosition) % 255) + 1; int tempVariable = randomizedBase256Codeword - pseudoRandomNumber; return tempVariable >= 0 ? tempVariable : tempVariable + 256; } } }
using J2N.Threading; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using Lucene.Net.Store; using Lucene.Net.Util; using NUnit.Framework; using System; using System.Threading; using Assert = Lucene.Net.TestFramework.Assert; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; [TestFixture] public class TestAtomicUpdate : LuceneTestCase { private abstract class TimedThread : ThreadJob { internal volatile bool failed; internal int count; internal static float RUN_TIME_MSEC = AtLeast(500); internal TimedThread[] allThreads; public abstract void DoWork(); internal TimedThread(TimedThread[] threads) { this.allThreads = threads; } public override void Run() { long stopTime = Environment.TickCount + (long)RUN_TIME_MSEC; count = 0; try { do { if (AnyErrors()) { break; } DoWork(); count++; } while (Environment.TickCount < stopTime); } catch (Exception e) { Console.WriteLine(Thread.CurrentThread.Name + ": exc"); Console.WriteLine(e.StackTrace); failed = true; } } internal virtual bool AnyErrors() { for (int i = 0; i < allThreads.Length; i++) { if (allThreads[i] != null && allThreads[i].failed) { return true; } } return false; } } private class IndexerThread : TimedThread { internal IndexWriter writer; public IndexerThread(IndexWriter writer, TimedThread[] threads) : base(threads) { this.writer = writer; } public override void DoWork() { // Update all 100 docs... for (int i = 0; i < 100; i++) { Documents.Document d = new Documents.Document(); d.Add(new StringField("id", Convert.ToString(i), Field.Store.YES)); d.Add(new TextField("contents", English.Int32ToEnglish(i + 10 * count), Field.Store.NO)); writer.UpdateDocument(new Term("id", Convert.ToString(i)), d); } } } private class SearcherThread : TimedThread { internal Directory directory; public SearcherThread(Directory directory, TimedThread[] threads) : base(threads) { this.directory = directory; } public override void DoWork() { IndexReader r = DirectoryReader.Open(directory); Assert.AreEqual(100, r.NumDocs); r.Dispose(); } } /* Run one indexer and 2 searchers against single index as stress test. */ public virtual void RunTest(Directory directory) { TimedThread[] threads = new TimedThread[4]; IndexWriterConfig conf = (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))).SetMaxBufferedDocs(7); ((TieredMergePolicy)conf.MergePolicy).MaxMergeAtOnce = 3; IndexWriter writer = RandomIndexWriter.MockIndexWriter(directory, conf, Random); // Establish a base index of 100 docs: for (int i = 0; i < 100; i++) { Documents.Document d = new Documents.Document(); d.Add(NewStringField("id", Convert.ToString(i), Field.Store.YES)); d.Add(NewTextField("contents", English.Int32ToEnglish(i), Field.Store.NO)); if ((i - 1) % 7 == 0) { writer.Commit(); } writer.AddDocument(d); } writer.Commit(); IndexReader r = DirectoryReader.Open(directory); Assert.AreEqual(100, r.NumDocs); r.Dispose(); IndexerThread indexerThread = new IndexerThread(writer, threads); threads[0] = indexerThread; indexerThread.Start(); IndexerThread indexerThread2 = new IndexerThread(writer, threads); threads[1] = indexerThread2; indexerThread2.Start(); SearcherThread searcherThread1 = new SearcherThread(directory, threads); threads[2] = searcherThread1; searcherThread1.Start(); SearcherThread searcherThread2 = new SearcherThread(directory, threads); threads[3] = searcherThread2; searcherThread2.Start(); indexerThread.Join(); indexerThread2.Join(); searcherThread1.Join(); searcherThread2.Join(); writer.Dispose(); Assert.IsTrue(!indexerThread.failed, "hit unexpected exception in indexer"); Assert.IsTrue(!indexerThread2.failed, "hit unexpected exception in indexer2"); Assert.IsTrue(!searcherThread1.failed, "hit unexpected exception in search1"); Assert.IsTrue(!searcherThread2.failed, "hit unexpected exception in search2"); //System.out.println(" Writer: " + indexerThread.count + " iterations"); //System.out.println("Searcher 1: " + searcherThread1.count + " searchers created"); //System.out.println("Searcher 2: " + searcherThread2.count + " searchers created"); } /* Run above stress test against RAMDirectory and then FSDirectory. */ [Test] [Slow] public virtual void TestAtomicUpdates() { Directory directory; // First in a RAM directory: using (directory = new MockDirectoryWrapper(Random, new RAMDirectory())) { RunTest(directory); } // Second in an FSDirectory: System.IO.DirectoryInfo dirPath = CreateTempDir("lucene.test.atomic"); using (directory = NewFSDirectory(dirPath)) { RunTest(directory); } System.IO.Directory.Delete(dirPath.FullName, true); } } }
using System.Net; using System.Text.Json; using FluentAssertions; using JsonApiDotNetCore.Serialization.Objects; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.NamingConventions; public sealed class PascalCasingTests : IClassFixture<IntegrationTestContext<PascalCasingConventionStartup<NamingDbContext>, NamingDbContext>> { private readonly IntegrationTestContext<PascalCasingConventionStartup<NamingDbContext>, NamingDbContext> _testContext; private readonly NamingFakers _fakers = new(); public PascalCasingTests(IntegrationTestContext<PascalCasingConventionStartup<NamingDbContext>, NamingDbContext> testContext) { _testContext = testContext; testContext.UseController<DivingBoardsController>(); testContext.UseController<SwimmingPoolsController>(); } [Fact] public async Task Can_get_resources_with_include() { // Arrange List<SwimmingPool> pools = _fakers.SwimmingPool.Generate(2); pools[1].DivingBoards = _fakers.DivingBoard.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<SwimmingPool>(); dbContext.SwimmingPools.AddRange(pools); await dbContext.SaveChangesAsync(); }); const string route = "/PublicApi/SwimmingPools?include=DivingBoards"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.ShouldHaveCount(2); responseDocument.Data.ManyValue.Should().OnlyContain(resourceObject => resourceObject.Type == "SwimmingPools"); responseDocument.Data.ManyValue.Should().OnlyContain(resourceObject => resourceObject.Attributes.ShouldContainKey("IsIndoor") != null); responseDocument.Data.ManyValue.Should().OnlyContain(resourceObject => resourceObject.Relationships.ShouldContainKey("WaterSlides") != null); responseDocument.Data.ManyValue.Should().OnlyContain(resourceObject => resourceObject.Relationships.ShouldContainKey("DivingBoards") != null); decimal height = pools[1].DivingBoards[0].HeightInMeters; responseDocument.Included.ShouldHaveCount(1); responseDocument.Included[0].Type.Should().Be("DivingBoards"); responseDocument.Included[0].Id.Should().Be(pools[1].DivingBoards[0].StringId); responseDocument.Included[0].Attributes.ShouldContainKey("HeightInMeters").With(value => value.As<decimal>().Should().BeApproximately(height)); responseDocument.Included[0].Relationships.Should().BeNull(); responseDocument.Included[0].Links.ShouldNotBeNull().Self.Should().Be($"/PublicApi/DivingBoards/{pools[1].DivingBoards[0].StringId}"); responseDocument.Meta.ShouldContainKey("Total").With(value => { JsonElement element = value.Should().BeOfType<JsonElement>().Subject; element.GetInt32().Should().Be(2); }); } [Fact] public async Task Can_filter_secondary_resources_with_sparse_fieldset() { // Arrange SwimmingPool pool = _fakers.SwimmingPool.Generate(); pool.WaterSlides = _fakers.WaterSlide.Generate(2); pool.WaterSlides[0].LengthInMeters = 1; pool.WaterSlides[1].LengthInMeters = 5; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.SwimmingPools.Add(pool); await dbContext.SaveChangesAsync(); }); string route = $"/PublicApi/SwimmingPools/{pool.StringId}/WaterSlides" + "?filter=greaterThan(LengthInMeters,'1')&fields[WaterSlides]=LengthInMeters"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.ShouldHaveCount(1); responseDocument.Data.ManyValue[0].Type.Should().Be("WaterSlides"); responseDocument.Data.ManyValue[0].Id.Should().Be(pool.WaterSlides[1].StringId); responseDocument.Data.ManyValue[0].Attributes.ShouldHaveCount(1); } [Fact] public async Task Can_create_resource() { // Arrange SwimmingPool newPool = _fakers.SwimmingPool.Generate(); var requestBody = new { data = new { type = "SwimmingPools", attributes = new Dictionary<string, object> { ["IsIndoor"] = newPool.IsIndoor } } }; const string route = "/PublicApi/SwimmingPools"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.ShouldNotBeNull(); responseDocument.Data.SingleValue.Type.Should().Be("SwimmingPools"); responseDocument.Data.SingleValue.Attributes.ShouldContainKey("IsIndoor").With(value => value.Should().Be(newPool.IsIndoor)); int newPoolId = int.Parse(responseDocument.Data.SingleValue.Id.ShouldNotBeNull()); string poolLink = $"{route}/{newPoolId}"; responseDocument.Data.SingleValue.Relationships.ShouldContainKey("WaterSlides").With(value => { value.ShouldNotBeNull(); value.Links.ShouldNotBeNull(); value.Links.Self.Should().Be($"{poolLink}/relationships/WaterSlides"); value.Links.Related.Should().Be($"{poolLink}/WaterSlides"); }); responseDocument.Data.SingleValue.Relationships.ShouldContainKey("DivingBoards").With(value => { value.ShouldNotBeNull(); value.Links.ShouldNotBeNull(); value.Links.Self.Should().Be($"{poolLink}/relationships/DivingBoards"); value.Links.Related.Should().Be($"{poolLink}/DivingBoards"); }); await _testContext.RunOnDatabaseAsync(async dbContext => { SwimmingPool poolInDatabase = await dbContext.SwimmingPools.FirstWithIdAsync(newPoolId); poolInDatabase.IsIndoor.Should().Be(newPool.IsIndoor); }); } [Fact] public async Task Applies_casing_convention_on_error_stack_trace() { // Arrange const string requestBody = "{ \"data\": {"; const string route = "/PublicApi/SwimmingPools"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body."); error.Meta.ShouldContainKey("StackTrace"); } [Fact] public async Task Applies_casing_convention_on_source_pointer_from_ModelState() { // Arrange DivingBoard existingBoard = _fakers.DivingBoard.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.DivingBoards.Add(existingBoard); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "DivingBoards", id = existingBoard.StringId, attributes = new Dictionary<string, object> { ["HeightInMeters"] = -1 } } }; string route = $"/PublicApi/DivingBoards/{existingBoard.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Input validation failed."); error.Detail.Should().Be("The field HeightInMeters must be between 1 and 20."); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/data/attributes/HeightInMeters"); } }
/* Copyright 2010 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 System.Collections.Generic; using Google.Apis.Json; using Google.Apis.Logging; using Google.Apis.Testing; using Google.Apis.Util; namespace Google.Apis.Discovery { /// <summary> /// IResource represents one resource as difined in a Google Api Discovery Document. /// It can contain more resources and/or methods. /// </summary> /// <seealso cref="IResourceContainer"/> /// <seealso cref="IMethod"/> public interface IResource : IResourceContainer { /// <summary> /// All the methods which belong to this resource. /// </summary> Dictionary<string, IMethod> Methods { get; } /// <summary> /// Will return the parent of this resource, or null if there is none. /// </summary> /// <remarks>Will be null if this is the service resource.</remarks> IResource Parent { get; } /// <summary> /// Retrievs the full name of a resource, /// e.g. TopResource.SubResource /// </summary> /// <remarks>Will return an empty string for the root resource or service.</remarks> string Path { get; } /// <summary> /// True only if this resource is the root resource node defined by the service. /// </summary> bool IsServiceResource { get; } } #region Base Resource /// <summary> /// Abstract implementation of a resource. /// </summary> internal class Resource : ServiceObject, IResource { private static readonly ILogger logger = ApplicationContext.Logger.ForType<IResource>(); private readonly JsonDictionary information; protected Dictionary<string, IMethod> methods; protected Dictionary<string, IResource> resources; /// <summary> /// Creates a new resource for the specified discovery version with the specified name and json dictionary. /// </summary> internal Resource(IServiceFactory factory, string name, JsonDictionary dictionary) : base(factory) { name.ThrowIfNull("name"); dictionary.ThrowIfNull("dictionary"); logger.Debug("Constructing Resource [{0}]", name); Name = name; information = dictionary; if (information == null) { throw new ArgumentException("got no valid dictionary"); } // Initialize subresources. if (information.ContainsKey("resources")) { var resourceJson = (JsonDictionary)information["resources"]; resources = new Dictionary<string, IResource>(); foreach (KeyValuePair<string, object> pair in resourceJson) { // Create the subresource. var subResource = (Resource)Factory.CreateResource(pair.Key, pair.Value as JsonDictionary); subResource.Parent = this; resources.Add(pair.Key, subResource); } } } #region IResource Members public string Name { get; set; } public Dictionary<string, IMethod> Methods { get { if (methods == null) { methods = FetchMethods(); } return methods; } } public IResource Parent { get; internal set; } public IDictionary<string, IResource> Resources { get { if (resources == null) { resources = FetchResources(); } return resources; } } #endregion private Dictionary<string, IMethod> FetchMethods() { if (information.ContainsKey(ServiceFactory.Methods) == false) { return new Dictionary<string, IMethod>(0); // return empty, not null. } JsonDictionary js = information[ServiceFactory.Methods] as JsonDictionary; if (js == null) { return new Dictionary<string, IMethod>(0); // return empty, not null. } var methods = new Dictionary<string, IMethod>(); foreach (KeyValuePair<string, object> kvp in js) { IMethod m = CreateMethod(kvp); methods.Add(kvp.Key, m); } return methods; } private Dictionary<string, IResource> FetchResources() { if (information.ContainsKey(ServiceFactory.Resources) == false) { return new Dictionary<string, IResource>(0); // return empty, not null. } JsonDictionary js = information[ServiceFactory.Resources] as JsonDictionary; if (js == null) { return new Dictionary<string, IResource>(0); // return empty, not null. } var resources = new Dictionary<string, IResource>(); foreach (KeyValuePair<string, object> kvp in js) { IResource r = CreateResource(kvp); resources.Add(kvp.Key, r); } return resources; } public string Path { get { return GetFullName(this); } } public bool IsServiceResource { get { return Parent == null && Path == String.Empty; } } /// <summary> /// Retrieves the full name of a resource, /// e.g. TopResource.SubResource /// </summary> private string GetFullName(IResource resource) { var parentResource = resource.Parent; if (parentResource == null || parentResource.IsServiceResource) { // Only IResource counts for the resource name, don't include the service itself. return resource.Name; } // Generate the full name using recursion. return GetFullName(parentResource) + "." + resource.Name; } } #endregion #region MockResource /// <summary> /// Mock resource for testing purposes. /// </summary> [VisibleForTestOnly] internal class MockResource : Resource { public MockResource() : this(new MockResourceFactory(), "MockMethod", new JsonDictionary()) {} public MockResource(IServiceFactory factory, string name, JsonDictionary dictionary) : base(factory, name, dictionary) { } private class MockResourceFactory : ServiceFactoryDiscoveryV1_0 { public override IResource CreateResource(string name, JsonDictionary dictionary) { return new MockResource(this, name, dictionary); } } } #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. */ using System; using System.Linq; using Lucene.Net.Index; using Document = Lucene.Net.Documents.Document; using FieldSelector = Lucene.Net.Documents.FieldSelector; using CorruptIndexException = Lucene.Net.Index.CorruptIndexException; using IndexReader = Lucene.Net.Index.IndexReader; using Term = Lucene.Net.Index.Term; using Directory = Lucene.Net.Store.Directory; using ReaderUtil = Lucene.Net.Util.ReaderUtil; namespace Lucene.Net.Search { /// <summary>Implements search over a single IndexReader. /// /// <p/>Applications usually need only call the inherited <see cref="Searcher.Search(Query,int)" /> /// or <see cref="Searcher.Search(Query,Filter,int)" /> methods. For performance reasons it is /// recommended to open only one IndexSearcher and use it for all of your searches. /// /// <a name="thread-safety"></a><p/><b>NOTE</b>: /// <see cref="IndexSearcher" /> instances are completely /// thread safe, meaning multiple threads can call any of its /// methods, concurrently. If your application requires /// external synchronization, you should <b>not</b> /// synchronize on the <c>IndexSearcher</c> instance; /// use your own (non-Lucene) objects instead.<p/> /// </summary> //[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300 public class IndexSearcher : Searcher { internal IndexReader reader; private bool closeReader; private bool isDisposed; // NOTE: these members might change in incompatible ways // in the next release private IndexReader[] subReaders; private int[] docStarts; /// <summary>Creates a searcher searching the index in the named /// directory, with readOnly=true</summary> /// <throws>CorruptIndexException if the index is corrupt</throws> /// <throws>IOException if there is a low-level IO error</throws> public IndexSearcher(Directory path) : this(IndexReader.Open(path, true), true) { } /// <summary>Creates a searcher searching the index in the named /// directory. You should pass readOnly=true, since it /// gives much better concurrent performance, unless you /// intend to do write operations (delete documents or /// change norms) with the underlying IndexReader. /// </summary> /// <throws> CorruptIndexException if the index is corrupt </throws> /// <throws> IOException if there is a low-level IO error </throws> /// <param name="path">directory where IndexReader will be opened /// </param> /// <param name="readOnly">if true, the underlying IndexReader /// will be opened readOnly /// </param> public IndexSearcher(Directory path, bool readOnly):this(IndexReader.Open(path, readOnly), true) { } /// <summary>Creates a searcher searching the provided index /// <para> /// Note that the underlying IndexReader is not closed, if /// IndexSearcher was constructed with IndexSearcher(IndexReader r). /// If the IndexReader was supplied implicitly by specifying a directory, then /// the IndexReader gets closed. /// </para> /// </summary> public IndexSearcher(IndexReader r):this(r, false) { } /// <summary> /// Expert: directly specify the reader, subReaders and their /// DocID starts /// <p/> /// <b>NOTE:</b> This API is experimental and /// might change in incompatible ways in the next /// release<p/> /// </summary> public IndexSearcher(IndexReader reader, IndexReader[] subReaders, int[] docStarts) { this.reader = reader; this.subReaders = subReaders; this.docStarts = docStarts; this.closeReader = false; } private IndexSearcher(IndexReader r, bool closeReader) { reader = r; this.closeReader = closeReader; System.Collections.Generic.IList<IndexReader> subReadersList = new System.Collections.Generic.List<IndexReader>(); GatherSubReaders(subReadersList, reader); subReaders = subReadersList.ToArray(); docStarts = new int[subReaders.Length]; int maxDoc = 0; for (int i = 0; i < subReaders.Length; i++) { docStarts[i] = maxDoc; maxDoc += subReaders[i].MaxDoc; } } protected internal virtual void GatherSubReaders(System.Collections.Generic.IList<IndexReader> allSubReaders, IndexReader r) { ReaderUtil.GatherSubReaders(allSubReaders, r); } /// <summary>Return the <see cref="Index.IndexReader" /> this searches. </summary> public virtual IndexReader IndexReader { get { return reader; } } protected override void Dispose(bool disposing) { if (isDisposed) return; if (disposing) { if (closeReader) reader.Close(); } isDisposed = true; } // inherit javadoc public override int DocFreq(Term term) { return reader.DocFreq(term); } // inherit javadoc public override Document Doc(int i) { return reader.Document(i); } // inherit javadoc public override Document Doc(int i, FieldSelector fieldSelector) { return reader.Document(i, fieldSelector); } // inherit javadoc public override int MaxDoc { get { return reader.MaxDoc; } } // inherit javadoc public override TopDocs Search(Weight weight, Filter filter, int nDocs) { if (nDocs <= 0) { throw new System.ArgumentException("nDocs must be > 0"); } nDocs = Math.Min(nDocs, reader.MaxDoc); TopScoreDocCollector collector = TopScoreDocCollector.Create(nDocs, !weight.GetScoresDocsOutOfOrder()); Search(weight, filter, collector); return collector.TopDocs(); } public override TopFieldDocs Search(Weight weight, Filter filter, int nDocs, Sort sort) { return Search(weight, filter, nDocs, sort, true); } /// <summary> Just like <see cref="Search(Weight, Filter, int, Sort)" />, but you choose /// whether or not the fields in the returned <see cref="FieldDoc" /> instances /// should be set by specifying fillFields. /// <p/> /// NOTE: this does not compute scores by default. If you need scores, create /// a <see cref="TopFieldCollector" /> instance by calling /// <see cref="TopFieldCollector.Create" /> and then pass that to /// <see cref="Search(Weight, Filter, Collector)" />. /// <p/> /// </summary> public virtual TopFieldDocs Search(Weight weight, Filter filter, int nDocs, Sort sort, bool fillFields) { nDocs = Math.Min(nDocs, reader.MaxDoc); TopFieldCollector collector2 = TopFieldCollector.Create(sort, nDocs, fillFields, fieldSortDoTrackScores, fieldSortDoMaxScore, !weight.GetScoresDocsOutOfOrder()); Search(weight, filter, collector2); return (TopFieldDocs) collector2.TopDocs(); } public override void Search(Weight weight, Filter filter, Collector collector) { if (filter == null) { for (int i = 0; i < subReaders.Length; i++) { // search each subreader collector.SetNextReader(subReaders[i], docStarts[i]); Scorer scorer = weight.Scorer(subReaders[i], !collector.AcceptsDocsOutOfOrder, true); if (scorer != null) { scorer.Score(collector); } } } else { for (int i = 0; i < subReaders.Length; i++) { // search each subreader collector.SetNextReader(subReaders[i], docStarts[i]); SearchWithFilter(subReaders[i], weight, filter, collector); } } } private void SearchWithFilter(IndexReader reader, Weight weight, Filter filter, Collector collector) { System.Diagnostics.Debug.Assert(filter != null); Scorer scorer = weight.Scorer(reader, true, false); if (scorer == null) { return ; } int docID = scorer.DocID(); System.Diagnostics.Debug.Assert(docID == - 1 || docID == DocIdSetIterator.NO_MORE_DOCS); // CHECKME: use ConjunctionScorer here? DocIdSet filterDocIdSet = filter.GetDocIdSet(reader); if (filterDocIdSet == null) { // this means the filter does not accept any documents. return ; } DocIdSetIterator filterIter = filterDocIdSet.Iterator(); if (filterIter == null) { // this means the filter does not accept any documents. return ; } int filterDoc = filterIter.NextDoc(); int scorerDoc = scorer.Advance(filterDoc); collector.SetScorer(scorer); while (true) { if (scorerDoc == filterDoc) { // Check if scorer has exhausted, only before collecting. if (scorerDoc == DocIdSetIterator.NO_MORE_DOCS) { break; } collector.Collect(scorerDoc); filterDoc = filterIter.NextDoc(); scorerDoc = scorer.Advance(filterDoc); } else if (scorerDoc > filterDoc) { filterDoc = filterIter.Advance(scorerDoc); } else { scorerDoc = scorer.Advance(filterDoc); } } } public override Query Rewrite(Query original) { Query query = original; for (Query rewrittenQuery = query.Rewrite(reader); rewrittenQuery != query; rewrittenQuery = query.Rewrite(reader)) { query = rewrittenQuery; } return query; } public override Explanation Explain(Weight weight, int doc) { int n = ReaderUtil.SubIndex(doc, docStarts); int deBasedDoc = doc - docStarts[n]; return weight.Explain(subReaders[n], deBasedDoc); } private bool fieldSortDoTrackScores; private bool fieldSortDoMaxScore; /// <summary> By default, no scores are computed when sorting by field (using /// <see cref="Searcher.Search(Query,Filter,int,Sort)" />). You can change that, per /// IndexSearcher instance, by calling this method. Note that this will incur /// a CPU cost. /// /// </summary> /// <param name="doTrackScores">If true, then scores are returned for every matching document /// in <see cref="TopFieldDocs" />. /// /// </param> /// <param name="doMaxScore">If true, then the max score for all matching docs is computed. /// </param> public virtual void SetDefaultFieldSortScoring(bool doTrackScores, bool doMaxScore) { fieldSortDoTrackScores = doTrackScores; fieldSortDoMaxScore = doMaxScore; } public IndexReader reader_ForNUnit { get { return reader; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** Purpose: Provides a way to write primitives types in ** binary from a Stream, while also supporting writing Strings ** in a particular encoding. ** ** ===========================================================*/ using System; using System.Runtime; using System.Runtime.Serialization; using System.Text; using System.Diagnostics.Contracts; namespace System.IO { // This abstract base class represents a writer that can write // primitives to an arbitrary stream. A subclass can override methods to // give unique encodings. // [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class BinaryWriter : IDisposable { public static readonly BinaryWriter Null = new BinaryWriter(); protected Stream OutStream; private byte[] _buffer; // temp space for writing primitives to. private Encoding _encoding; private Encoder _encoder; [OptionalField] // New in .NET FX 4.5. False is the right default value. private bool _leaveOpen; // This field should never have been serialized and has not been used since before v2.0. // However, this type is serializable, and we need to keep the field name around when deserializing. // Also, we'll make .NET FX 4.5 not break if it's missing. #pragma warning disable 169 [OptionalField] private char[] _tmpOneCharBuffer; #pragma warning restore 169 // Perf optimization stuff private byte[] _largeByteBuffer; // temp space for writing chars. private int _maxChars; // max # of chars we can put in _largeByteBuffer // Size should be around the max number of chars/string * Encoding's max bytes/char private const int LargeByteBufferSize = 256; // Protected default constructor that sets the output stream // to a null stream (a bit bucket). protected BinaryWriter() { OutStream = Stream.Null; _buffer = new byte[16]; _encoding = new UTF8Encoding(false, true); _encoder = _encoding.GetEncoder(); } public BinaryWriter(Stream output) : this(output, new UTF8Encoding(false, true), false) { } public BinaryWriter(Stream output, Encoding encoding) : this(output, encoding, false) { } public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen) { if (output==null) throw new ArgumentNullException("output"); if (encoding==null) throw new ArgumentNullException("encoding"); if (!output.CanWrite) throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable")); Contract.EndContractBlock(); OutStream = output; _buffer = new byte[16]; _encoding = encoding; _encoder = _encoding.GetEncoder(); _leaveOpen = leaveOpen; } // Closes this writer and releases any system resources associated with the // writer. Following a call to Close, any operations on the writer // may raise exceptions. public virtual void Close() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { if (_leaveOpen) OutStream.Flush(); else OutStream.Close(); } } public void Dispose() { Dispose(true); } /* * Returns the stream associate with the writer. It flushes all pending * writes before returning. All subclasses should override Flush to * ensure that all buffered data is sent to the stream. */ public virtual Stream BaseStream { get { Flush(); return OutStream; } } // Clears all buffers for this writer and causes any buffered data to be // written to the underlying device. public virtual void Flush() { OutStream.Flush(); } public virtual long Seek(int offset, SeekOrigin origin) { return OutStream.Seek(offset, origin); } // Writes a boolean to this stream. A single byte is written to the stream // with the value 0 representing false or the value 1 representing true. // public virtual void Write(bool value) { _buffer[0] = (byte) (value ? 1 : 0); OutStream.Write(_buffer, 0, 1); } // Writes a byte to this stream. The current position of the stream is // advanced by one. // public virtual void Write(byte value) { OutStream.WriteByte(value); } // Writes a signed byte to this stream. The current position of the stream // is advanced by one. // [CLSCompliant(false)] public virtual void Write(sbyte value) { OutStream.WriteByte((byte) value); } // Writes a byte array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the byte array. // public virtual void Write(byte[] buffer) { if (buffer == null) throw new ArgumentNullException("buffer"); Contract.EndContractBlock(); OutStream.Write(buffer, 0, buffer.Length); } // Writes a section of a byte array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the byte array. // public virtual void Write(byte[] buffer, int index, int count) { OutStream.Write(buffer, index, count); } // Writes a character to this stream. The current position of the stream is // advanced by two. // Note this method cannot handle surrogates properly in UTF-8. // [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual void Write(char ch) { if (Char.IsSurrogate(ch)) throw new ArgumentException(Environment.GetResourceString("Arg_SurrogatesNotAllowedAsSingleChar")); Contract.EndContractBlock(); Contract.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)"); int numBytes = 0; fixed(byte * pBytes = _buffer) { numBytes = _encoder.GetBytes(&ch, 1, pBytes, _buffer.Length, flush: true); } OutStream.Write(_buffer, 0, numBytes); } // Writes a character array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the character array. // public virtual void Write(char[] chars) { if (chars == null) throw new ArgumentNullException("chars"); Contract.EndContractBlock(); byte[] bytes = _encoding.GetBytes(chars, 0, chars.Length); OutStream.Write(bytes, 0, bytes.Length); } // Writes a section of a character array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the character array. // public virtual void Write(char[] chars, int index, int count) { byte[] bytes = _encoding.GetBytes(chars, index, count); OutStream.Write(bytes, 0, bytes.Length); } // Writes a double to this stream. The current position of the stream is // advanced by eight. // [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual void Write(double value) { ulong TmpValue = *(ulong *)&value; _buffer[0] = (byte) TmpValue; _buffer[1] = (byte) (TmpValue >> 8); _buffer[2] = (byte) (TmpValue >> 16); _buffer[3] = (byte) (TmpValue >> 24); _buffer[4] = (byte) (TmpValue >> 32); _buffer[5] = (byte) (TmpValue >> 40); _buffer[6] = (byte) (TmpValue >> 48); _buffer[7] = (byte) (TmpValue >> 56); OutStream.Write(_buffer, 0, 8); } public virtual void Write(decimal value) { Decimal.GetBytes(value,_buffer); OutStream.Write(_buffer, 0, 16); } // Writes a two-byte signed integer to this stream. The current position of // the stream is advanced by two. // public virtual void Write(short value) { _buffer[0] = (byte) value; _buffer[1] = (byte) (value >> 8); OutStream.Write(_buffer, 0, 2); } // Writes a two-byte unsigned integer to this stream. The current position // of the stream is advanced by two. // [CLSCompliant(false)] public virtual void Write(ushort value) { _buffer[0] = (byte) value; _buffer[1] = (byte) (value >> 8); OutStream.Write(_buffer, 0, 2); } // Writes a four-byte signed integer to this stream. The current position // of the stream is advanced by four. // public virtual void Write(int value) { _buffer[0] = (byte) value; _buffer[1] = (byte) (value >> 8); _buffer[2] = (byte) (value >> 16); _buffer[3] = (byte) (value >> 24); OutStream.Write(_buffer, 0, 4); } // Writes a four-byte unsigned integer to this stream. The current position // of the stream is advanced by four. // [CLSCompliant(false)] public virtual void Write(uint value) { _buffer[0] = (byte) value; _buffer[1] = (byte) (value >> 8); _buffer[2] = (byte) (value >> 16); _buffer[3] = (byte) (value >> 24); OutStream.Write(_buffer, 0, 4); } // Writes an eight-byte signed integer to this stream. The current position // of the stream is advanced by eight. // public virtual void Write(long value) { _buffer[0] = (byte) value; _buffer[1] = (byte) (value >> 8); _buffer[2] = (byte) (value >> 16); _buffer[3] = (byte) (value >> 24); _buffer[4] = (byte) (value >> 32); _buffer[5] = (byte) (value >> 40); _buffer[6] = (byte) (value >> 48); _buffer[7] = (byte) (value >> 56); OutStream.Write(_buffer, 0, 8); } // Writes an eight-byte unsigned integer to this stream. The current // position of the stream is advanced by eight. // [CLSCompliant(false)] public virtual void Write(ulong value) { _buffer[0] = (byte) value; _buffer[1] = (byte) (value >> 8); _buffer[2] = (byte) (value >> 16); _buffer[3] = (byte) (value >> 24); _buffer[4] = (byte) (value >> 32); _buffer[5] = (byte) (value >> 40); _buffer[6] = (byte) (value >> 48); _buffer[7] = (byte) (value >> 56); OutStream.Write(_buffer, 0, 8); } // Writes a float to this stream. The current position of the stream is // advanced by four. // [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual void Write(float value) { uint TmpValue = *(uint *)&value; _buffer[0] = (byte) TmpValue; _buffer[1] = (byte) (TmpValue >> 8); _buffer[2] = (byte) (TmpValue >> 16); _buffer[3] = (byte) (TmpValue >> 24); OutStream.Write(_buffer, 0, 4); } // Writes a length-prefixed string to this stream in the BinaryWriter's // current Encoding. This method first writes the length of the string as // a four-byte unsigned integer, and then writes that many characters // to the stream. // [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual void Write(String value) { if (value==null) throw new ArgumentNullException("value"); Contract.EndContractBlock(); int len = _encoding.GetByteCount(value); Write7BitEncodedInt(len); if (_largeByteBuffer == null) { _largeByteBuffer = new byte[LargeByteBufferSize]; _maxChars = _largeByteBuffer.Length / _encoding.GetMaxByteCount(1); } if (len <= _largeByteBuffer.Length) { //Contract.Assert(len == _encoding.GetBytes(chars, 0, chars.Length, _largeByteBuffer, 0), "encoding's GetByteCount & GetBytes gave different answers! encoding type: "+_encoding.GetType().Name); _encoding.GetBytes(value, 0, value.Length, _largeByteBuffer, 0); OutStream.Write(_largeByteBuffer, 0, len); } else { // Aggressively try to not allocate memory in this loop for // runtime performance reasons. Use an Encoder to write out // the string correctly (handling surrogates crossing buffer // boundaries properly). int charStart = 0; int numLeft = value.Length; #if _DEBUG int totalBytes = 0; #endif while (numLeft > 0) { // Figure out how many chars to process this round. int charCount = (numLeft > _maxChars) ? _maxChars : numLeft; int byteLen; checked { if (charStart < 0 || charCount < 0 || charStart > value.Length - charCount) { throw new ArgumentOutOfRangeException(nameof(charCount)); } fixed (char* pChars = value) { fixed (byte* pBytes = _largeByteBuffer) { byteLen = _encoder.GetBytes(pChars + charStart, charCount, pBytes, _largeByteBuffer.Length, charCount == numLeft); } } } #if _DEBUG totalBytes += byteLen; Contract.Assert (totalBytes <= len && byteLen <= _largeByteBuffer.Length, "BinaryWriter::Write(String) - More bytes encoded than expected!"); #endif OutStream.Write(_largeByteBuffer, 0, byteLen); charStart += charCount; numLeft -= charCount; } #if _DEBUG Contract.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!"); #endif } } protected void Write7BitEncodedInt(int value) { // Write out an int 7 bits at a time. The high bit of the byte, // when on, tells reader to continue reading more bytes. uint v = (uint) value; // support negative numbers while (v >= 0x80) { Write((byte) (v | 0x80)); v >>= 7; } Write((byte)v); } } }
// 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.ComponentModel; using System.Diagnostics; using System.Drawing.Internal; using System.Globalization; using System.Runtime.InteropServices; namespace System.Drawing { /// <summary> /// Defines a particular format for text, including font face, size, and style attributes. /// </summary> [ComVisible(true)] public sealed partial class Font : MarshalByRefObject, ICloneable, IDisposable { private const int LogFontCharSetOffset = 23; private const int LogFontNameOffset = 28; private IntPtr _nativeFont; private float _fontSize; private FontStyle _fontStyle; private FontFamily _fontFamily; private GraphicsUnit _fontUnit; private byte _gdiCharSet = SafeNativeMethods.DEFAULT_CHARSET; private bool _gdiVerticalFont; private string _systemFontName = ""; private string _originalFontName; ///<summary> /// Creates the GDI+ native font object. ///</summary> private void CreateNativeFont() { Debug.Assert(_nativeFont == IntPtr.Zero, "nativeFont already initialized, this will generate a handle leak."); Debug.Assert(_fontFamily != null, "fontFamily not initialized."); // Note: GDI+ creates singleton font family objects (from the corresponding font file) and reference count them so // if creating the font object from an external FontFamily, this object's FontFamily will share the same native object. int status = SafeNativeMethods.Gdip.GdipCreateFont( new HandleRef(this, _fontFamily.NativeFamily), _fontSize, _fontStyle, _fontUnit, out _nativeFont); // Special case this common error message to give more information if (status == SafeNativeMethods.Gdip.FontStyleNotFound) { throw new ArgumentException(SR.Format(SR.GdiplusFontStyleNotFound, _fontFamily.Name, _fontStyle.ToString())); } else if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class from the specified existing <see cref='Font'/> /// and <see cref='FontStyle'/>. /// </summary> public Font(Font prototype, FontStyle newStyle) { // Copy over the originalFontName because it won't get initialized _originalFontName = prototype.OriginalFontName; Initialize(prototype.FontFamily, prototype.Size, newStyle, prototype.Unit, SafeNativeMethods.DEFAULT_CHARSET, false); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit) { Initialize(family, emSize, style, unit, SafeNativeMethods.DEFAULT_CHARSET, false); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet) { Initialize(family, emSize, style, unit, gdiCharSet, false); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont) { Initialize(family, emSize, style, unit, gdiCharSet, gdiVerticalFont); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet) { Initialize(familyName, emSize, style, unit, gdiCharSet, IsVerticalName(familyName)); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont) { if (float.IsNaN(emSize) || float.IsInfinity(emSize) || emSize <= 0) { throw new ArgumentException(SR.Format(SR.InvalidBoundArgument, "emSize", emSize, 0, "System.Single.MaxValue"), "emSize"); } Initialize(familyName, emSize, style, unit, gdiCharSet, gdiVerticalFont); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(FontFamily family, float emSize, FontStyle style) { Initialize(family, emSize, style, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, false); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(FontFamily family, float emSize, GraphicsUnit unit) { Initialize(family, emSize, FontStyle.Regular, unit, SafeNativeMethods.DEFAULT_CHARSET, false); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(FontFamily family, float emSize) { Initialize(family, emSize, FontStyle.Regular, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, false); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit) { Initialize(familyName, emSize, style, unit, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName)); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(string familyName, float emSize, FontStyle style) { Initialize(familyName, emSize, style, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName)); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(string familyName, float emSize, GraphicsUnit unit) { Initialize(familyName, emSize, FontStyle.Regular, unit, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName)); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(string familyName, float emSize) { Initialize(familyName, emSize, FontStyle.Regular, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName)); } /// <summary> /// Constructor to initialize fields from an exisiting native GDI+ object reference. Used by ToLogFont. /// </summary> private Font(IntPtr nativeFont, byte gdiCharSet, bool gdiVerticalFont) { Debug.Assert(_nativeFont == IntPtr.Zero, "GDI+ native font already initialized, this will generate a handle leak"); Debug.Assert(nativeFont != IntPtr.Zero, "nativeFont is null"); int status = 0; float size = 0; GraphicsUnit unit = GraphicsUnit.Point; FontStyle style = FontStyle.Regular; IntPtr nativeFamily = IntPtr.Zero; _nativeFont = nativeFont; status = SafeNativeMethods.Gdip.GdipGetFontUnit(new HandleRef(this, nativeFont), out unit); SafeNativeMethods.Gdip.CheckStatus(status); status = SafeNativeMethods.Gdip.GdipGetFontSize(new HandleRef(this, nativeFont), out size); SafeNativeMethods.Gdip.CheckStatus(status); status = SafeNativeMethods.Gdip.GdipGetFontStyle(new HandleRef(this, nativeFont), out style); SafeNativeMethods.Gdip.CheckStatus(status); status = SafeNativeMethods.Gdip.GdipGetFamily(new HandleRef(this, nativeFont), out nativeFamily); SafeNativeMethods.Gdip.CheckStatus(status); SetFontFamily(new FontFamily(nativeFamily)); Initialize(_fontFamily, size, style, unit, gdiCharSet, gdiVerticalFont); } /// <summary> /// Initializes this object's fields. /// </summary> private void Initialize(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont) { _originalFontName = familyName; SetFontFamily(new FontFamily(StripVerticalName(familyName), createDefaultOnFail: true)); Initialize(_fontFamily, emSize, style, unit, gdiCharSet, gdiVerticalFont); } /// <summary> /// Initializes this object's fields. /// </summary> private void Initialize(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont) { if (family == null) { throw new ArgumentNullException(nameof(family)); } if (float.IsNaN(emSize) || float.IsInfinity(emSize) || emSize <= 0) { throw new ArgumentException(SR.Format(SR.InvalidBoundArgument, nameof(emSize), emSize, 0, "System.Single.MaxValue"), nameof(emSize)); } int status; _fontSize = emSize; _fontStyle = style; _fontUnit = unit; _gdiCharSet = gdiCharSet; _gdiVerticalFont = gdiVerticalFont; if (_fontFamily == null) { // GDI+ FontFamily is a singleton object. SetFontFamily(new FontFamily(family.NativeFamily)); } if (_nativeFont == IntPtr.Zero) { CreateNativeFont(); } // Get actual size. status = SafeNativeMethods.Gdip.GdipGetFontSize(new HandleRef(this, _nativeFont), out _fontSize); SafeNativeMethods.Gdip.CheckStatus(status); } /// <summary> /// Creates a <see cref='System.Drawing.Font'/> from the specified Windows handle. /// </summary> public static Font FromHfont(IntPtr hfont) { var lf = new SafeNativeMethods.LOGFONT(); SafeNativeMethods.GetObject(new HandleRef(null, hfont), lf); IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); try { return FromLogFont(lf, screenDC); } finally { UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC)); } } public static Font FromLogFont(object lf) { IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); try { return FromLogFont(lf, screenDC); } finally { UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC)); } } public static Font FromLogFont(object lf, IntPtr hdc) { IntPtr font = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateFontFromLogfontW(new HandleRef(null, hdc), lf, out font); // Special case this incredibly common error message to give more information if (status == SafeNativeMethods.Gdip.NotTrueTypeFont) { throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont_NoName)); } else if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } // GDI+ returns font = 0 even though the status is Ok. if (font == IntPtr.Zero) { throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont, lf.ToString())); } #pragma warning disable 0618 bool gdiVerticalFont = (Marshal.ReadInt16(lf, LogFontNameOffset) == (short)'@'); return new Font(font, Marshal.ReadByte(lf, LogFontCharSetOffset), gdiVerticalFont); #pragma warning restore 0618 } /// <summary> /// Creates a Font from the specified Windows handle to a device context. /// </summary> public static Font FromHdc(IntPtr hdc) { IntPtr font = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateFontFromDC(new HandleRef(null, hdc), ref font); // Special case this incredibly common error message to give more information if (status == SafeNativeMethods.Gdip.NotTrueTypeFont) { throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont_NoName)); } else if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } return new Font(font, 0, false); } /// <summary> /// Creates an exact copy of this <see cref='Font'/>. /// </summary> public object Clone() { IntPtr clonedFont = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCloneFont(new HandleRef(this, _nativeFont), out clonedFont); SafeNativeMethods.Gdip.CheckStatus(status); return new Font(clonedFont, _gdiCharSet, _gdiVerticalFont); } /// <summary> /// Get native GDI+ object pointer. This property triggers the creation of the GDI+ native object if not initialized yet. /// </summary> internal IntPtr NativeFont => _nativeFont; /// <summary> /// Gets the <see cref='Drawing.FontFamily'/> of this <see cref='Font'/>. /// </summary> [Browsable(false)] public FontFamily FontFamily { get { Debug.Assert(_fontFamily != null, "fontFamily should never be null"); return _fontFamily; } } private void SetFontFamily(FontFamily family) { _fontFamily = family; // GDI+ creates ref-counted singleton FontFamily objects based on the family name so all managed // objects with same family name share the underlying GDI+ native pointer. The unmanged object is // destroyed when its ref-count gets to zero. // Make sure this.fontFamily is not finalized so the underlying singleton object is kept alive. GC.SuppressFinalize(_fontFamily); } /// <summary> /// Cleans up Windows resources for this <see cref='Font'/>. /// </summary> ~Font() => Dispose(false); /// <summary> /// Cleans up Windows resources for this <see cref='Font'/>. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (_nativeFont != IntPtr.Zero) { try { #if DEBUG int status = #endif SafeNativeMethods.Gdip.GdipDeleteFont(new HandleRef(this, _nativeFont)); #if DEBUG Debug.Assert(status == SafeNativeMethods.Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); #endif } catch (Exception ex) when (!ClientUtils.IsCriticalException(ex)) { } finally { _nativeFont = IntPtr.Zero; } } } private static bool IsVerticalName(string familyName) => familyName?.Length > 0 && familyName[0] == '@'; /// <summary> /// Gets a value indicating whether this <see cref='System.Drawing.Font'/> is bold. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool Bold => (Style & FontStyle.Bold) != 0; /// <summary> /// Returns the GDI char set for this instance of a font. This will only /// be valid if this font was created from a classic GDI font definition, /// like a LOGFONT or HFONT, or it was passed into the constructor. /// /// This is here for compatability with native Win32 intrinsic controls /// on non-Unicode platforms. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public byte GdiCharSet => _gdiCharSet; /// <summary> /// Determines if this font was created to represt a GDI vertical font. This will only be valid if this font /// was created from a classic GDIfont definition, like a LOGFONT or HFONT, or it was passed into the constructor. /// /// This is here for compatability with native Win32 intrinsic controls on non-Unicode platforms. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool GdiVerticalFont => _gdiVerticalFont; /// <summary> /// Gets a value indicating whether this <see cref='Font'/> is Italic. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool Italic => (Style & FontStyle.Italic) != 0; /// <summary> /// Gets the face name of this <see cref='Font'/> . /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string Name => FontFamily.Name; /// <summary> /// This property is required by the framework and not intended to be used directly. /// </summary> [Browsable(false)] public string OriginalFontName => _originalFontName; /// <summary> /// Gets a value indicating whether this <see cref='Font'/> is strikeout (has a line through it). /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool Strikeout => (Style & FontStyle.Strikeout) != 0; /// <summary> /// Gets a value indicating whether this <see cref='Font'/> is underlined. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool Underline => (Style & FontStyle.Underline) != 0; /// <summary> /// Returns a value indicating whether the specified object is a <see cref='Font'/> equivalent to this /// <see cref='Font'/>. /// </summary> public override bool Equals(object obj) { if (obj == this) { return true; } if (!(obj is Font font)) { return false; } // Note: If this and/or the passed-in font are disposed, this method can still return true since we check for cached properties // here. // We need to call properties on the passed-in object since it could be a proxy in a remoting scenario and proxies don't // have access to private/internal fields. return font.FontFamily.Equals(FontFamily) && font.GdiVerticalFont == GdiVerticalFont && font.GdiCharSet == GdiCharSet && font.Style == Style && font.Size == Size && font.Unit == Unit; } /// <summary> /// Gets the hash code for this <see cref='Font'/>. /// </summary> public override int GetHashCode() { return unchecked((int)((((uint)_fontStyle << 13) | ((uint)_fontStyle >> 19)) ^ (((uint)_fontUnit << 26) | ((uint)_fontUnit >> 6)) ^ (((uint)_fontSize << 7) | ((uint)_fontSize >> 25)))); } private static string StripVerticalName(string familyName) { if (familyName?.Length > 1 && familyName[0] == '@') { return familyName.Substring(1); } return familyName; } /// <summary> /// Returns a human-readable string representation of this <see cref='Font'/>. /// </summary> public override string ToString() { return string.Format(CultureInfo.CurrentCulture, "[{0}: Name={1}, Size={2}, Units={3}, GdiCharSet={4}, GdiVerticalFont={5}]", GetType().Name, FontFamily.Name, _fontSize, (int)_fontUnit, _gdiCharSet, _gdiVerticalFont); } public void ToLogFont(object logFont) { IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); try { Graphics graphics = Graphics.FromHdcInternal(screenDC); try { ToLogFont(logFont, graphics); } finally { graphics.Dispose(); } } finally { UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC)); } } public unsafe void ToLogFont(object logFont, Graphics graphics) { if (graphics == null) { throw new ArgumentNullException(nameof(graphics)); } int status = SafeNativeMethods.Gdip.GdipGetLogFontW(new HandleRef(this, NativeFont), new HandleRef(graphics, graphics.NativeGraphics), logFont); // Prefix the string with '@' this is a gdiVerticalFont. #pragma warning disable 0618 if (_gdiVerticalFont) { // Copy the Unicode contents of the name. for (int i = 60; i >= 0; i -= 2) { Marshal.WriteInt16(logFont, LogFontNameOffset + i + 2, Marshal.ReadInt16(logFont, LogFontNameOffset + i)); } // Prefix the name with an '@' sign. Marshal.WriteInt16(logFont, LogFontNameOffset, (short)'@'); } if (Marshal.ReadByte(logFont, LogFontCharSetOffset) == 0) { Marshal.WriteByte(logFont, LogFontCharSetOffset, _gdiCharSet); } #pragma warning restore 0618 SafeNativeMethods.Gdip.CheckStatus(status); } /// <summary> /// Returns a handle to this <see cref='Font'/>. /// </summary> public IntPtr ToHfont() { var lf = new SafeNativeMethods.LOGFONT(); ToLogFont(lf); IntPtr handle = IntUnsafeNativeMethods.IntCreateFontIndirect(lf); if (handle == IntPtr.Zero) { throw new Win32Exception(); } return handle; } /// <summary> /// Returns the height of this Font in the specified graphics context. /// </summary> public float GetHeight(Graphics graphics) { if (graphics == null) { throw new ArgumentNullException(nameof(graphics)); } float height; int status = SafeNativeMethods.Gdip.GdipGetFontHeight(new HandleRef(this, NativeFont), new HandleRef(graphics, graphics.NativeGraphics), out height); SafeNativeMethods.Gdip.CheckStatus(status); return height; } public float GetHeight() { IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); try { using (Graphics graphics = Graphics.FromHdcInternal(screenDC)) { return GetHeight(graphics); } } finally { UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC)); } } public float GetHeight(float dpi) { float height; int status = SafeNativeMethods.Gdip.GdipGetFontHeightGivenDPI(new HandleRef(this, NativeFont), dpi, out height); SafeNativeMethods.Gdip.CheckStatus(status); return height; } /// <summary> /// Gets style information for this <see cref='Font'/>. /// </summary> [Browsable(false)] public FontStyle Style => _fontStyle; // Return value is in Unit (the unit the font was created in) /// <summary> /// Gets the size of this <see cref='Font'/>. /// </summary> public float Size => _fontSize; /// <summary> /// Gets the size, in points, of this <see cref='Font'/>. /// </summary> [Browsable(false)] public float SizeInPoints { get { if (Unit == GraphicsUnit.Point) { return Size; } IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); try { using (Graphics graphics = Graphics.FromHdcInternal(screenDC)) { float pixelsPerPoint = (float)(graphics.DpiY / 72.0); float lineSpacingInPixels = GetHeight(graphics); float emHeightInPixels = lineSpacingInPixels * FontFamily.GetEmHeight(Style) / FontFamily.GetLineSpacing(Style); return emHeightInPixels / pixelsPerPoint; } } finally { UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC)); } } } /// <summary> /// Gets the unit of measure for this <see cref='Font'/>. /// </summary> public GraphicsUnit Unit => _fontUnit; /// <summary> /// Gets the height of this <see cref='Font'/>. /// </summary> [Browsable(false)] public int Height => (int)Math.Ceiling(GetHeight()); /// <summary> /// Returns true if this <see cref='Font'/> is a SystemFont. /// </summary> [Browsable(false)] public bool IsSystemFont => !string.IsNullOrEmpty(_systemFontName); /// <summary> /// Gets the name of this <see cref='Drawing.SystemFont'/>. /// </summary> [Browsable(false)] public string SystemFontName => _systemFontName; // This is used by SystemFonts when constructing a system Font objects. internal void SetSystemFontName(string systemFontName) => _systemFontName = systemFontName; } }
// 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.Reflection { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; #if FEATURE_REMOTING using System.Runtime.Remoting.Metadata; #endif //FEATURE_REMOTING using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using MemberListType = System.RuntimeType.MemberListType; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; using System.Runtime.CompilerServices; [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_MethodInfo))] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] #pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class MethodInfo : MethodBase, _MethodInfo { #region Constructor protected MethodInfo() { } #endregion #if !FEATURE_CORECLR public static bool operator ==(MethodInfo left, MethodInfo right) { if (ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null || left is RuntimeMethodInfo || right is RuntimeMethodInfo) { return false; } return left.Equals(right); } public static bool operator !=(MethodInfo left, MethodInfo right) { return !(left == right); } #endif // !FEATURE_CORECLR public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } #region MemberInfo Overrides public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Method; } } #endregion #region Public Abstract\Virtual Members public virtual Type ReturnType { get { throw new NotImplementedException(); } } public virtual ParameterInfo ReturnParameter { get { throw new NotImplementedException(); } } public abstract ICustomAttributeProvider ReturnTypeCustomAttributes { get; } public abstract MethodInfo GetBaseDefinition(); [System.Runtime.InteropServices.ComVisible(true)] public override Type[] GetGenericArguments() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } [System.Runtime.InteropServices.ComVisible(true)] public virtual MethodInfo GetGenericMethodDefinition() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } public virtual MethodInfo MakeGenericMethod(params Type[] typeArguments) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } public virtual Delegate CreateDelegate(Type delegateType) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } public virtual Delegate CreateDelegate(Type delegateType, Object target) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } #endregion #if !FEATURE_CORECLR Type _MethodInfo.GetType() { return base.GetType(); } void _MethodInfo.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _MethodInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _MethodInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } // If you implement this method, make sure to include _MethodInfo.Invoke in VM\DangerousAPIs.h and // include _MethodInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. void _MethodInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } [Serializable] internal sealed class RuntimeMethodInfo : MethodInfo, ISerializable, IRuntimeMethodInfo { #region Private Data Members private IntPtr m_handle; private RuntimeTypeCache m_reflectedTypeCache; private string m_name; private string m_toString; private ParameterInfo[] m_parameters; private ParameterInfo m_returnParameter; private BindingFlags m_bindingFlags; private MethodAttributes m_methodAttributes; private Signature m_signature; private RuntimeType m_declaringType; private object m_keepalive; private INVOCATION_FLAGS m_invocationFlags; #if FEATURE_APPX private bool IsNonW8PFrameworkAPI() { if (m_declaringType.IsArray && IsPublic && !IsStatic) return false; RuntimeAssembly rtAssembly = GetRuntimeAssembly(); if (rtAssembly.IsFrameworkAssembly()) { int ctorToken = rtAssembly.InvocableAttributeCtorToken; if (System.Reflection.MetadataToken.IsNullToken(ctorToken) || !CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken)) return true; } if (GetRuntimeType().IsNonW8PFrameworkAPI()) return true; if (IsGenericMethod && !IsGenericMethodDefinition) { foreach (Type t in GetGenericArguments()) { if (((RuntimeType)t).IsNonW8PFrameworkAPI()) return true; } } return false; } internal override bool IsDynamicallyInvokable { get { return !AppDomain.ProfileAPICheck || !IsNonW8PFrameworkAPI(); } } #endif internal INVOCATION_FLAGS InvocationFlags { [System.Security.SecuritySafeCritical] get { if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) { INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN; Type declaringType = DeclaringType; // // first take care of all the NO_INVOKE cases. if (ContainsGenericParameters || ReturnType.IsByRef || (declaringType != null && declaringType.ContainsGenericParameters) || ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) || ((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject)) { // We don't need other flags if this method cannot be invoked invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; } else { // this should be an invocable method, determine the other flags that participate in invocation invocationFlags = RuntimeMethodHandle.GetSecurityFlags(this); if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0) { if ( (Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public || (declaringType != null && declaringType.NeedsReflectionSecurityCheck) ) { // If method is non-public, or declaring type is not visible invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; } else if (IsGenericMethod) { Type[] genericArguments = GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { if (genericArguments[i].NeedsReflectionSecurityCheck) { invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; break; } } } } } #if FEATURE_APPX if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI()) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API; #endif // FEATURE_APPX m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; } return m_invocationFlags; } } #endregion #region Constructor [System.Security.SecurityCritical] // auto-generated internal RuntimeMethodInfo( RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive) { Contract.Ensures(!m_handle.IsNull()); Contract.Assert(!handle.IsNullHandle()); Contract.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle)); m_bindingFlags = bindingFlags; m_declaringType = declaringType; m_keepalive = keepalive; m_handle = handle.Value; m_reflectedTypeCache = reflectedTypeCache; m_methodAttributes = methodAttributes; } #endregion #if FEATURE_REMOTING #region Legacy Remoting Cache // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h. // This member is currently being used by Remoting for caching remoting data. If you // need to cache data here, talk to the Remoting team to work out a mechanism, so that // both caching systems can happily work together. private RemotingMethodCachedData m_cachedData; internal RemotingMethodCachedData RemotingCache { get { // This grabs an internal copy of m_cachedData and uses // that instead of looking at m_cachedData directly because // the cache may get cleared asynchronously. This prevents // us from having to take a lock. RemotingMethodCachedData cache = m_cachedData; if (cache == null) { cache = new RemotingMethodCachedData(this); RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); if (ret != null) cache = ret; } return cache; } } #endregion #endif //FEATURE_REMOTING #region Private Methods RuntimeMethodHandleInternal IRuntimeMethodInfo.Value { [System.Security.SecuritySafeCritical] get { return new RuntimeMethodHandleInternal(m_handle); } } private RuntimeType ReflectedTypeInternal { get { return m_reflectedTypeCache.GetRuntimeType(); } } [System.Security.SecurityCritical] // auto-generated private ParameterInfo[] FetchNonReturnParameters() { if (m_parameters == null) m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature); return m_parameters; } [System.Security.SecurityCritical] // auto-generated private ParameterInfo FetchReturnParameter() { if (m_returnParameter == null) m_returnParameter = RuntimeParameterInfo.GetReturnParameter(this, this, Signature); return m_returnParameter; } #endregion #region Internal Members internal override string FormatNameAndSig(bool serialization) { // Serialization uses ToString to resolve MethodInfo overloads. StringBuilder sbName = new StringBuilder(Name); // serialization == true: use unambiguous (except for assembly name) type names to distinguish between overloads. // serialization == false: use basic format to maintain backward compatibility of MethodInfo.ToString(). TypeNameFormatFlags format = serialization ? TypeNameFormatFlags.FormatSerialization : TypeNameFormatFlags.FormatBasic; if (IsGenericMethod) sbName.Append(RuntimeMethodHandle.ConstructInstantiation(this, format)); sbName.Append("("); sbName.Append(ConstructParameters(GetParameterTypes(), CallingConvention, serialization)); sbName.Append(")"); return sbName.ToString(); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal override bool CacheEquals(object o) { RuntimeMethodInfo m = o as RuntimeMethodInfo; if ((object)m == null) return false; return m.m_handle == m_handle; } internal Signature Signature { get { if (m_signature == null) m_signature = new Signature(this, m_declaringType); return m_signature; } } internal BindingFlags BindingFlags { get { return m_bindingFlags; } } // Differs from MethodHandle in that it will return a valid handle even for reflection only loaded types internal RuntimeMethodHandle GetMethodHandle() { return new RuntimeMethodHandle(this); } [System.Security.SecuritySafeCritical] // auto-generated internal RuntimeMethodInfo GetParentDefinition() { if (!IsVirtual || m_declaringType.IsInterface) return null; RuntimeType parent = (RuntimeType)m_declaringType.BaseType; if (parent == null) return null; int slot = RuntimeMethodHandle.GetSlot(this); if (RuntimeTypeHandle.GetNumVirtuals(parent) <= slot) return null; return (RuntimeMethodInfo)RuntimeType.GetMethodBase(parent, RuntimeTypeHandle.GetMethodAt(parent, slot)); } // Unlike DeclaringType, this will return a valid type even for global methods internal RuntimeType GetDeclaringTypeInternal() { return m_declaringType; } #endregion #region Object Overrides public override String ToString() { if (m_toString == null) m_toString = ReturnType.FormatTypeName() + " " + FormatNameAndSig(); return m_toString; } public override int GetHashCode() { // See RuntimeMethodInfo.Equals() below. if (IsGenericMethod) return ValueType.GetHashCodeOfPtr(m_handle); else return base.GetHashCode(); } [System.Security.SecuritySafeCritical] // auto-generated public override bool Equals(object obj) { if (!IsGenericMethod) return obj == (object)this; // We cannot do simple object identity comparisons for generic methods. // Equals will be called in CerHashTable when RuntimeType+RuntimeTypeCache.GetGenericMethodInfo() // retrieve items from and insert items into s_methodInstantiations which is a CerHashtable. RuntimeMethodInfo mi = obj as RuntimeMethodInfo; if (mi == null || !mi.IsGenericMethod) return false; // now we know that both operands are generic methods IRuntimeMethodInfo handle1 = RuntimeMethodHandle.StripMethodInstantiation(this); IRuntimeMethodInfo handle2 = RuntimeMethodHandle.StripMethodInstantiation(mi); if (handle1.Value.Value != handle2.Value.Value) return false; Type[] lhs = GetGenericArguments(); Type[] rhs = mi.GetGenericArguments(); if (lhs.Length != rhs.Length) return false; for (int i = 0; i < lhs.Length; i++) { if (lhs[i] != rhs[i]) return false; } if (DeclaringType != mi.DeclaringType) return false; if (ReflectedType != mi.ReflectedType) return false; return true; } #endregion #region ICustomAttributeProvider [System.Security.SecuritySafeCritical] // auto-generated public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType as RuntimeType, inherit); } [System.Security.SecuritySafeCritical] // auto-generated public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #region MemberInfo Overrides public override String Name { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) m_name = RuntimeMethodHandle.GetName(this); return m_name; } } public override Type DeclaringType { get { if (m_reflectedTypeCache.IsGlobal) return null; return m_declaringType; } } public override Type ReflectedType { get { if (m_reflectedTypeCache.IsGlobal) return null; return m_reflectedTypeCache.GetRuntimeType(); } } public override MemberTypes MemberType { get { return MemberTypes.Method; } } public override int MetadataToken { [System.Security.SecuritySafeCritical] // auto-generated get { return RuntimeMethodHandle.GetMethodDef(this); } } public override Module Module { get { return GetRuntimeModule(); } } internal RuntimeType GetRuntimeType() { return m_declaringType; } internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); } public override bool IsSecurityCritical { get { return RuntimeMethodHandle.IsSecurityCritical(this); } } public override bool IsSecuritySafeCritical { get { return RuntimeMethodHandle.IsSecuritySafeCritical(this); } } public override bool IsSecurityTransparent { get { return RuntimeMethodHandle.IsSecurityTransparent(this); } } #endregion #region MethodBase Overrides [System.Security.SecuritySafeCritical] // auto-generated internal override ParameterInfo[] GetParametersNoCopy() { FetchNonReturnParameters(); return m_parameters; } [System.Security.SecuritySafeCritical] // auto-generated [System.Diagnostics.Contracts.Pure] public override ParameterInfo[] GetParameters() { FetchNonReturnParameters(); if (m_parameters.Length == 0) return m_parameters; ParameterInfo[] ret = new ParameterInfo[m_parameters.Length]; Array.Copy(m_parameters, ret, m_parameters.Length); return ret; } public override MethodImplAttributes GetMethodImplementationFlags() { return RuntimeMethodHandle.GetImplAttributes(this); } internal bool IsOverloaded { get { return m_reflectedTypeCache.GetMethodList(MemberListType.CaseSensitive, Name).Length > 1; } } public override RuntimeMethodHandle MethodHandle { get { Type declaringType = DeclaringType; if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly")); return new RuntimeMethodHandle(this); } } public override MethodAttributes Attributes { get { return m_methodAttributes; } } public override CallingConventions CallingConvention { get { return Signature.CallingConvention; } } [System.Security.SecuritySafeCritical] // overrides SafeCritical member #if !FEATURE_CORECLR #pragma warning disable 618 [ReflectionPermissionAttribute(SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess)] #pragma warning restore 618 #endif public override MethodBody GetMethodBody() { MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); if (mb != null) mb.m_methodBase = this; return mb; } #endregion #region Invocation Logic(On MemberBase) private void CheckConsistency(Object target) { // only test instance methods if ((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static) { if (!m_declaringType.IsInstanceOfType(target)) { if (target == null) throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg")); else throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch")); } } } [System.Security.SecuritySafeCritical] private void ThrowNoInvokeException() { // method is ReflectionOnly Type declaringType = DeclaringType; if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) { throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke")); } // method is on a class that contains stack pointers else if ((InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS) != 0) { throw new NotSupportedException(); } // method is vararg else if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) { throw new NotSupportedException(); } // method is generic or on a generic class else if (DeclaringType.ContainsGenericParameters || ContainsGenericParameters) { throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenParam")); } // method is abstract class else if (IsAbstract) { throw new MemberAccessException(); } // ByRef return are not allowed in reflection else if (ReturnType.IsByRef) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_ByRefReturn")); } throw new TargetException(); } [System.Security.SecuritySafeCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture); #region Security Check INVOCATION_FLAGS invocationFlags = InvocationFlags; #if FEATURE_APPX if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark); if (caller != null && !caller.IsSafeForReflection()) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName)); } #endif if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0) { #if !FEATURE_CORECLR if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0) CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess); if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0) #endif // !FEATURE_CORECLR RuntimeMethodHandle.PerformSecurityCheck(obj, this, m_declaringType, (uint)m_invocationFlags); } #endregion return UnsafeInvokeInternal(obj, parameters, arguments); } [System.Security.SecurityCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal object UnsafeInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture); return UnsafeInvokeInternal(obj, parameters, arguments); } [System.Security.SecurityCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] private object UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) { if (arguments == null || arguments.Length == 0) return RuntimeMethodHandle.InvokeMethod(obj, null, Signature, false); else { Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, Signature, false); // copy out. This should be made only if ByRef are present. for (int index = 0; index < arguments.Length; index++) parameters[index] = arguments[index]; return retValue; } } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] private object[] InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { Signature sig = Signature; // get the signature int formalCount = sig.Arguments.Length; int actualCount = (parameters != null) ? parameters.Length : 0; INVOCATION_FLAGS invocationFlags = InvocationFlags; // INVOCATION_FLAGS_CONTAINS_STACK_POINTERS means that the struct (either the declaring type or the return type) // contains pointers that point to the stack. This is either a ByRef or a TypedReference. These structs cannot // be boxed and thus cannot be invoked through reflection which only deals with boxed value type objects. if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS)) != 0) ThrowNoInvokeException(); // check basic method consistency. This call will throw if there are problems in the target/method relationship CheckConsistency(obj); if (formalCount != actualCount) throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt")); if (actualCount != 0) return CheckArguments(parameters, binder, invokeAttr, culture, sig); else return null; } #endregion #region MethodInfo Overrides public override Type ReturnType { get { return Signature.ReturnType; } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return ReturnParameter; } } public override ParameterInfo ReturnParameter { [System.Security.SecuritySafeCritical] // auto-generated get { Contract.Ensures(m_returnParameter != null); FetchReturnParameter(); return m_returnParameter as ParameterInfo; } } [System.Security.SecuritySafeCritical] // auto-generated public override MethodInfo GetBaseDefinition() { if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface) return this; int slot = RuntimeMethodHandle.GetSlot(this); RuntimeType declaringType = (RuntimeType)DeclaringType; RuntimeType baseDeclaringType = declaringType; RuntimeMethodHandleInternal baseMethodHandle = new RuntimeMethodHandleInternal(); do { int cVtblSlots = RuntimeTypeHandle.GetNumVirtuals(declaringType); if (cVtblSlots <= slot) break; baseMethodHandle = RuntimeTypeHandle.GetMethodAt(declaringType, slot); baseDeclaringType = declaringType; declaringType = (RuntimeType)declaringType.BaseType; } while (declaringType != null); return(MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle); } [System.Security.SecuritySafeCritical] public override Delegate CreateDelegate(Type delegateType) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; // This API existed in v1/v1.1 and only expected to create closed // instance delegates. Constrain the call to BindToMethodInfo to // open delegates only for backwards compatibility. But we'll allow // relaxed signature checking and open static delegates because // there's no ambiguity there (the caller would have to explicitly // pass us a static method or a method with a non-exact signature // and the only change in behavior from v1.1 there is that we won't // fail the call). return CreateDelegateInternal( delegateType, null, DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature, ref stackMark); } [System.Security.SecuritySafeCritical] public override Delegate CreateDelegate(Type delegateType, Object target) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; // This API is new in Whidbey and allows the full range of delegate // flexability (open or closed delegates binding to static or // instance methods with relaxed signature checking). The delegate // can also be closed over null. There's no ambiguity with all these // options since the caller is providing us a specific MethodInfo. return CreateDelegateInternal( delegateType, target, DelegateBindingFlags.RelaxedSignature, ref stackMark); } [System.Security.SecurityCritical] private Delegate CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags, ref StackCrawlMark stackMark) { // Validate the parameters. if (delegateType == null) throw new ArgumentNullException("delegateType"); Contract.EndContractBlock(); RuntimeType rtType = delegateType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "delegateType"); if (!rtType.IsDelegate()) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "delegateType"); Delegate d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags, ref stackMark); if (d == null) { throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); } return d; } #endregion #region Generics [System.Security.SecuritySafeCritical] // auto-generated public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation) { if (methodInstantiation == null) throw new ArgumentNullException("methodInstantiation"); Contract.EndContractBlock(); RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length]; if (!IsGenericMethodDefinition) throw new InvalidOperationException( Environment.GetResourceString("Arg_NotGenericMethodDefinition", this)); for (int i = 0; i < methodInstantiation.Length; i++) { Type methodInstantiationElem = methodInstantiation[i]; if (methodInstantiationElem == null) throw new ArgumentNullException(); RuntimeType rtMethodInstantiationElem = methodInstantiationElem as RuntimeType; if (rtMethodInstantiationElem == null) { Type[] methodInstantiationCopy = new Type[methodInstantiation.Length]; for (int iCopy = 0; iCopy < methodInstantiation.Length; iCopy++) methodInstantiationCopy[iCopy] = methodInstantiation[iCopy]; methodInstantiation = methodInstantiationCopy; return System.Reflection.Emit.MethodBuilderInstantiation.MakeGenericMethod(this, methodInstantiation); } methodInstantionRuntimeType[i] = rtMethodInstantiationElem; } RuntimeType[] genericParameters = GetGenericArgumentsInternal(); RuntimeType.SanityCheckGenericArguments(methodInstantionRuntimeType, genericParameters); MethodInfo ret = null; try { ret = RuntimeType.GetMethodBase(ReflectedTypeInternal, RuntimeMethodHandle.GetStubIfNeeded(new RuntimeMethodHandleInternal(this.m_handle), m_declaringType, methodInstantionRuntimeType)) as MethodInfo; } catch (VerificationException e) { RuntimeType.ValidateGenericArguments(this, methodInstantionRuntimeType, e); throw; } return ret; } internal RuntimeType[] GetGenericArgumentsInternal() { return RuntimeMethodHandle.GetMethodInstantiationInternal(this); } public override Type[] GetGenericArguments() { Type[] types = RuntimeMethodHandle.GetMethodInstantiationPublic(this); if (types == null) { types = EmptyArray<Type>.Value; } return types; } public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); Contract.EndContractBlock(); return RuntimeType.GetMethodBase(m_declaringType, RuntimeMethodHandle.StripMethodInstantiation(this)) as MethodInfo; } public override bool IsGenericMethod { get { return RuntimeMethodHandle.HasMethodInstantiation(this); } } public override bool IsGenericMethodDefinition { get { return RuntimeMethodHandle.IsGenericMethodDefinition(this); } } public override bool ContainsGenericParameters { get { if (DeclaringType != null && DeclaringType.ContainsGenericParameters) return true; if (!IsGenericMethod) return false; Type[] pis = GetGenericArguments(); for (int i = 0; i < pis.Length; i++) { if (pis[i].ContainsGenericParameters) return true; } return false; } } #endregion #region ISerializable Implementation [System.Security.SecurityCritical] // auto-generated public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); if (m_reflectedTypeCache.IsGlobal) throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization")); MemberInfoSerializationHolder.GetSerializationInfo( info, Name, ReflectedTypeInternal, ToString(), SerializationToString(), MemberTypes.Method, IsGenericMethod & !IsGenericMethodDefinition ? GetGenericArguments() : null); } internal string SerializationToString() { return ReturnType.FormatTypeName(true) + " " + FormatNameAndSig(true); } #endregion #region Legacy Internal internal static MethodBase InternalGetCurrentMethod(ref StackCrawlMark stackMark) { IRuntimeMethodInfo method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark); if (method == null) return null; return RuntimeType.GetMethodBase(method); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Diagnostics; using System.DirectoryServices.Interop; using System.ComponentModel; using System.Threading; using System.Reflection; using System.DirectoryServices.Design; using System.Globalization; using System.Net; namespace System.DirectoryServices { /// <devdoc> /// Encapsulates a node or an object in the Active Directory hierarchy. /// </devdoc> [ TypeConverterAttribute(typeof(DirectoryEntryConverter)) ] public class DirectoryEntry : Component { private string _path = ""; private UnsafeNativeMethods.IAds _adsObject; private bool _useCache = true; private bool _cacheFilled; // disable csharp compiler warning #0414: field assigned unused value #pragma warning disable 0414 internal bool propertiesAlreadyEnumerated = false; #pragma warning restore 0414 private bool _disposed = false; private AuthenticationTypes _authenticationType = AuthenticationTypes.Secure; private NetworkCredential _credentials; private readonly DirectoryEntryConfiguration _options; private PropertyCollection _propertyCollection = null; internal bool allowMultipleChange = false; private bool _userNameIsNull = false; private bool _passwordIsNull = false; private bool _objectSecurityInitialized = false; private bool _objectSecurityModified = false; private ActiveDirectorySecurity _objectSecurity = null; private static string s_securityDescriptorProperty = "ntSecurityDescriptor"; /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/>class. /// </devdoc> public DirectoryEntry() { _options = new DirectoryEntryConfiguration(this); } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class that will bind /// to the directory entry at <paramref name="path"/>. /// </devdoc> public DirectoryEntry(string path) : this() { Path = path; } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class. /// </devdoc> public DirectoryEntry(string path, string username, string password) : this(path, username, password, AuthenticationTypes.Secure) { } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class. /// </devdoc> public DirectoryEntry(string path, string username, string password, AuthenticationTypes authenticationType) : this(path) { _credentials = new NetworkCredential(username, password); if (username == null) _userNameIsNull = true; if (password == null) _passwordIsNull = true; _authenticationType = authenticationType; } internal DirectoryEntry(string path, bool useCache, string username, string password, AuthenticationTypes authenticationType) { _path = path; _useCache = useCache; _credentials = new NetworkCredential(username, password); if (username == null) _userNameIsNull = true; if (password == null) _passwordIsNull = true; _authenticationType = authenticationType; _options = new DirectoryEntryConfiguration(this); } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class that will bind /// to the native Active Directory object which is passed in. /// </devdoc> public DirectoryEntry(object adsObject) : this(adsObject, true, null, null, AuthenticationTypes.Secure, true) { } internal DirectoryEntry(object adsObject, bool useCache, string username, string password, AuthenticationTypes authenticationType) : this(adsObject, useCache, username, password, authenticationType, false) { } internal DirectoryEntry(object adsObject, bool useCache, string username, string password, AuthenticationTypes authenticationType, bool AdsObjIsExternal) { _adsObject = adsObject as UnsafeNativeMethods.IAds; if (_adsObject == null) throw new ArgumentException(SR.DSDoesNotImplementIADs); // GetInfo is not needed here. ADSI executes an implicit GetInfo when GetEx // is called on the PropertyValueCollection. 0x800704BC error might be returned // on some WinNT entries, when iterating through 'Users' group members. // if (forceBind) // this.adsObject.GetInfo(); _path = _adsObject.ADsPath; _useCache = useCache; _authenticationType = authenticationType; _credentials = new NetworkCredential(username, password); if (username == null) _userNameIsNull = true; if (password == null) _passwordIsNull = true; if (!useCache) CommitChanges(); _options = new DirectoryEntryConfiguration(this); // We are starting from an already bound connection so make sure the options are set properly. // If this is an externallly managed com object then we don't want to change it's current behavior if (!AdsObjIsExternal) { InitADsObjectOptions(); } } internal UnsafeNativeMethods.IAds AdsObject { get { Bind(); return _adsObject; } } [DefaultValue(AuthenticationTypes.Secure)] public AuthenticationTypes AuthenticationType { get => _authenticationType; set { if (_authenticationType == value) return; _authenticationType = value; Unbind(); } } private bool Bound => _adsObject != null; /// <devdoc> /// Gets a <see cref='System.DirectoryServices.DirectoryEntries'/> /// containing the child entries of this node in the Active /// Directory hierarchy. /// </devdoc> public DirectoryEntries Children => new DirectoryEntries(this); internal UnsafeNativeMethods.IAdsContainer ContainerObject { get { Bind(); return (UnsafeNativeMethods.IAdsContainer)_adsObject; } } /// <devdoc> /// Gets the globally unique identifier of the <see cref='System.DirectoryServices.DirectoryEntry'/>. /// </devdoc> public Guid Guid { get { string guid = NativeGuid; if (guid.Length == 32) { // oddly, the value comes back as a string with no dashes from LDAP byte[] intGuid = new byte[16]; for (int j = 0; j < 16; j++) { intGuid[j] = Convert.ToByte(new string(new char[] { guid[j * 2], guid[j * 2 + 1] }), 16); } return new Guid(intGuid); // return new Guid(guid.Substring(0, 8) + "-" + guid.Substring(8, 4) + "-" + guid.Substring(12, 4) + "-" + guid.Substring(16, 4) + "-" + guid.Substring(20)); } else return new Guid(guid); } } public ActiveDirectorySecurity ObjectSecurity { get { if (!_objectSecurityInitialized) { _objectSecurity = GetObjectSecurityFromCache(); _objectSecurityInitialized = true; } return _objectSecurity; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } _objectSecurity = value; _objectSecurityInitialized = true; _objectSecurityModified = true; CommitIfNotCaching(); } } internal bool IsContainer { get { Bind(); return _adsObject is UnsafeNativeMethods.IAdsContainer; } } internal bool JustCreated { get; set; } /// <devdoc> /// Gets the relative name of the object as named with the underlying directory service. /// </devdoc> public string Name { get { Bind(); string tmpName = _adsObject.Name; GC.KeepAlive(this); return tmpName; } } public string NativeGuid { get { FillCache("GUID"); string tmpGuid = _adsObject.GUID; GC.KeepAlive(this); return tmpGuid; } } /// <devdoc> /// Gets the native Active Directory Services Interface (ADSI) object. /// </devdoc> public object NativeObject { get { Bind(); return _adsObject; } } /// <devdoc> /// Gets this entry's parent entry in the Active Directory hierarchy. /// </devdoc> public DirectoryEntry Parent { get { Bind(); return new DirectoryEntry(_adsObject.Parent, UsePropertyCache, GetUsername(), GetPassword(), AuthenticationType); } } /// <devdoc> /// Gets or sets the password to use when authenticating the client. /// </devdoc> [DefaultValue(null)] public string Password { set { if (value == GetPassword()) return; if (_credentials == null) { _credentials = new NetworkCredential(); // have not set it yet _userNameIsNull = true; } if (value == null) _passwordIsNull = true; else _passwordIsNull = false; _credentials.Password = value; Unbind(); } } /// <devdoc> /// Gets or sets the path for this <see cref='System.DirectoryServices.DirectoryEntry'/>. /// </devdoc> [ DefaultValue(""), // CoreFXPort - Remove design support // TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign) ] public string Path { get => _path; set { if (value == null) value = ""; if (System.DirectoryServices.ActiveDirectory.Utils.Compare(_path, value) == 0) return; _path = value; Unbind(); } } /// <devdoc> /// Gets a <see cref='System.DirectoryServices.PropertyCollection'/> of properties set on this object. /// </devdoc> public PropertyCollection Properties { get { if (_propertyCollection == null) { _propertyCollection = new PropertyCollection(this); } return _propertyCollection; } } /// <devdoc> /// Gets the name of the schema used for this <see cref='System.DirectoryServices.DirectoryEntry'/> /// </devdoc> public string SchemaClassName { get { Bind(); string tmpClass = _adsObject.Class; GC.KeepAlive(this); return tmpClass; } } /// <devdoc> /// Gets the <see cref='System.DirectoryServices.DirectoryEntry'/> that holds schema information for this /// entry. An entry's <see cref='System.DirectoryServices.DirectoryEntry.SchemaClassName'/> /// determines what properties are valid for it. /// </devdoc> public DirectoryEntry SchemaEntry { get { Bind(); return new DirectoryEntry(_adsObject.Schema, UsePropertyCache, GetUsername(), GetPassword(), AuthenticationType); } } // By default changes to properties are done locally to // a cache and reading property values is cached after // the first read. Setting this to false will cause the // cache to be committed after each operation. // /// <devdoc> /// Gets a value indicating whether the cache should be committed after each /// operation. /// </devdoc> [DefaultValue(true)] public bool UsePropertyCache { get => _useCache; set { if (value == _useCache) return; // auto-commit when they set this to false. if (!value) CommitChanges(); _cacheFilled = false; // cache mode has been changed _useCache = value; } } /// <devdoc> /// Gets or sets the username to use when authenticating the client. /// </devdoc> [ DefaultValue(null), // CoreFXPort - Remove design support // TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign) ] public string Username { get { if (_credentials == null || _userNameIsNull) return null; return _credentials.UserName; } set { if (value == GetUsername()) return; if (_credentials == null) { _credentials = new NetworkCredential(); _passwordIsNull = true; } if (value == null) _userNameIsNull = true; else _userNameIsNull = false; _credentials.UserName = value; Unbind(); } } public DirectoryEntryConfiguration Options { get { // only LDAP provider supports IADsObjectOptions, so make the check here if (!(AdsObject is UnsafeNativeMethods.IAdsObjectOptions)) return null; return _options; } } internal void InitADsObjectOptions() { if (_adsObject is UnsafeNativeMethods.IAdsObjectOptions2) { //-------------------------------------------- // Check if ACCUMULATE_MODIFICATION is available //-------------------------------------------- object o = null; int unmanagedResult = 0; // check whether the new option is available // 8 is ADS_OPTION_ACCUMULATIVE_MODIFICATION unmanagedResult = ((UnsafeNativeMethods.IAdsObjectOptions2)_adsObject).GetOption(8, out o); if (unmanagedResult != 0) { // rootdse does not support this option and invalid parameter due to without accumulative change fix in ADSI if ((unmanagedResult == unchecked((int)0x80004001)) || (unmanagedResult == unchecked((int)0x80005008))) { return; } else { throw COMExceptionHelper.CreateFormattedComException(unmanagedResult); } } // the new option is available, set it so we get the new PutEx behavior that will allow multiple changes Variant value = new Variant(); value.varType = 11; //VT_BOOL value.boolvalue = -1; ((UnsafeNativeMethods.IAdsObjectOptions2)_adsObject).SetOption(8, value); allowMultipleChange = true; } } /// <devdoc> /// Binds to the ADs object (if not already bound). /// </devdoc> private void Bind() { Bind(true); } internal void Bind(bool throwIfFail) { //Cannot rebind after the object has been disposed, since finalization has been suppressed. if (_disposed) throw new ObjectDisposedException(GetType().Name); if (_adsObject == null) { string pathToUse = Path; if (pathToUse == null || pathToUse.Length == 0) { // get the default naming context. This should be the default root for the search. DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE", true, null, null, AuthenticationTypes.Secure); //SECREVIEW: Looking at the root of the DS will demand browse permissions // on "*" or "LDAP://RootDSE". string defaultNamingContext = (string)rootDSE.Properties["defaultNamingContext"][0]; rootDSE.Dispose(); pathToUse = "LDAP://" + defaultNamingContext; } // Ensure we've got a thread model set, else CoInitialize() won't have been called. if (Thread.CurrentThread.GetApartmentState() == ApartmentState.Unknown) Thread.CurrentThread.SetApartmentState(ApartmentState.MTA); Guid g = new Guid("00000000-0000-0000-c000-000000000046"); // IID_IUnknown object value = null; int hr = UnsafeNativeMethods.ADsOpenObject(pathToUse, GetUsername(), GetPassword(), (int)_authenticationType, ref g, out value); if (hr != 0) { if (throwIfFail) throw COMExceptionHelper.CreateFormattedComException(hr); } else { _adsObject = (UnsafeNativeMethods.IAds)value; } InitADsObjectOptions(); } } // Create new entry with the same data, but different IADs object, and grant it Browse Permission. internal DirectoryEntry CloneBrowsable() { DirectoryEntry newEntry = new DirectoryEntry(this.Path, this.UsePropertyCache, this.GetUsername(), this.GetPassword(), this.AuthenticationType); return newEntry; } /// <devdoc> /// Closes the <see cref='System.DirectoryServices.DirectoryEntry'/> /// and releases any system resources associated with this component. /// </devdoc> public void Close() { Unbind(); } /// <devdoc> /// Saves any changes to the entry in the directory store. /// </devdoc> public void CommitChanges() { if (JustCreated) { // Note: Permissions Demand is not necessary here, because entry has already been created with appr. permissions. // Write changes regardless of Caching mode to finish construction of a new entry. try { // // Write the security descriptor to the cache // SetObjectSecurityInCache(); _adsObject.SetInfo(); } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } JustCreated = false; _objectSecurityInitialized = false; _objectSecurityModified = false; // we need to refresh that properties table. _propertyCollection = null; return; } if (!_useCache) { // unless we have modified the existing security descriptor (in-place) through ObjectSecurity property // there is nothing to do if ((_objectSecurity == null) || (!_objectSecurity.IsModified())) { return; } } if (!Bound) return; try { // // Write the security descriptor to the cache // SetObjectSecurityInCache(); _adsObject.SetInfo(); _objectSecurityInitialized = false; _objectSecurityModified = false; } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } // we need to refresh that properties table. _propertyCollection = null; } internal void CommitIfNotCaching() { if (JustCreated) return; // Do not write changes, beacuse the entry is just under construction until CommitChanges() is called. if (_useCache) return; if (!Bound) return; try { // // Write the security descriptor to the cache // SetObjectSecurityInCache(); _adsObject.SetInfo(); _objectSecurityInitialized = false; _objectSecurityModified = false; } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } // we need to refresh that properties table. _propertyCollection = null; } /// <devdoc> /// Creates a copy of this entry as a child of the given parent. /// </devdoc> public DirectoryEntry CopyTo(DirectoryEntry newParent) => CopyTo(newParent, null); /// <devdoc> /// Creates a copy of this entry as a child of the given parent and gives it a new name. /// </devdoc> public DirectoryEntry CopyTo(DirectoryEntry newParent, string newName) { if (!newParent.IsContainer) throw new InvalidOperationException(SR.Format(SR.DSNotAContainer , newParent.Path)); object copy = null; try { copy = newParent.ContainerObject.CopyHere(Path, newName); } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } return new DirectoryEntry(copy, newParent.UsePropertyCache, GetUsername(), GetPassword(), AuthenticationType); } /// <devdoc> /// Deletes this entry and its entire subtree from the Active Directory hierarchy. /// </devdoc> public void DeleteTree() { if (!(AdsObject is UnsafeNativeMethods.IAdsDeleteOps)) throw new InvalidOperationException(SR.DSCannotDelete); UnsafeNativeMethods.IAdsDeleteOps entry = (UnsafeNativeMethods.IAdsDeleteOps)AdsObject; try { entry.DeleteObject(0); } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } GC.KeepAlive(this); } protected override void Dispose(bool disposing) { // no managed object to free // free own state (unmanaged objects) if (!_disposed) { Unbind(); _disposed = true; } base.Dispose(disposing); } /// <devdoc> /// Searches the directory store at the given path to see whether an entry exists. /// </devdoc> public static bool Exists(string path) { DirectoryEntry entry = new DirectoryEntry(path); try { entry.Bind(true); // throws exceptions (possibly can break applications) return entry.Bound; } catch (System.Runtime.InteropServices.COMException e) { if (e.ErrorCode == unchecked((int)0x80072030) || e.ErrorCode == unchecked((int)0x80070003) || // ERROR_DS_NO_SUCH_OBJECT and path not found (not found in strict sense) e.ErrorCode == unchecked((int)0x800708AC)) // Group name could not be found return false; throw; } finally { entry.Dispose(); } } /// <devdoc> /// If UsePropertyCache is true, calls GetInfo the first time it's necessary. /// If it's false, calls GetInfoEx on the given property name. /// </devdoc> internal void FillCache(string propertyName) { if (UsePropertyCache) { if (_cacheFilled) return; RefreshCache(); _cacheFilled = true; } else { Bind(); try { if (propertyName.Length > 0) _adsObject.GetInfoEx(new object[] { propertyName }, 0); else _adsObject.GetInfo(); } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } } } /// <devdoc> /// Calls a method on the native Active Directory. /// </devdoc> public object Invoke(string methodName, params object[] args) { object target = this.NativeObject; Type type = target.GetType(); object result = null; try { result = type.InvokeMember(methodName, BindingFlags.InvokeMethod, null, target, args, CultureInfo.InvariantCulture); GC.KeepAlive(this); } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } catch (TargetInvocationException e) { if (e.InnerException != null) { if (e.InnerException is COMException) { COMException inner = (COMException)e.InnerException; throw new TargetInvocationException(e.Message, COMExceptionHelper.CreateFormattedComException(inner)); } } throw e; } if (result is UnsafeNativeMethods.IAds) return new DirectoryEntry(result, UsePropertyCache, GetUsername(), GetPassword(), AuthenticationType); else return result; } /// <devdoc> /// Reads a property on the native Active Directory object. /// </devdoc> public object InvokeGet(string propertyName) { object target = this.NativeObject; Type type = target.GetType(); object result = null; try { result = type.InvokeMember(propertyName, BindingFlags.GetProperty, null, target, null, CultureInfo.InvariantCulture); GC.KeepAlive(this); } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } catch (TargetInvocationException e) { if (e.InnerException != null) { if (e.InnerException is COMException) { COMException inner = (COMException)e.InnerException; throw new TargetInvocationException(e.Message, COMExceptionHelper.CreateFormattedComException(inner)); } } throw e; } return result; } /// <devdoc> /// Sets a property on the native Active Directory object. /// </devdoc> public void InvokeSet(string propertyName, params object[] args) { object target = this.NativeObject; Type type = target.GetType(); try { type.InvokeMember(propertyName, BindingFlags.SetProperty, null, target, args, CultureInfo.InvariantCulture); GC.KeepAlive(this); } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } catch (TargetInvocationException e) { if (e.InnerException != null) { if (e.InnerException is COMException) { COMException inner = (COMException)e.InnerException; throw new TargetInvocationException(e.Message, COMExceptionHelper.CreateFormattedComException(inner)); } } throw e; } } /// <devdoc> /// Moves this entry to the given parent. /// </devdoc> public void MoveTo(DirectoryEntry newParent) => MoveTo(newParent, null); /// <devdoc> /// Moves this entry to the given parent, and gives it a new name. /// </devdoc> public void MoveTo(DirectoryEntry newParent, string newName) { object newEntry = null; if (!(newParent.AdsObject is UnsafeNativeMethods.IAdsContainer)) throw new InvalidOperationException(SR.Format(SR.DSNotAContainer , newParent.Path)); try { if (AdsObject.ADsPath.StartsWith("WinNT:", StringComparison.Ordinal)) { // get the ADsPath instead of using Path as ADsPath for the case that "WinNT://computername" is passed in while we need "WinNT://domain/computer" string childPath = AdsObject.ADsPath; string parentPath = newParent.AdsObject.ADsPath; // we know ADsPath does not end with object type qualifier like ",computer" so it is fine to compare with whole newparent's adspath // for the case that child has different components from newparent in the aspects other than case, we don't do any processing, just let ADSI decide in case future adsi change if (System.DirectoryServices.ActiveDirectory.Utils.Compare(childPath, 0, parentPath.Length, parentPath, 0, parentPath.Length) == 0) { uint compareFlags = System.DirectoryServices.ActiveDirectory.Utils.NORM_IGNORENONSPACE | System.DirectoryServices.ActiveDirectory.Utils.NORM_IGNOREKANATYPE | System.DirectoryServices.ActiveDirectory.Utils.NORM_IGNOREWIDTH | System.DirectoryServices.ActiveDirectory.Utils.SORT_STRINGSORT; // work around the ADSI case sensitive if (System.DirectoryServices.ActiveDirectory.Utils.Compare(childPath, 0, parentPath.Length, parentPath, 0, parentPath.Length, compareFlags) != 0) { childPath = parentPath + childPath.Substring(parentPath.Length); } } newEntry = newParent.ContainerObject.MoveHere(childPath, newName); } else { newEntry = newParent.ContainerObject.MoveHere(Path, newName); } } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } if (Bound) System.Runtime.InteropServices.Marshal.ReleaseComObject(_adsObject); // release old handle _adsObject = (UnsafeNativeMethods.IAds)newEntry; _path = _adsObject.ADsPath; // Reset the options on the ADSI object since there were lost when the new object was created. InitADsObjectOptions(); if (!_useCache) CommitChanges(); else RefreshCache(); // in ADSI cache is lost after moving } /// <devdoc> /// Loads the property values for this directory entry into the property cache. /// </devdoc> public void RefreshCache() { Bind(); try { _adsObject.GetInfo(); } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } _cacheFilled = true; // we need to refresh that properties table. _propertyCollection = null; // need to refresh the objectSecurity property _objectSecurityInitialized = false; _objectSecurityModified = false; } /// <devdoc> /// Loads the values of the specified properties into the property cache. /// </devdoc> public void RefreshCache(string[] propertyNames) { Bind(); //Consider there shouldn't be any marshaling issues //by just doing: AdsObject.GetInfoEx(object[]propertyNames, 0); object[] names = new object[propertyNames.Length]; for (int i = 0; i < propertyNames.Length; i++) names[i] = propertyNames[i]; try { AdsObject.GetInfoEx(names, 0); } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } // this is a half-lie, but oh well. Without it, this method is pointless. _cacheFilled = true; // we need to partially refresh that properties table. if (_propertyCollection != null && propertyNames != null) { for (int i = 0; i < propertyNames.Length; i++) { if (propertyNames[i] != null) { string name = propertyNames[i].ToLower(CultureInfo.InvariantCulture); _propertyCollection.valueTable.Remove(name); // also need to consider the range retrieval case string[] results = name.Split(new char[] { ';' }); if (results.Length != 1) { string rangeName = ""; for (int count = 0; count < results.Length; count++) { if (!results[count].StartsWith("range=", StringComparison.Ordinal)) { rangeName += results[count]; rangeName += ";"; } } // remove the last ';' character rangeName = rangeName.Remove(rangeName.Length - 1, 1); _propertyCollection.valueTable.Remove(rangeName); } // if this is "ntSecurityDescriptor" we should refresh the objectSecurity property if (string.Equals(propertyNames[i], s_securityDescriptorProperty, StringComparison.OrdinalIgnoreCase)) { _objectSecurityInitialized = false; _objectSecurityModified = false; } } } } } /// <devdoc> /// Changes the name of this entry. /// </devdoc> public void Rename(string newName) => MoveTo(Parent, newName); private void Unbind() { if (_adsObject != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(_adsObject); _adsObject = null; // we need to release that properties table. _propertyCollection = null; // need to refresh the objectSecurity property _objectSecurityInitialized = false; _objectSecurityModified = false; } internal string GetUsername() { if (_credentials == null || _userNameIsNull) return null; return _credentials.UserName; } internal string GetPassword() { if (_credentials == null || _passwordIsNull) return null; return _credentials.Password; } private ActiveDirectorySecurity GetObjectSecurityFromCache() { try { // // This property is the managed version of the "ntSecurityDescriptor" // attribute. In order to build an ActiveDirectorySecurity object from it // we need to get the binary form of the security descriptor. // If we use IADs::Get to get the IADsSecurityDescriptor interface and then // convert to raw form, there would be a performance overhead (because of // sid lookups and reverse lookups during conversion). // So to get the security descriptor in binary form, we use // IADsPropertyList::GetPropertyItem // // // GetPropertyItem does not implicitly fill the property cache // so we need to fill it explicitly (for an existing entry) // if (!JustCreated) { SecurityMasks securityMasksUsedInRetrieval; // // To ensure that we honor the security masks while retrieving // the security descriptor, we will retrieve the "ntSecurityDescriptor" each time // while initializing the ObjectSecurity property // securityMasksUsedInRetrieval = this.Options.SecurityMasks; RefreshCache(new string[] { s_securityDescriptorProperty }); // // Get the IAdsPropertyList interface // (Check that the IAdsPropertyList interface is supported) // if (!(NativeObject is UnsafeNativeMethods.IAdsPropertyList)) throw new NotSupportedException(SR.DSPropertyListUnsupported); UnsafeNativeMethods.IAdsPropertyList list = (UnsafeNativeMethods.IAdsPropertyList)NativeObject; UnsafeNativeMethods.IAdsPropertyEntry propertyEntry = (UnsafeNativeMethods.IAdsPropertyEntry)list.GetPropertyItem(s_securityDescriptorProperty, (int)AdsType.ADSTYPE_OCTET_STRING); GC.KeepAlive(this); // // Create a new ActiveDirectorySecurity object from the binary form // of the security descriptor // object[] values = (object[])propertyEntry.Values; // // This should never happen. It indicates that there is a problem in ADSI's property cache logic. // if (values.Length < 1) { Debug.Fail("ntSecurityDescriptor property exists in cache but has no values."); throw new InvalidOperationException(SR.DSSDNoValues); } // // Do not support more than one security descriptor // if (values.Length > 1) { throw new NotSupportedException(SR.DSMultipleSDNotSupported); } UnsafeNativeMethods.IAdsPropertyValue propertyValue = (UnsafeNativeMethods.IAdsPropertyValue)values[0]; return new ActiveDirectorySecurity((byte[])propertyValue.OctetString, securityMasksUsedInRetrieval); } else { // // Newly created directory entry // return null; } } catch (System.Runtime.InteropServices.COMException e) { if (e.ErrorCode == unchecked((int)0x8000500D)) // property not found exception return null; else throw; } } private void SetObjectSecurityInCache() { if ((_objectSecurity != null) && (_objectSecurityModified || _objectSecurity.IsModified())) { UnsafeNativeMethods.IAdsPropertyValue sDValue = (UnsafeNativeMethods.IAdsPropertyValue)new UnsafeNativeMethods.PropertyValue(); sDValue.ADsType = (int)AdsType.ADSTYPE_OCTET_STRING; sDValue.OctetString = _objectSecurity.GetSecurityDescriptorBinaryForm(); UnsafeNativeMethods.IAdsPropertyEntry newSDEntry = (UnsafeNativeMethods.IAdsPropertyEntry)new UnsafeNativeMethods.PropertyEntry(); newSDEntry.Name = s_securityDescriptorProperty; newSDEntry.ADsType = (int)AdsType.ADSTYPE_OCTET_STRING; newSDEntry.ControlCode = (int)AdsPropertyOperation.Update; newSDEntry.Values = new object[] { sDValue }; ((UnsafeNativeMethods.IAdsPropertyList)NativeObject).PutPropertyItem(newSDEntry); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.Azure.Management.Network; using Microsoft.Azure.Management.Network.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Network { /// <summary> /// The Network Resource Provider API includes operations for managing the /// Virtual network Gateway for your subscription. /// </summary> internal partial class LocalNetworkGatewayOperations : IServiceOperations<NetworkResourceProviderClient>, ILocalNetworkGatewayOperations { /// <summary> /// Initializes a new instance of the LocalNetworkGatewayOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal LocalNetworkGatewayOperations(NetworkResourceProviderClient client) { this._client = client; } private NetworkResourceProviderClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Network.NetworkResourceProviderClient. /// </summary> public NetworkResourceProviderClient Client { get { return this._client; } } /// <summary> /// The Put LocalNetworkGateway operation creates/updates a local /// network gateway in the specified resource group through Network /// resource provider. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='localNetworkGatewayName'> /// Required. The name of the local network gateway. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Begin Create or update Local /// Network Gateway operation through Network resource provider. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for PutLocalNetworkGateway Api servive call /// </returns> public async Task<LocalNetworkGatewayPutResponse> BeginCreateOrUpdatingAsync(string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (localNetworkGatewayName == null) { throw new ArgumentNullException("localNetworkGatewayName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Location == null) { throw new ArgumentNullException("parameters.Location"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdatingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Network"; url = url + "/localNetworkGateways/"; url = url + Uri.EscapeDataString(localNetworkGatewayName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject localNetworkGatewayJsonFormatValue = new JObject(); requestDoc = localNetworkGatewayJsonFormatValue; JObject propertiesValue = new JObject(); localNetworkGatewayJsonFormatValue["properties"] = propertiesValue; if (parameters.LocalNetworkAddressSpace != null) { JObject localNetworkAddressSpaceValue = new JObject(); propertiesValue["localNetworkAddressSpace"] = localNetworkAddressSpaceValue; if (parameters.LocalNetworkAddressSpace.AddressPrefixes != null) { if (parameters.LocalNetworkAddressSpace.AddressPrefixes is ILazyCollection == false || ((ILazyCollection)parameters.LocalNetworkAddressSpace.AddressPrefixes).IsInitialized) { JArray addressPrefixesArray = new JArray(); foreach (string addressPrefixesItem in parameters.LocalNetworkAddressSpace.AddressPrefixes) { addressPrefixesArray.Add(addressPrefixesItem); } localNetworkAddressSpaceValue["addressPrefixes"] = addressPrefixesArray; } } } if (parameters.GatewayIpAddress != null) { propertiesValue["gatewayIpAddress"] = parameters.GatewayIpAddress; } if (parameters.ResourceGuid != null) { propertiesValue["resourceGuid"] = parameters.ResourceGuid; } if (parameters.ProvisioningState != null) { propertiesValue["provisioningState"] = parameters.ProvisioningState; } if (parameters.Etag != null) { localNetworkGatewayJsonFormatValue["etag"] = parameters.Etag; } if (parameters.Id != null) { localNetworkGatewayJsonFormatValue["id"] = parameters.Id; } if (parameters.Name != null) { localNetworkGatewayJsonFormatValue["name"] = parameters.Name; } if (parameters.Type != null) { localNetworkGatewayJsonFormatValue["type"] = parameters.Type; } localNetworkGatewayJsonFormatValue["location"] = parameters.Location; if (parameters.Tags != null) { JObject tagsDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Tags) { string tagsKey = pair.Key; string tagsValue = pair.Value; tagsDictionary[tagsKey] = tagsValue; } localNetworkGatewayJsonFormatValue["tags"] = tagsDictionary; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LocalNetworkGatewayPutResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LocalNetworkGatewayPutResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { LocalNetworkGateway localNetworkGatewayInstance = new LocalNetworkGateway(); result.LocalNetworkGateway = localNetworkGatewayInstance; JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { JToken localNetworkAddressSpaceValue2 = propertiesValue2["localNetworkAddressSpace"]; if (localNetworkAddressSpaceValue2 != null && localNetworkAddressSpaceValue2.Type != JTokenType.Null) { AddressSpace localNetworkAddressSpaceInstance = new AddressSpace(); localNetworkGatewayInstance.LocalNetworkAddressSpace = localNetworkAddressSpaceInstance; JToken addressPrefixesArray2 = localNetworkAddressSpaceValue2["addressPrefixes"]; if (addressPrefixesArray2 != null && addressPrefixesArray2.Type != JTokenType.Null) { foreach (JToken addressPrefixesValue in ((JArray)addressPrefixesArray2)) { localNetworkAddressSpaceInstance.AddressPrefixes.Add(((string)addressPrefixesValue)); } } } JToken gatewayIpAddressValue = propertiesValue2["gatewayIpAddress"]; if (gatewayIpAddressValue != null && gatewayIpAddressValue.Type != JTokenType.Null) { string gatewayIpAddressInstance = ((string)gatewayIpAddressValue); localNetworkGatewayInstance.GatewayIpAddress = gatewayIpAddressInstance; } JToken resourceGuidValue = propertiesValue2["resourceGuid"]; if (resourceGuidValue != null && resourceGuidValue.Type != JTokenType.Null) { string resourceGuidInstance = ((string)resourceGuidValue); localNetworkGatewayInstance.ResourceGuid = resourceGuidInstance; } JToken provisioningStateValue = propertiesValue2["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); localNetworkGatewayInstance.ProvisioningState = provisioningStateInstance; } } JToken etagValue = responseDoc["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); localNetworkGatewayInstance.Etag = etagInstance; } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); localNetworkGatewayInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); localNetworkGatewayInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); localNetworkGatewayInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); localNetworkGatewayInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey2 = ((string)property.Name); string tagsValue2 = ((string)property.Value); localNetworkGatewayInstance.Tags.Add(tagsKey2, tagsValue2); } } JToken errorValue = responseDoc["error"]; if (errorValue != null && errorValue.Type != JTokenType.Null) { Error errorInstance = new Error(); result.Error = errorInstance; JToken codeValue = errorValue["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = errorValue["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = errorValue["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } JToken detailsArray = errorValue["details"]; if (detailsArray != null && detailsArray.Type != JTokenType.Null) { foreach (JToken detailsValue in ((JArray)detailsArray)) { ErrorDetails errorDetailsInstance = new ErrorDetails(); errorInstance.Details.Add(errorDetailsInstance); JToken codeValue2 = detailsValue["code"]; if (codeValue2 != null && codeValue2.Type != JTokenType.Null) { string codeInstance2 = ((string)codeValue2); errorDetailsInstance.Code = codeInstance2; } JToken targetValue2 = detailsValue["target"]; if (targetValue2 != null && targetValue2.Type != JTokenType.Null) { string targetInstance2 = ((string)targetValue2); errorDetailsInstance.Target = targetInstance2; } JToken messageValue2 = detailsValue["message"]; if (messageValue2 != null && messageValue2.Type != JTokenType.Null) { string messageInstance2 = ((string)messageValue2); errorDetailsInstance.Message = messageInstance2; } } } JToken innerErrorValue = errorValue["innerError"]; if (innerErrorValue != null && innerErrorValue.Type != JTokenType.Null) { string innerErrorInstance = ((string)innerErrorValue); errorInstance.InnerError = innerErrorInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Azure-AsyncOperation")) { result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Delete LocalNetworkGateway operation deletes the specifed local /// network Gateway through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='localNetworkGatewayName'> /// Required. The name of the local network gateway. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// If the resource provide needs to return an error to any operation, /// it should return the appropriate HTTP error code and a message /// body as can be seen below.The message should be localized per the /// Accept-Language header specified in the original request such /// thatit could be directly be exposed to users /// </returns> public async Task<UpdateOperationResponse> BeginDeletingAsync(string resourceGroupName, string localNetworkGatewayName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (localNetworkGatewayName == null) { throw new ArgumentNullException("localNetworkGatewayName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName); TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Network"; url = url + "/localNetworkGateways/"; url = url + Uri.EscapeDataString(localNetworkGatewayName); url = url + "/"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result UpdateOperationResponse result = null; // Deserialize Response result = new UpdateOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Azure-AsyncOperation")) { result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Put LocalNetworkGateway operation creates/updates a local /// network gateway in the specified resource group through Network /// resource provider. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='localNetworkGatewayName'> /// Required. The name of the local network gateway. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Begin Create or update Local /// Network Gateway operation through Network resource provider. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async Task<AzureAsyncOperationResponse> CreateOrUpdateAsync(string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters, CancellationToken cancellationToken) { NetworkResourceProviderClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); LocalNetworkGatewayPutResponse response = await client.LocalNetworkGateways.BeginCreateOrUpdatingAsync(resourceGroupName, localNetworkGatewayName, parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); AzureAsyncOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != Microsoft.Azure.Management.Network.Models.OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// The Delete LocalNetworkGateway operation deletes the specifed local /// network Gateway through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='localNetworkGatewayName'> /// Required. The name of the local network gateway. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string localNetworkGatewayName, CancellationToken cancellationToken) { NetworkResourceProviderClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); UpdateOperationResponse response = await client.LocalNetworkGateways.BeginDeletingAsync(resourceGroupName, localNetworkGatewayName, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); AzureAsyncOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != Microsoft.Azure.Management.Network.Models.OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// The Get LocalNetworkGateway operation retrieves information about /// the specified local network gateway through Network resource /// provider. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='localNetworkGatewayName'> /// Required. The name of the local network gateway. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for GetLocalNetworkgateway Api servive call. /// </returns> public async Task<LocalNetworkGatewayGetResponse> GetAsync(string resourceGroupName, string localNetworkGatewayName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (localNetworkGatewayName == null) { throw new ArgumentNullException("localNetworkGatewayName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Network"; url = url + "/localNetworkGateways/"; url = url + Uri.EscapeDataString(localNetworkGatewayName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LocalNetworkGatewayGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LocalNetworkGatewayGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { LocalNetworkGateway localNetworkGatewayInstance = new LocalNetworkGateway(); result.LocalNetworkGateway = localNetworkGatewayInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JToken localNetworkAddressSpaceValue = propertiesValue["localNetworkAddressSpace"]; if (localNetworkAddressSpaceValue != null && localNetworkAddressSpaceValue.Type != JTokenType.Null) { AddressSpace localNetworkAddressSpaceInstance = new AddressSpace(); localNetworkGatewayInstance.LocalNetworkAddressSpace = localNetworkAddressSpaceInstance; JToken addressPrefixesArray = localNetworkAddressSpaceValue["addressPrefixes"]; if (addressPrefixesArray != null && addressPrefixesArray.Type != JTokenType.Null) { foreach (JToken addressPrefixesValue in ((JArray)addressPrefixesArray)) { localNetworkAddressSpaceInstance.AddressPrefixes.Add(((string)addressPrefixesValue)); } } } JToken gatewayIpAddressValue = propertiesValue["gatewayIpAddress"]; if (gatewayIpAddressValue != null && gatewayIpAddressValue.Type != JTokenType.Null) { string gatewayIpAddressInstance = ((string)gatewayIpAddressValue); localNetworkGatewayInstance.GatewayIpAddress = gatewayIpAddressInstance; } JToken resourceGuidValue = propertiesValue["resourceGuid"]; if (resourceGuidValue != null && resourceGuidValue.Type != JTokenType.Null) { string resourceGuidInstance = ((string)resourceGuidValue); localNetworkGatewayInstance.ResourceGuid = resourceGuidInstance; } JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); localNetworkGatewayInstance.ProvisioningState = provisioningStateInstance; } } JToken etagValue = responseDoc["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); localNetworkGatewayInstance.Etag = etagInstance; } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); localNetworkGatewayInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); localNetworkGatewayInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); localNetworkGatewayInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); localNetworkGatewayInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); localNetworkGatewayInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The List LocalNetworkGateways opertion retrieves all the local /// network gateways stored. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for ListLocalNetworkGateways Api service call /// </returns> public async Task<LocalNetworkGatewayListResponse> ListAsync(string resourceGroupName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Network"; url = url + "/localNetworkGateways"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LocalNetworkGatewayListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LocalNetworkGatewayListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { LocalNetworkGateway localNetworkGatewayJsonFormatInstance = new LocalNetworkGateway(); result.LocalNetworkGateways.Add(localNetworkGatewayJsonFormatInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JToken localNetworkAddressSpaceValue = propertiesValue["localNetworkAddressSpace"]; if (localNetworkAddressSpaceValue != null && localNetworkAddressSpaceValue.Type != JTokenType.Null) { AddressSpace localNetworkAddressSpaceInstance = new AddressSpace(); localNetworkGatewayJsonFormatInstance.LocalNetworkAddressSpace = localNetworkAddressSpaceInstance; JToken addressPrefixesArray = localNetworkAddressSpaceValue["addressPrefixes"]; if (addressPrefixesArray != null && addressPrefixesArray.Type != JTokenType.Null) { foreach (JToken addressPrefixesValue in ((JArray)addressPrefixesArray)) { localNetworkAddressSpaceInstance.AddressPrefixes.Add(((string)addressPrefixesValue)); } } } JToken gatewayIpAddressValue = propertiesValue["gatewayIpAddress"]; if (gatewayIpAddressValue != null && gatewayIpAddressValue.Type != JTokenType.Null) { string gatewayIpAddressInstance = ((string)gatewayIpAddressValue); localNetworkGatewayJsonFormatInstance.GatewayIpAddress = gatewayIpAddressInstance; } JToken resourceGuidValue = propertiesValue["resourceGuid"]; if (resourceGuidValue != null && resourceGuidValue.Type != JTokenType.Null) { string resourceGuidInstance = ((string)resourceGuidValue); localNetworkGatewayJsonFormatInstance.ResourceGuid = resourceGuidInstance; } JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); localNetworkGatewayJsonFormatInstance.ProvisioningState = provisioningStateInstance; } } JToken etagValue = valueValue["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); localNetworkGatewayJsonFormatInstance.Etag = etagInstance; } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); localNetworkGatewayJsonFormatInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); localNetworkGatewayJsonFormatInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); localNetworkGatewayJsonFormatInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); localNetworkGatewayJsonFormatInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); localNetworkGatewayJsonFormatInstance.Tags.Add(tagsKey, tagsValue); } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Shouldly { internal static class Is { public static bool InRange<T>(T comparable, T @from, T to) where T : IComparable<T> { return comparable.CompareTo(from) >= 0 && comparable.CompareTo(to) <= 0; } public static bool Same(object actual, object expected) { if (actual == null && expected == null) return true; if (actual == null || expected == null) return false; return ReferenceEquals(actual, expected); } public static bool Equal<T>(T expected, T actual) { return Equal(expected, actual, GetEqualityComparer<T>()); } public static bool Equal<T>(T expected, T actual, IEqualityComparer<T> comparer) { return comparer.Equals(actual, expected); } static IEqualityComparer<T> GetEqualityComparer<T>(IEqualityComparer innerComparer = null) { return new EqualityComparer<T>(innerComparer); } public static bool Equal<T>(IEnumerable<T> actual, IEnumerable<T> expected) { if (actual == null && expected == null) return true; if (actual == null || expected == null) return false; var expectedEnum = expected.GetEnumerator(); var actualEnum = actual.GetEnumerator(); for (; ; ) { var expectedHasData = expectedEnum.MoveNext(); var actualHasData = actualEnum.MoveNext(); if (!expectedHasData && !actualHasData) return true; if (expectedHasData != actualHasData || !Equal(actualEnum.Current, expectedEnum.Current)) { return false; } } } public static bool EqualIgnoreOrder<T>(IEnumerable<T> actual, IEnumerable<T> expected) { if (actual == null && expected == null) return true; if (actual == null || expected == null) return false; var actualCollection = actual as ICollection; if (actualCollection != null && expected is ICollection && actualCollection.Count != ((ICollection)expected).Count) return false; var expectedList = expected.ToList(); foreach (var actualElement in actual) { var match = expectedList.FirstOrDefault(x => Equal(x, actualElement)); if (!expectedList.Remove(match)) return false; } return !expectedList.Any(); } public static bool Equal(IEnumerable<decimal> actual, IEnumerable<decimal> expected, decimal tolerance) { var expectedEnum = expected.GetEnumerator(); var actualEnum = actual.GetEnumerator(); for (; ; ) { var expectedHasData = expectedEnum.MoveNext(); var actualHasData = actualEnum.MoveNext(); if (!expectedHasData && !actualHasData) return true; if (expectedHasData != actualHasData || !Equal(actualEnum.Current, expectedEnum.Current, tolerance)) { return false; } } } public static bool Equal(IEnumerable<float> actual, IEnumerable<float> expected, double tolerance) { var expectedEnum = expected.GetEnumerator(); var actualEnum = actual.GetEnumerator(); for (; ; ) { var expectedHasData = expectedEnum.MoveNext(); var actualHasData = actualEnum.MoveNext(); if (!expectedHasData && !actualHasData) return true; if (expectedHasData != actualHasData || !Equal(actualEnum.Current, expectedEnum.Current, tolerance)) { return false; } } } public static bool Equal(IEnumerable<double> actual, IEnumerable<double> expected, double tolerance) { var expectedEnum = expected.GetEnumerator(); var actualEnum = actual.GetEnumerator(); for (; ; ) { var expectedHasData = expectedEnum.MoveNext(); var actualHasData = actualEnum.MoveNext(); if (!expectedHasData && !actualHasData) return true; if (expectedHasData != actualHasData || !Equal(actualEnum.Current, expectedEnum.Current, tolerance)) { return false; } } } public static bool Equal(decimal actual, decimal expected, decimal tolerance) { return Math.Abs(actual - expected) < tolerance; } public static bool Equal(double actual, double expected, double tolerance) { return Math.Abs(actual - expected) < tolerance; } public static bool Equal(DateTime actual, DateTime expected, TimeSpan tolerance) { return (actual - expected).Duration() < tolerance; } public static bool Equal(DateTimeOffset actual, DateTimeOffset expected, TimeSpan tolerance) { return (actual - expected).Duration() < tolerance; } public static bool Equal(TimeSpan actual, TimeSpan expected, TimeSpan tolerance) { return (actual - expected).Duration() < tolerance; } public static bool InstanceOf(object o, Type expected) { if (o == null) return false; return expected.IsInstanceOfType(o); } public static bool StringMatchingRegex(string actual, string regexPattern) { return Regex.IsMatch(actual, regexPattern); } public static bool StringContainingIgnoreCase(string actual, string expected) { if (actual == null) return false; return actual.IndexOf(expected, StringComparison.InvariantCultureIgnoreCase) != -1; } public static bool EndsWithIgnoringCase(string actual, string expected) { if (actual == null) return false; return actual.EndsWith(expected, StringComparison.InvariantCultureIgnoreCase); } public static bool StringStartingWithIgnoreCase(string actual, string expected) { if (actual == null) return false; return actual.StartsWith(expected, StringComparison.InvariantCultureIgnoreCase); } public static bool StringEqualIgnoreCase(string actual, string expected) { return StringComparer.InvariantCultureIgnoreCase.Equals(actual, expected); } public static bool GreaterThanOrEqualTo<T>(IComparable<T> comparable, T expected) { return Compare(comparable, expected) >= 0; } public static bool LessThanOrEqualTo<T>(IComparable<T> comparable, T expected) { return Compare(comparable, expected) <= 0; } public static bool GreaterThan<T>(IComparable<T> comparable, T expected) { return Compare(comparable, expected) > 0; } public static bool LessThan<T>(IComparable<T> comparable, T expected) { return Compare(comparable, expected) < 0; } private static decimal Compare<T>(IComparable<T> comparable, T expected) { if (!typeof(T).IsValueType) { // ReSharper disable CompareNonConstrainedGenericWithNull if (comparable == null) return expected == null ? 0 : -1; if (expected == null) return +1; // ReSharper restore CompareNonConstrainedGenericWithNull } return comparable.CompareTo(expected); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.IO; using System.Text; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Html; namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers { /// <summary> /// <para> /// A <see cref="TextWriter"/> that is backed by a unbuffered writer (over the Response stream) and/or a /// <see cref="ViewBuffer"/> /// </para> /// <para> /// When <c>Flush</c> or <c>FlushAsync</c> is invoked, the writer copies all content from the buffer to /// the writer and switches to writing to the unbuffered writer for all further write operations. /// </para> /// </summary> internal class ViewBufferTextWriter : TextWriter { private readonly TextWriter _inner; private readonly HtmlEncoder _htmlEncoder; /// <summary> /// Creates a new instance of <see cref="ViewBufferTextWriter"/>. /// </summary> /// <param name="buffer">The <see cref="ViewBuffer"/> for buffered output.</param> /// <param name="encoding">The <see cref="System.Text.Encoding"/>.</param> public ViewBufferTextWriter(ViewBuffer buffer, Encoding encoding) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (encoding == null) { throw new ArgumentNullException(nameof(encoding)); } Buffer = buffer; Encoding = encoding; } /// <summary> /// Creates a new instance of <see cref="ViewBufferTextWriter"/>. /// </summary> /// <param name="buffer">The <see cref="ViewBuffer"/> for buffered output.</param> /// <param name="encoding">The <see cref="System.Text.Encoding"/>.</param> /// <param name="htmlEncoder">The HTML encoder.</param> /// <param name="inner"> /// The inner <see cref="TextWriter"/> to write output to when this instance is no longer buffering. /// </param> public ViewBufferTextWriter(ViewBuffer buffer, Encoding encoding, HtmlEncoder htmlEncoder, TextWriter inner) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (encoding == null) { throw new ArgumentNullException(nameof(encoding)); } if (htmlEncoder == null) { throw new ArgumentNullException(nameof(htmlEncoder)); } if (inner == null) { throw new ArgumentNullException(nameof(inner)); } Buffer = buffer; Encoding = encoding; _htmlEncoder = htmlEncoder; _inner = inner; } /// <inheritdoc /> public override Encoding Encoding { get; } /// <summary> /// Gets the <see cref="ViewBuffer"/>. /// </summary> public ViewBuffer Buffer { get; } /// <summary> /// Gets a value that indiciates if <see cref="Flush"/> or <see cref="FlushAsync" /> was invoked. /// </summary> public bool Flushed { get; private set; } /// <inheritdoc /> public override void Write(char value) { Buffer.AppendHtml(value.ToString()); } /// <inheritdoc /> public override void Write(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException(nameof(buffer)); } Buffer.AppendHtml(new string(buffer, index, count)); } /// <inheritdoc /> public override void Write(string value) { if (string.IsNullOrEmpty(value)) { return; } Buffer.AppendHtml(value); } /// <inheritdoc /> public override void Write(object value) { if (value == null) { return; } if (value is IHtmlContentContainer container) { Write(container); } else if (value is IHtmlContent htmlContent) { Write(htmlContent); } else { Write(value.ToString()); } } /// <summary> /// Writes an <see cref="IHtmlContent"/> value. /// </summary> /// <param name="value">The <see cref="IHtmlContent"/> value.</param> public void Write(IHtmlContent value) { if (value == null) { return; } Buffer.AppendHtml(value); } /// <summary> /// Writes an <see cref="IHtmlContentContainer"/> value. /// </summary> /// <param name="value">The <see cref="IHtmlContentContainer"/> value.</param> public void Write(IHtmlContentContainer value) { if (value == null) { return; } value.MoveTo(Buffer); } /// <inheritdoc /> public override void WriteLine(object value) { if (value == null) { return; } if (value is IHtmlContentContainer container) { Write(container); Write(NewLine); } else if (value is IHtmlContent htmlContent) { Write(htmlContent); Write(NewLine); } else { Write(value.ToString()); Write(NewLine); } } /// <inheritdoc /> public override Task WriteAsync(char value) { Buffer.AppendHtml(value.ToString()); return Task.CompletedTask; } /// <inheritdoc /> public override Task WriteAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0 || (buffer.Length - index < count)) { throw new ArgumentOutOfRangeException(nameof(count)); } Buffer.AppendHtml(new string(buffer, index, count)); return Task.CompletedTask; } /// <inheritdoc /> public override Task WriteAsync(string value) { Buffer.AppendHtml(value); return Task.CompletedTask; } /// <inheritdoc /> public override void WriteLine() { Buffer.AppendHtml(NewLine); } /// <inheritdoc /> public override void WriteLine(string value) { Buffer.AppendHtml(value); Buffer.AppendHtml(NewLine); } /// <inheritdoc /> public override Task WriteLineAsync(char value) { Buffer.AppendHtml(value.ToString()); Buffer.AppendHtml(NewLine); return Task.CompletedTask; } /// <inheritdoc /> public override Task WriteLineAsync(char[] value, int start, int offset) { Buffer.AppendHtml(new string(value, start, offset)); Buffer.AppendHtml(NewLine); return Task.CompletedTask; } /// <inheritdoc /> public override Task WriteLineAsync(string value) { Buffer.AppendHtml(value); Buffer.AppendHtml(NewLine); return Task.CompletedTask; } /// <inheritdoc /> public override Task WriteLineAsync() { Buffer.AppendHtml(NewLine); return Task.CompletedTask; } /// <summary> /// Copies the buffered content to the unbuffered writer and invokes flush on it. /// </summary> public override void Flush() { if (_inner == null || _inner is ViewBufferTextWriter) { return; } Flushed = true; Buffer.WriteTo(_inner, _htmlEncoder); Buffer.Clear(); _inner.Flush(); } /// <summary> /// Copies the buffered content to the unbuffered writer and invokes flush on it. /// </summary> /// <returns>A <see cref="Task"/> that represents the asynchronous copy and flush operations.</returns> public override async Task FlushAsync() { if (_inner == null || _inner is ViewBufferTextWriter) { return; } Flushed = true; await Buffer.WriteToAsync(_inner, _htmlEncoder); Buffer.Clear(); await _inner.FlushAsync(); } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlTypes; public partial class Backoffice_Controls_EditKasirFIS : System.Web.UI.UserControl { public int NoKe = 0; public decimal TotalTagihan = 0; protected void Page_Load(object sender, EventArgs e) { } private void ModeEditForm() { pnlList.Visible = false; pnlEdit.Visible = true; pnlView.Visible = false; btnAdd.Visible = false; lblError.Text = ""; lblWarning.Text = ""; } private void ModeListForm() { pnlList.Visible = true; pnlEdit.Visible = false; pnlView.Visible = false; btnAdd.Visible = true; } private void ModeViewForm() { lblWarning.Text = ""; GV.EditIndex = -1; pnlList.Visible = false; pnlEdit.Visible = false; pnlView.Visible = true; btnAdd.Visible = false; } protected void GV_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) { GV.SelectedIndex = e.NewSelectedIndex; FillFormView(GV.DataKeys[e.NewSelectedIndex].Value.ToString()); ModeViewForm(); } protected void GV_PageIndexChanging(object sender, GridViewPageEventArgs e) { GV.PageIndex = e.NewPageIndex; GV.SelectedIndex = -1; BindDataGrid(); } protected void GV_Sorting(object sender, GridViewSortEventArgs e) { String strSortBy = GV.Attributes["SortField"]; String strSortAscending = GV.Attributes["SortAscending"]; // Sets the new sorting field GV.Attributes["SortField"] = e.SortExpression; // Sets the order (defaults to ascending). If you click on the // sorted column, the order reverts. GV.Attributes["SortAscending"] = "yes"; if (e.SortExpression == strSortBy) GV.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes"); // Refreshes the view GV.SelectedIndex = -1; BindDataGrid(); } protected void GV_RowEditing(object sender, GridViewEditEventArgs e) { lblTitleEditForm.Text = Resources.GetString("RS", "TitleKasirEditFIS"); GV.SelectedIndex = e.NewEditIndex; string key = GV.DataKeys[e.NewEditIndex].Value.ToString(); FillFormEdit(key); ModeEditForm(); } protected void btnEditDetil_Click(object sender, EventArgs e) { //FillFormEdit(txtRJLayananId.Text); FillFormEdit(lblRJLayananId.Text); lblTitleEditForm.Text = Resources.GetString("RS", "TitleKasirEditFIS"); ModeEditForm(); } protected void GV_RowDeleting(object sender, GridViewDeleteEventArgs e) { int i = e.RowIndex; DeleteData(GV.DataKeys[i].Value.ToString()); } protected void btnAdd_Click(object sender, EventArgs e) { lblTitleEditForm.Text = Resources.GetString("RS", "TitleKasirAddFIS"); ModeEditForm(); EmptyFormEdit(); } protected void btnCancel_Click(object sender, EventArgs e) { ModeListForm(); } protected void btnSave_Click(object sender, EventArgs e) { SaveData(); } protected void btnBack_Click(object sender, EventArgs e) { ModeListForm(); } protected void btnDeleteDetil_Click(object sender, EventArgs e) { DeleteData(lblRJLayananId.Text); } public void BindDataGrid() { DataView dv = GetData(); dv.Sort = GV.Attributes["SortField"]; if (GV.Attributes["SortAscending"] == "no") dv.Sort += " DESC"; if (dv.Count > 0) { int intRowCount = dv.Count; int intPageSaze = GV.PageSize; int intPageCount = intRowCount / intPageSaze; if (intRowCount - (intPageCount * intPageSaze) > 0) intPageCount = intPageCount + 1; if (GV.PageIndex >= intPageCount) GV.PageIndex = intPageCount - 1; TotalTagihan = 0; bool statusbayar = true; bool statusBelumBayar = false; foreach (DataRow dr in dv.Table.Rows) { statusBelumBayar = dr["StatusBayar"].ToString() == "0" ? true : false; if (statusBelumBayar) statusbayar = false; TotalTagihan += (decimal)dr["JumlahTagihan"]; } if (!statusbayar) { btnKuitansi.Visible = true; btnKuitansi.Attributes.Remove("onclick"); btnKuitansi.Attributes.Add("onclick", "displayPopup_scroll(2,'PrintKuitansiRJ.aspx?RawatJalanId=" + txtRawatJalanId.Text + "','Pasien',600,800,(version4 ? event : null));"); } else { btnKuitansi.Visible = false; } } else { btnKuitansi.Visible = false; GV.PageIndex = 0; } NoKe = GV.PageSize * GV.PageIndex; GV.DataSource = dv; GV.DataBind(); ModeListForm(); } //=================================================================== // POLULATE DATA REFERENSI //=================================================================== private void SelectJenisLayanan(string JenisLayananId) { if (cmbJenisLayanan.Items.Count > 0) { cmbJenisLayanan.SelectedIndex = 0; for (int i = 0; i < cmbJenisLayanan.Items.Count; i++) { if (cmbJenisLayanan.Items[i].Value == JenisLayananId) { cmbJenisLayanan.SelectedIndex = i; break; } } } else { PopulateJenisLayanan(JenisLayananId); } } private void PopulateJenisLayanan(string JenisLayananId) { SIMRS.DataAccess.RS_JenisLayanan myObj = new SIMRS.DataAccess.RS_JenisLayanan(); DataTable dt = myObj.GetList(); cmbJenisLayanan.Items.Clear(); int i = 0; if (dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) { if (dr["Id"].ToString() != "2") { cmbJenisLayanan.Items.Add(""); cmbJenisLayanan.Items[i].Text = dr["Nama"].ToString(); cmbJenisLayanan.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == JenisLayananId) cmbJenisLayanan.SelectedIndex = i; i++; } } if (JenisLayananId == "") cmbJenisLayanan.SelectedIndex = 0; } } private void SelectKelompokLayanan(string KelompokLayananId) { if (cmbKelompokLayanan.Items.Count > 0) { cmbKelompokLayanan.SelectedIndex = -1; for (int i = 0; i < cmbKelompokLayanan.Items.Count; i++) { if (cmbKelompokLayanan.Items[i].Value == KelompokLayananId) { cmbKelompokLayanan.SelectedIndex = i; break; } } } else { PopulateKelompokLayanan(KelompokLayananId); } } private void PopulateKelompokLayanan(string KelompokLayananId) { SIMRS.DataAccess.RS_KelompokLayanan myObj = new SIMRS.DataAccess.RS_KelompokLayanan(); DataTable dt = myObj.GetList(); cmbKelompokLayanan.Items.Clear(); int i = 0; cmbKelompokLayanan.Items.Add(""); cmbKelompokLayanan.Items[i].Text = ""; cmbKelompokLayanan.Items[i].Value = ""; i++; if (dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) { cmbKelompokLayanan.Items.Add(""); cmbKelompokLayanan.Items[i].Text = dr["Nama"].ToString(); cmbKelompokLayanan.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == KelompokLayananId) cmbKelompokLayanan.SelectedIndex = i; i++; } } } private void SelectLayanan(string LayananId) { SIMRS.DataAccess.RS_Layanan myObj = new SIMRS.DataAccess.RS_Layanan(); myObj.JenisLayananId = int.Parse(cmbJenisLayanan.SelectedItem.Value); if (cmbKelompokLayanan.SelectedIndex > 0 ) myObj.KelompokLayananId = int.Parse(cmbKelompokLayanan.SelectedItem.Value); myObj.PoliklinikId = int.Parse(txtPolilinikId.Text); DataTable dt = myObj.GetListFilterRJ(); cmbLayanan.Items.Clear(); int i = 0; cmbLayanan.Items.Add(""); cmbLayanan.Items[i].Text = ""; cmbLayanan.Items[i].Value = ""; cmbLayanan.SelectedIndex = -1; pnlLayananLain.Visible = false; i++; if (dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) { cmbLayanan.Items.Add(""); cmbLayanan.Items[i].Text = dr["Nama"].ToString(); cmbLayanan.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == LayananId) { cmbLayanan.SelectedIndex = i; } i++; } } cmbLayanan.Items.Add(""); cmbLayanan.Items[i].Text = "Lainnya"; cmbLayanan.Items[i].Value = "-1"; if (LayananId == "") { cmbLayanan.SelectedIndex = i; pnlLayananLain.Visible = true; } } //=================================================================== public void SetDataRawatJalan(string RawatJalanId, string PolilinikId) { txtRawatJalanId.Text = RawatJalanId; txtPolilinikId.Text = PolilinikId; } public DataView GetData() { SIMRS.DataAccess.RS_RJLayanan objData = new SIMRS.DataAccess.RS_RJLayanan(); objData.RawatJalanId = Int64.Parse(txtRawatJalanId.Text); DataTable dt = objData.SelectAllWRawatJalanIdLogic(); return dt.DefaultView; } private void EmptyFormEdit() { txtRJLayananId.Text = "0"; SelectJenisLayanan(""); SelectKelompokLayanan(""); SelectLayanan("-1"); txtTarif.Text = "0"; txtJumlahSatuan.Text = "1"; txtDiscount.Text = "0"; txtBiayaTambahan.Text = "0"; txtJumlahTagihan.Text = "0"; txtKeterangan.Text = ""; } private void FillFormEdit(string RJLayananId) { SIMRS.DataAccess.RS_RJLayanan myObj = new SIMRS.DataAccess.RS_RJLayanan(); myObj.RJLayananId = Int64.Parse(RJLayananId); DataTable dt = myObj.SelectOne(); if (dt.Rows.Count > 0) { DataRow dr = dt.Rows[0]; txtRJLayananId.Text = dr["RJLayananId"].ToString(); SelectJenisLayanan(dr["JenisLayananId"].ToString()); SelectKelompokLayanan(dr["KelompokLayananId"].ToString()); SelectLayanan(dr["LayananId"].ToString()); txtNamaLayanan.Text = dr["NamaLayanan"].ToString(); txtTarif.Text = dr["Tarif"].ToString() != "" ? ((Decimal)dr["Tarif"]).ToString("#,###.###.###.###") : ""; txtJumlahSatuan.Text = dr["JumlahSatuan"].ToString(); txtDiscount.Text = dr["Discount"].ToString(); txtBiayaTambahan.Text = dr["BiayaTambahan"].ToString(); txtJumlahTagihan.Text = dr["JumlahTagihan"].ToString() != "" ? ((Decimal)dr["JumlahTagihan"]).ToString("#,###.###.###.###") : ""; txtKeterangan.Text = dr["Keterangan"].ToString(); } } private void FillFormView(string RJLayananId) { SIMRS.DataAccess.RS_RJLayanan myObj = new SIMRS.DataAccess.RS_RJLayanan(); myObj.RJLayananId = Int64.Parse(RJLayananId); DataTable dt = myObj.SelectOne(); if (dt.Rows.Count > 0) { DataRow dr = dt.Rows[0]; lblRJLayananId.Text = dr["RJLayananId"].ToString(); lblKelompokLayanan.Text = dr["KelompokLayananNama"].ToString(); lblNamaLayanan.Text = dr["NamaLayanan"].ToString(); lblTarif.Text = dr["Tarif"].ToString() != "" ? ((Decimal)dr["Tarif"]).ToString("#,###.###.###.###") : ""; lblJumlahSatuan.Text = dr["JumlahSatuan"].ToString(); lblDiscount.Text = dr["Discount"].ToString(); lblBiayaTambahan.Text = dr["BiayaTambahan"].ToString(); lblJumlahTagihan.Text = dr["JumlahTagihan"].ToString() != "" ? ((Decimal)dr["JumlahTagihan"]).ToString("#,###.###.###.###") : ""; lblKeterangan.Text = dr["Keterangan"].ToString().Replace("\r\n","<br />"); } } private void SaveData() { if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } if (!Page.IsValid) { return; } int UserId = (int)Session["SIMRS.UserId"]; SIMRS.DataAccess.RS_RJLayanan myObj = new SIMRS.DataAccess.RS_RJLayanan(); myObj.RJLayananId = Int64.Parse(txtRJLayananId.Text); if (myObj.RJLayananId > 0) myObj.SelectOne(); myObj.RawatJalanId = Int64.Parse(txtRawatJalanId.Text); myObj.JenisLayananId = int.Parse(cmbJenisLayanan.SelectedItem.Value); if (cmbKelompokLayanan.SelectedIndex > 0) myObj.KelompokLayananId = int.Parse(cmbKelompokLayanan.SelectedItem.Value); else myObj.KelompokLayananId = SqlInt32.Null; if (cmbLayanan.SelectedIndex > 0 && cmbLayanan.SelectedItem.Value != "-1") myObj.LayananId = int.Parse(cmbLayanan.SelectedItem.Value); else myObj.LayananId = SqlInt32.Null; myObj.NamaLayanan = txtNamaLayanan.Text; if(txtTarif.Text != "") myObj.Tarif = decimal.Parse(txtTarif.Text); if (txtJumlahSatuan.Text != "") myObj.JumlahSatuan = double.Parse(txtJumlahSatuan.Text); if (txtDiscount.Text != "") myObj.Discount = double.Parse(txtDiscount.Text); if (txtBiayaTambahan.Text != "") myObj.BiayaTambahan = double.Parse(txtBiayaTambahan.Text); if (txtJumlahTagihan.Text != "") myObj.JumlahTagihan = decimal.Parse(txtJumlahTagihan.Text); myObj.Keterangan = txtKeterangan.Text; if (myObj.RJLayananId == 0) { //Kondisi Insert Data myObj.CreatedBy = UserId; myObj.CreatedDate = DateTime.Now; myObj.Insert(); lblWarning.Text = Resources.GetString("", "WarSuccessSave"); } else { //Kondisi Update Data myObj.ModifiedBy = UserId; myObj.ModifiedDate = DateTime.Now; myObj.Update(); lblWarning.Text = Resources.GetString("", "WarSuccessSave"); } BindDataGrid(); ModeListForm(); } private void DeleteData(string RJLayananId) { SIMRS.DataAccess.RS_RJLayanan myObj = new SIMRS.DataAccess.RS_RJLayanan(); myObj.RJLayananId = int.Parse(RJLayananId); myObj.SelectOne(); /* if (myObj.StatusBayar == 0) { */ try { myObj.Delete(); GV.SelectedIndex = -1; BindDataGrid(); lblWarning.Text = Resources.GetString("", "WarSuccessDelete"); ModeListForm(); } catch { lblWarning.Text = Resources.GetString("", "WarAlreadyUsed"); } /* } else { lblWarning.Text = Resources.GetString("", "WarAlreadyUsed"); } */ } private void GetTarif() { SIMRS.DataAccess.RS_Layanan myObj = new SIMRS.DataAccess.RS_Layanan(); if (cmbLayanan.SelectedIndex > 0) myObj.Id = int.Parse(cmbLayanan.SelectedItem.Value); DataTable dt = myObj.GetTarifRJByLayananId(); if (dt.Rows.Count > 0) { DataRow dr = dt.Rows[0]; txtTarif.Text = dr["Tarif"].ToString() != "" ? ((Decimal)dr["Tarif"]).ToString("#,###.###.###.###") : "0"; HitungJumlahTagihan(); } else { txtTarif.Text = "0"; } } protected void cmbLayanan_SelectedIndexChanged(object sender, EventArgs e) { GetTarif(); if (cmbLayanan.SelectedIndex == cmbLayanan.Items.Count - 1) { pnlLayananLain.Visible = true; txtNamaLayanan.Text = ""; } else { pnlLayananLain.Visible = false; txtNamaLayanan.Text = cmbLayanan.SelectedItem.Text; } } protected void cmbKelompokLayanan_SelectedIndexChanged(object sender, EventArgs e) { SelectLayanan("-1"); GetTarif(); } private void HitungJumlahTagihan() { decimal jumlahTagihan = 0; ; decimal discount = 0; decimal biayaTambahan = 0; if (txtJumlahSatuan.Text != "") jumlahTagihan = decimal.Parse(txtJumlahSatuan.Text) * decimal.Parse(txtTarif.Text); if (txtDiscount.Text != "") discount = jumlahTagihan * decimal.Parse(txtDiscount.Text)/100; if (txtBiayaTambahan.Text != "") biayaTambahan = jumlahTagihan * decimal.Parse(txtBiayaTambahan.Text)/100; jumlahTagihan = jumlahTagihan + biayaTambahan - discount; if (jumlahTagihan > 0) txtJumlahTagihan.Text = jumlahTagihan.ToString("#,###.###.###.###"); else txtJumlahTagihan.Text = "0"; } protected void txtTarif_TextChanged(object sender, EventArgs e) { if (REVTarif.IsValid && txtTarif.Text != "") { if (txtTarif.Text != "0") txtTarif.Text = (decimal.Parse(txtTarif.Text)).ToString("#,###.###.###.###"); HitungJumlahTagihan(); } } protected void txtJumlahSatuan_TextChanged(object sender, EventArgs e) { if (REVJumlahSatuan.IsValid && txtJumlahSatuan.Text != "") { if (txtJumlahSatuan.Text != "0") txtJumlahSatuan.Text = (decimal.Parse(txtJumlahSatuan.Text)).ToString("#,###.###.###.###"); HitungJumlahTagihan(); } } protected void txtDiscount_TextChanged(object sender, EventArgs e) { if (REVDiscount.IsValid && txtDiscount.Text != "") { if(txtDiscount.Text != "0") txtDiscount.Text = (decimal.Parse(txtDiscount.Text)).ToString("#,###.###.###.###"); HitungJumlahTagihan(); } } protected void txtBiayaTambahan_TextChanged(object sender, EventArgs e) { if (REVBiayaTambahan.IsValid && txtBiayaTambahan.Text != "") { if (txtBiayaTambahan.Text != "0") txtBiayaTambahan.Text = (decimal.Parse(txtBiayaTambahan.Text)).ToString("#,###.###.###.###"); HitungJumlahTagihan(); } } protected void cbxAll_CheckedChanged(object sender, EventArgs e) { CheckBox cbAll = (CheckBox)GV.HeaderRow.FindControl("cbxAll"); bool ceck = cbAll.Checked; for (int i = 0; i < GV.Rows.Count; i++) { ((CheckBox)GV.Rows[i].FindControl("cbxRJLayananId")).Checked = ceck; } } protected void cbxRJLayananId_CheckedChanged(object sender, EventArgs e) { decimal total = 0; for (int i = 0; i < GV.Rows.Count; i++) { if (((CheckBox)GV.Rows[i].FindControl("cbxRJLayananId")).Checked == true) { total += decimal.Parse(((Label)GV.Rows[i].FindControl("lblgTarif")).Text); } } TotalTagihan = total; } protected void cmbJenisLayanan_SelectedIndexChanged(object sender, EventArgs e) { SelectLayanan("-1"); GetTarif(); } }
// 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. // This provider is only available on an Android device. #if UNITY_ANDROID && !UNITY_EDITOR using UnityEngine; using System; using System.Runtime.InteropServices; /// @cond namespace Gvr.Internal { /// Controller Provider that uses the native GVR C API to communicate with controllers /// via Google VR Services on Android. class AndroidNativeControllerProvider : IControllerProvider { // Note: keep structs and function signatures in sync with the C header file (gvr_controller.h). // GVR controller option flags. private const int GVR_CONTROLLER_ENABLE_ORIENTATION = 1 << 0; private const int GVR_CONTROLLER_ENABLE_TOUCH = 1 << 1; private const int GVR_CONTROLLER_ENABLE_GYRO = 1 << 2; private const int GVR_CONTROLLER_ENABLE_ACCEL = 1 << 3; private const int GVR_CONTROLLER_ENABLE_GESTURES = 1 << 4; private const int GVR_CONTROLLER_ENABLE_POSE_PREDICTION = 1 << 5; // enum gvr_controller_button: private const int GVR_CONTROLLER_BUTTON_NONE = 0; private const int GVR_CONTROLLER_BUTTON_CLICK = 1; private const int GVR_CONTROLLER_BUTTON_HOME = 2; private const int GVR_CONTROLLER_BUTTON_APP = 3; private const int GVR_CONTROLLER_BUTTON_VOLUME_UP = 4; private const int GVR_CONTROLLER_BUTTON_VOLUME_DOWN = 5; private const int GVR_CONTROLLER_BUTTON_COUNT = 6; // enum gvr_controller_connection_state: private const int GVR_CONTROLLER_DISCONNECTED = 0; private const int GVR_CONTROLLER_SCANNING = 1; private const int GVR_CONTROLLER_CONNECTING = 2; private const int GVR_CONTROLLER_CONNECTED = 3; // enum gvr_controller_api_status private const int GVR_CONTROLLER_API_OK = 0; private const int GVR_CONTROLLER_API_UNSUPPORTED = 1; private const int GVR_CONTROLLER_API_NOT_AUTHORIZED = 2; private const int GVR_CONTROLLER_API_UNAVAILABLE = 3; private const int GVR_CONTROLLER_API_SERVICE_OBSOLETE = 4; private const int GVR_CONTROLLER_API_CLIENT_OBSOLETE = 5; private const int GVR_CONTROLLER_API_MALFUNCTION = 6; [StructLayout(LayoutKind.Sequential)] private struct gvr_quat { internal float x; internal float y; internal float z; internal float w; } [StructLayout(LayoutKind.Sequential)] private struct gvr_vec3 { internal float x; internal float y; internal float z; } [StructLayout(LayoutKind.Sequential)] private struct gvr_vec2 { internal float x; internal float y; } private const string dllName = GvrActivityHelper.GVR_DLL_NAME; [DllImport(dllName)] private static extern int gvr_controller_get_default_options(); [DllImport(dllName)] private static extern IntPtr gvr_controller_create_and_init_android( IntPtr jniEnv, IntPtr androidContext, IntPtr classLoader, int options, IntPtr context); [DllImport(dllName)] private static extern void gvr_controller_destroy(ref IntPtr api); [DllImport(dllName)] private static extern void gvr_controller_pause(IntPtr api); [DllImport(dllName)] private static extern void gvr_controller_resume(IntPtr api); [DllImport(dllName)] private static extern IntPtr gvr_controller_state_create(); [DllImport(dllName)] private static extern void gvr_controller_state_destroy(ref IntPtr state); [DllImport(dllName)] private static extern void gvr_controller_state_update(IntPtr api, int flags, IntPtr out_state); [DllImport(dllName)] private static extern int gvr_controller_state_get_api_status(IntPtr state); [DllImport(dllName)] private static extern int gvr_controller_state_get_connection_state(IntPtr state); [DllImport(dllName)] private static extern gvr_quat gvr_controller_state_get_orientation(IntPtr state); [DllImport(dllName)] private static extern gvr_vec3 gvr_controller_state_get_gyro(IntPtr state); [DllImport(dllName)] private static extern gvr_vec3 gvr_controller_state_get_accel(IntPtr state); [DllImport(dllName)] private static extern byte gvr_controller_state_is_touching(IntPtr state); [DllImport(dllName)] private static extern gvr_vec2 gvr_controller_state_get_touch_pos(IntPtr state); [DllImport(dllName)] private static extern byte gvr_controller_state_get_touch_down(IntPtr state); [DllImport(dllName)] private static extern byte gvr_controller_state_get_touch_up(IntPtr state); [DllImport(dllName)] private static extern byte gvr_controller_state_get_recentered(IntPtr state); [DllImport(dllName)] private static extern byte gvr_controller_state_get_recentering(IntPtr state); [DllImport(dllName)] private static extern byte gvr_controller_state_get_button_state(IntPtr state, int button); [DllImport(dllName)] private static extern byte gvr_controller_state_get_button_down(IntPtr state, int button); [DllImport(dllName)] private static extern byte gvr_controller_state_get_button_up(IntPtr state, int button); [DllImport(dllName)] private static extern long gvr_controller_state_get_last_orientation_timestamp(IntPtr state); [DllImport(dllName)] private static extern long gvr_controller_state_get_last_gyro_timestamp(IntPtr state); [DllImport(dllName)] private static extern long gvr_controller_state_get_last_accel_timestamp(IntPtr state); [DllImport(dllName)] private static extern long gvr_controller_state_get_last_touch_timestamp(IntPtr state); [DllImport(dllName)] private static extern long gvr_controller_state_get_last_button_timestamp(IntPtr state); [DllImport(dllName)] private static extern byte gvr_controller_state_get_battery_charging(IntPtr state); [DllImport(dllName)] private static extern int gvr_controller_state_get_battery_level(IntPtr state); [DllImport(dllName)] private static extern long gvr_controller_state_get_last_battery_timestamp(IntPtr state); private const string VRCORE_UTILS_CLASS = "com.google.vr.vrcore.base.api.VrCoreUtils"; private IntPtr api; private bool hasBatteryMethods = false; private AndroidJavaObject androidContext; private AndroidJavaObject classLoader; private bool error = false; private string errorDetails = string.Empty; private IntPtr statePtr; private MutablePose3D pose3d = new MutablePose3D(); public bool SupportsBatteryStatus { get { return hasBatteryMethods; } } internal AndroidNativeControllerProvider() { #if !UNITY_EDITOR Debug.Log("Initializing Daydream controller API."); int options = gvr_controller_get_default_options(); options |= GVR_CONTROLLER_ENABLE_ACCEL; options |= GVR_CONTROLLER_ENABLE_GYRO; statePtr = gvr_controller_state_create(); // Get a hold of the activity, context and class loader. AndroidJavaObject activity = GvrActivityHelper.GetActivity(); if (activity == null) { error = true; errorDetails = "Failed to get Activity from Unity Player."; return; } androidContext = GvrActivityHelper.GetApplicationContext(activity); if (androidContext == null) { error = true; errorDetails = "Failed to get Android application context from Activity."; return; } classLoader = GetClassLoaderFromActivity(activity); if (classLoader == null) { error = true; errorDetails = "Failed to get class loader from Activity."; return; } // Use IntPtr instead of GetRawObject() so that Unity can shut down gracefully on // Application.Quit(). Note that GetRawObject() is not pinned by the receiver so it's not // cleaned up appropriately on shutdown, which is a known bug in Unity. IntPtr androidContextPtr = AndroidJNI.NewLocalRef(androidContext.GetRawObject()); IntPtr classLoaderPtr = AndroidJNI.NewLocalRef(classLoader.GetRawObject()); Debug.Log ("Creating and initializing GVR API controller object."); api = gvr_controller_create_and_init_android (IntPtr.Zero, androidContextPtr, classLoaderPtr, options, IntPtr.Zero); AndroidJNI.DeleteLocalRef(androidContextPtr); AndroidJNI.DeleteLocalRef(classLoaderPtr); if (IntPtr.Zero == api) { Debug.LogError("Error creating/initializing Daydream controller API."); error = true; errorDetails = "Failed to initialize Daydream controller API."; return; } try { gvr_controller_state_get_battery_charging(statePtr); gvr_controller_state_get_battery_level(statePtr); hasBatteryMethods = true; } catch (EntryPointNotFoundException) { // Older VrCore version. Does not support battery indicator. // Note that controller API is not dynamically loaded as of June 2017 (b/35662043), // so we'll need to support this case indefinitely... } Debug.Log("GVR API successfully initialized. Now resuming it."); gvr_controller_resume(api); Debug.Log("GVR API resumed."); #endif } ~AndroidNativeControllerProvider() { Debug.Log("Destroying GVR API structures."); gvr_controller_state_destroy(ref statePtr); gvr_controller_destroy(ref api); Debug.Log("AndroidNativeControllerProvider destroyed."); } public void ReadState(ControllerState outState) { if (error) { outState.connectionState = GvrConnectionState.Error; outState.apiStatus = GvrControllerApiStatus.Error; outState.errorDetails = errorDetails; return; } gvr_controller_state_update(api, 0, statePtr); outState.connectionState = ConvertConnectionState( gvr_controller_state_get_connection_state(statePtr)); outState.apiStatus = ConvertControllerApiStatus( gvr_controller_state_get_api_status(statePtr)); gvr_quat rawOri = gvr_controller_state_get_orientation(statePtr); gvr_vec3 rawAccel = gvr_controller_state_get_accel(statePtr); gvr_vec3 rawGyro = gvr_controller_state_get_gyro(statePtr); // Convert GVR API orientation (right-handed) into Unity axis system (left-handed). pose3d.Set(Vector3.zero, new Quaternion(rawOri.x, rawOri.y, rawOri.z, rawOri.w)); pose3d.SetRightHanded(pose3d.Matrix); outState.orientation = pose3d.Orientation; // For accelerometer, we have to flip Z because the GVR API has Z pointing backwards // and Unity has Z pointing forward. outState.accel = new Vector3(rawAccel.x, rawAccel.y, -rawAccel.z); // Gyro in GVR represents a right-handed angular velocity about each axis (positive means // clockwise when sighting along axis). Since Unity uses a left-handed system, we flip the // signs to adjust the sign of the rotational velocity (so that positive means // counter-clockwise). In addition, since in Unity the Z axis points forward while GVR // has Z pointing backwards, we flip the Z axis sign again. So the result is that // we should use -X, -Y, +Z: outState.gyro = new Vector3(-rawGyro.x, -rawGyro.y, rawGyro.z); outState.isTouching = 0 != gvr_controller_state_is_touching(statePtr); gvr_vec2 touchPos = gvr_controller_state_get_touch_pos(statePtr); outState.touchPos = new Vector2(touchPos.x, touchPos.y); outState.touchDown = 0 != gvr_controller_state_get_touch_down(statePtr); outState.touchUp = 0 != gvr_controller_state_get_touch_up(statePtr); outState.appButtonDown = 0 != gvr_controller_state_get_button_down(statePtr, GVR_CONTROLLER_BUTTON_APP); outState.appButtonState = 0 != gvr_controller_state_get_button_state(statePtr, GVR_CONTROLLER_BUTTON_APP); outState.appButtonUp = 0 != gvr_controller_state_get_button_up(statePtr, GVR_CONTROLLER_BUTTON_APP); outState.homeButtonDown = 0 != gvr_controller_state_get_button_down(statePtr, GVR_CONTROLLER_BUTTON_HOME); outState.homeButtonState = 0 != gvr_controller_state_get_button_state(statePtr, GVR_CONTROLLER_BUTTON_HOME); outState.clickButtonDown = 0 != gvr_controller_state_get_button_down(statePtr, GVR_CONTROLLER_BUTTON_CLICK); outState.clickButtonState = 0 != gvr_controller_state_get_button_state(statePtr, GVR_CONTROLLER_BUTTON_CLICK); outState.clickButtonUp = 0 != gvr_controller_state_get_button_up(statePtr, GVR_CONTROLLER_BUTTON_CLICK); outState.recentering = 0 != gvr_controller_state_get_recentering(statePtr); outState.recentered = 0 != gvr_controller_state_get_recentered(statePtr); outState.gvrPtr = statePtr; if (hasBatteryMethods) { outState.isCharging = 0 != gvr_controller_state_get_battery_charging(statePtr); outState.batteryLevel = (GvrControllerBatteryLevel)gvr_controller_state_get_battery_level(statePtr); } } public void OnPause() { if (IntPtr.Zero != api) { gvr_controller_pause(api); } } public void OnResume() { if (IntPtr.Zero != api) { gvr_controller_resume(api); } } private GvrConnectionState ConvertConnectionState(int connectionState) { switch (connectionState) { case GVR_CONTROLLER_CONNECTED: return GvrConnectionState.Connected; case GVR_CONTROLLER_CONNECTING: return GvrConnectionState.Connecting; case GVR_CONTROLLER_SCANNING: return GvrConnectionState.Scanning; default: return GvrConnectionState.Disconnected; } } private GvrControllerApiStatus ConvertControllerApiStatus(int gvrControllerApiStatus) { switch (gvrControllerApiStatus) { case GVR_CONTROLLER_API_OK: return GvrControllerApiStatus.Ok; case GVR_CONTROLLER_API_UNSUPPORTED: return GvrControllerApiStatus.Unsupported; case GVR_CONTROLLER_API_NOT_AUTHORIZED: return GvrControllerApiStatus.NotAuthorized; case GVR_CONTROLLER_API_SERVICE_OBSOLETE: return GvrControllerApiStatus.ApiServiceObsolete; case GVR_CONTROLLER_API_CLIENT_OBSOLETE: return GvrControllerApiStatus.ApiClientObsolete; case GVR_CONTROLLER_API_MALFUNCTION: return GvrControllerApiStatus.ApiMalfunction; case GVR_CONTROLLER_API_UNAVAILABLE: default: // Fall through. return GvrControllerApiStatus.Unavailable; } } private static AndroidJavaObject GetClassLoaderFromActivity(AndroidJavaObject activity) { AndroidJavaObject result = activity.Call<AndroidJavaObject>("getClassLoader"); if (result == null) { Debug.LogErrorFormat("Failed to get class loader from Activity."); return null; } return result; } private static int GetVrCoreClientApiVersion(AndroidJavaObject activity) { try { AndroidJavaClass utilsClass = new AndroidJavaClass(VRCORE_UTILS_CLASS); int apiVersion = utilsClass.CallStatic<int>("getVrCoreClientApiVersion", activity); Debug.LogFormat("VrCore client API version: " + apiVersion); return apiVersion; } catch (Exception exc) { // Even though a catch-all block is normally frowned upon, in this case we really // need it because this method has to be robust to unpredictable circumstances: // VrCore might not exist in the device, the Java layer might be broken, etc, etc. // None of those should abort the app. Debug.LogError("Error obtaining VrCore client API version: " + exc); return 0; } } } } /// @endcond #endif // UNITY_ANDROID && !UNITY_EDITOR
using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using Spectre.Cli.Internal.Configuration; namespace Spectre.Cli.Internal.Modelling { internal static class CommandModelBuilder { // Consider removing this in favor for value tuples at some point. private sealed class OrderedProperties { public int Level { get; } public int SortOrder { get; } public PropertyInfo[] Properties { get; } public OrderedProperties(int level, int sortOrder, PropertyInfo[] properties) { Level = level; SortOrder = sortOrder; Properties = properties; } } public static CommandModel Build(IConfiguration configuration) { var result = new List<CommandInfo>(); foreach (var command in configuration.Commands) { result.Add(Build(null, command)); } var defaultCommand = default(CommandInfo); if (configuration.DefaultCommand != null) { // Add the examples from the configuration to the default command. configuration.DefaultCommand.Examples.AddRange(configuration.Examples); // Build the default command. defaultCommand = Build(null, configuration.DefaultCommand); } // Create the command model and validate it. var model = new CommandModel(configuration.Settings, defaultCommand, result, configuration.Examples); CommandModelValidator.Validate(model, configuration.Settings); return model; } private static CommandInfo Build(CommandInfo parent, ConfiguredCommand command) { var info = new CommandInfo(parent, command); foreach (var parameter in GetParameters(info)) { info.Parameters.Add(parameter); } foreach (var childCommand in command.Children) { var child = Build(info, childCommand); info.Children.Add(child); } // Normalize argument positions. var index = 0; foreach (var argument in info.Parameters.OfType<CommandArgument>() .OrderBy(argument => argument.Position)) { argument.Position = index; index++; } return info; } private static IEnumerable<CommandParameter> GetParameters(CommandInfo command) { var result = new List<CommandParameter>(); var argumentPosition = 0; // We need to get parameters in order of the class where they were defined. // We assign each inheritance level a value that is used to properly sort the // arguments when iterating over them. IEnumerable<OrderedProperties> GetPropertiesInOrder() { var current = command.SettingsType; var level = 0; var sortOrder = 0; while (current.BaseType != null) { yield return new OrderedProperties(level, sortOrder, current.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)); current = current.BaseType; // Things get a little bit complicated now. // Only consider a setting's base type part of the // setting, if there isn't a parent command that implements // the setting's base type. This might come back to bite us :) var currentCommand = command.Parent; while (currentCommand != null) { if (currentCommand.SettingsType == current) { level--; break; } currentCommand = currentCommand.Parent; } sortOrder--; } } var groups = GetPropertiesInOrder(); foreach (var group in groups.OrderBy(x => x.Level).ThenBy(x => x.SortOrder)) { var parameters = new List<CommandParameter>(); foreach (var property in group.Properties) { if (property.IsDefined(typeof(CommandOptionAttribute))) { var attribute = property.GetCustomAttribute<CommandOptionAttribute>(); if (attribute != null) { var option = BuildOptionParameter(property, attribute); // Any previous command has this option defined? if (command.HaveParentWithOption(option)) { // Do we allow it to exist on this command as well? if (command.AllowParentOption(option)) { option.Required = false; option.IsShadowed = true; parameters.Add(option); } } else { // No parent have this option. parameters.Add(option); } } } else if (property.IsDefined(typeof(CommandArgumentAttribute))) { var attribute = property.GetCustomAttribute<CommandArgumentAttribute>(); if (attribute != null) { var argument = BuildArgumentParameter(property, attribute); // Any previous command has this argument defined? // In that case, we should not assign the parameter to this command. if (!command.HaveParentWithArgument(argument)) { parameters.Add(argument); } } } } // Update the position for the parameters. foreach (var argument in parameters.OfType<CommandArgument>().OrderBy(x => x.Position)) { argument.Position = argumentPosition++; } // Add all parameters to the result. foreach (var groupResult in parameters) { result.Add(groupResult); } } return result; } private static CommandOption BuildOptionParameter(PropertyInfo property, CommandOptionAttribute attribute) { var description = property.GetCustomAttribute<DescriptionAttribute>(); var converter = property.GetCustomAttribute<TypeConverterAttribute>(); var validators = property.GetCustomAttributes<ParameterValidationAttribute>(true); var defaultValue = property.GetCustomAttribute<DefaultValueAttribute>(); var kind = property.PropertyType == typeof(bool) ? ParameterKind.Flag : ParameterKind.Single; if (defaultValue == null && property.PropertyType == typeof(bool)) { defaultValue = new DefaultValueAttribute(false); } return new CommandOption(property.PropertyType, kind, property, description?.Description, converter, attribute, validators, defaultValue); } private static CommandArgument BuildArgumentParameter(PropertyInfo property, CommandArgumentAttribute attribute) { var description = property.GetCustomAttribute<DescriptionAttribute>(); var converter = property.GetCustomAttribute<TypeConverterAttribute>(); var validators = property.GetCustomAttributes<ParameterValidationAttribute>(true); var kind = property.PropertyType == typeof(bool) ? ParameterKind.Flag : ParameterKind.Single; return new CommandArgument(property.PropertyType, kind, property, description?.Description, converter, attribute, validators); } } }
// *********************************************************************** // Copyright (c) 2012 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.Threading; using System.Reflection; using NUnit.Framework.Compatibility; using NUnit.Framework.Internal.Commands; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal.Execution { /// <summary> /// A CompositeWorkItem represents a test suite and /// encapsulates the execution of the suite as well /// as all its child tests. /// </summary> public class CompositeWorkItem : WorkItem { // static Logger log = InternalTrace.GetLogger("CompositeWorkItem"); private TestSuite _suite; private ITestFilter _childFilter; private TestCommand _setupCommand; private TestCommand _teardownCommand; private List<WorkItem> _children; private CountdownEvent _childTestCountdown; /// <summary> /// Construct a CompositeWorkItem for executing a test suite /// using a filter to select child tests. /// </summary> /// <param name="suite">The TestSuite to be executed</param> /// <param name="childFilter">A filter used to select child tests</param> public CompositeWorkItem(TestSuite suite, ITestFilter childFilter) : base(suite) { _suite = suite; _childFilter = childFilter; } /// <summary> /// Method that actually performs the work. Overridden /// in CompositeWorkItem to do setup, run all child /// items and then do teardown. /// </summary> protected override void PerformWork() { // Inititialize actions, setup and teardown // We can't do this in the constructor because // the context is not available at that point. InitializeSetUpAndTearDownCommands(); if (!CheckForCancellation()) if (Test.RunState == RunState.Explicit && !_childFilter.IsExplicitMatch(Test)) SkipFixture(ResultState.Explicit, GetSkipReason(), null); else switch (Test.RunState) { default: case RunState.Runnable: case RunState.Explicit: // Assume success, since the result will be inconclusive // if there is no setup method to run or if the // context initialization fails. Result.SetResult(ResultState.Success); CreateChildWorkItems(); if (_children.Count > 0) { PerformOneTimeSetUp(); if (!CheckForCancellation()) switch (Result.ResultState.Status) { case TestStatus.Passed: RunChildren(); return; // Just return: completion event will take care // of TestFixtureTearDown when all tests are done. case TestStatus.Skipped: case TestStatus.Inconclusive: case TestStatus.Failed: SkipChildren(_suite, Result.ResultState.WithSite(FailureSite.Parent), "OneTimeSetUp: " + Result.Message); break; } // Directly execute the OneTimeFixtureTearDown for tests that // were skipped, failed or set to inconclusive in one time setup // unless we are aborting. if (Context.ExecutionStatus != TestExecutionStatus.AbortRequested) PerformOneTimeTearDown(); } break; case RunState.Skipped: SkipFixture(ResultState.Skipped, GetSkipReason(), null); break; case RunState.Ignored: SkipFixture(ResultState.Ignored, GetSkipReason(), null); break; case RunState.NotRunnable: SkipFixture(ResultState.NotRunnable, GetSkipReason(), GetProviderStackTrace()); break; } // Fall through in case nothing was run. // Otherwise, this is done in the completion event. WorkItemComplete(); } #region Helper Methods private bool CheckForCancellation() { if (Context.ExecutionStatus != TestExecutionStatus.Running) { Result.SetResult(ResultState.Cancelled, "Test cancelled by user"); return true; } return false; } private void InitializeSetUpAndTearDownCommands() { List<SetUpTearDownItem> setUpTearDownItems = _suite.TypeInfo != null ? CommandBuilder.BuildSetUpTearDownList(_suite.TypeInfo.Type, typeof(OneTimeSetUpAttribute), typeof(OneTimeTearDownAttribute)) : new List<SetUpTearDownItem>(); var actionItems = new List<TestActionItem>(); foreach (ITestAction action in Actions) { // Special handling here for ParameterizedMethodSuite is a bit ugly. However, // it is needed because Tests are not supposed to know anything about Action // Attributes (or any attribute) and Attributes don't know where they were // initially applied unless we tell them. // // ParameterizedMethodSuites and individual test cases both use the same // MethodInfo as a source of attributes. We handle the Test and Default targets // in the test case, so we don't want to doubly handle it here. bool applyToSuite = (action.Targets & ActionTargets.Suite) == ActionTargets.Suite || action.Targets == ActionTargets.Default && !(Test is ParameterizedMethodSuite); bool applyToTest = (action.Targets & ActionTargets.Test) == ActionTargets.Test && !(Test is ParameterizedMethodSuite); if (applyToSuite) actionItems.Add(new TestActionItem(action)); if (applyToTest) Context.UpstreamActions.Add(action); } _setupCommand = CommandBuilder.MakeOneTimeSetUpCommand(_suite, setUpTearDownItems, actionItems); _teardownCommand = CommandBuilder.MakeOneTimeTearDownCommand(_suite, setUpTearDownItems, actionItems); } private void PerformOneTimeSetUp() { try { _setupCommand.Execute(Context); // SetUp may have changed some things in the environment Context.UpdateContextFromEnvironment(); } catch (Exception ex) { if (ex is NUnitException || ex is TargetInvocationException) ex = ex.InnerException; Result.RecordException(ex, FailureSite.SetUp); } } private void RunChildren() { int childCount = _children.Count; if (childCount == 0) throw new InvalidOperationException("RunChildren called but item has no children"); _childTestCountdown = new CountdownEvent(childCount); foreach (WorkItem child in _children) { if (CheckForCancellation()) break; child.Completed += new EventHandler(OnChildCompleted); child.InitializeContext(new TestExecutionContext(Context)); Context.Dispatcher.Dispatch(child); childCount--; } if (childCount > 0) { while (childCount-- > 0) CountDownChildTest(); } } private void CreateChildWorkItems() { _children = new List<WorkItem>(); foreach (ITest test in _suite.Tests) if (_childFilter.Pass(test)) _children.Add(WorkItem.CreateWorkItem(test, _childFilter)); } private void SkipFixture(ResultState resultState, string message, string stackTrace) { Result.SetResult(resultState.WithSite(FailureSite.SetUp), message, StackFilter.Filter(stackTrace)); SkipChildren(_suite, resultState.WithSite(FailureSite.Parent), "OneTimeSetUp: " + message); } private void SkipChildren(TestSuite suite, ResultState resultState, string message) { foreach (Test child in suite.Tests) { if (_childFilter.Pass(child)) { TestResult childResult = child.MakeTestResult(); childResult.SetResult(resultState, message); Result.AddResult(childResult); // Some runners may depend on getting the TestFinished event // even for tests that have been skipped at a higher level. Context.Listener.TestFinished(childResult); if (child.IsSuite) SkipChildren((TestSuite)child, resultState, message); } } } private void PerformOneTimeTearDown() { // Our child tests or even unrelated tests may have // executed on the same thread since the time that // this test started, so we have to re-establish // the proper execution environment this.Context.EstablishExecutionEnvironment(); _teardownCommand.Execute(this.Context); } private string GetSkipReason() { return (string)Test.Properties.Get(PropertyNames.SkipReason); } private string GetProviderStackTrace() { return (string)Test.Properties.Get(PropertyNames.ProviderStackTrace); } private object _completionLock = new object(); private void OnChildCompleted(object sender, EventArgs e) { lock (_completionLock) { WorkItem childTask = sender as WorkItem; if (childTask != null) { childTask.Completed -= new EventHandler(OnChildCompleted); Result.AddResult(childTask.Result); if (Context.StopOnError && childTask.Result.ResultState.Status == TestStatus.Failed) Context.ExecutionStatus = TestExecutionStatus.StopRequested; // Check to see if all children completed CountDownChildTest(); } } } private void CountDownChildTest() { _childTestCountdown.Signal(); if (_childTestCountdown.CurrentCount == 0) { if (Context.ExecutionStatus != TestExecutionStatus.AbortRequested) PerformOneTimeTearDown(); foreach (var childResult in this.Result.Children) if (childResult.ResultState == ResultState.Cancelled) { this.Result.SetResult(ResultState.Cancelled, "Cancelled by user"); break; } WorkItemComplete(); } } private static bool IsStaticClass(Type type) { return type.GetTypeInfo().IsAbstract && type.GetTypeInfo().IsSealed; } private object cancelLock = new object(); /// <summary> /// Cancel (abort or stop) a CompositeWorkItem and all of its children /// </summary> /// <param name="force">true if the CompositeWorkItem and all of its children should be aborted, false if it should allow all currently running tests to complete</param> public override void Cancel(bool force) { lock (cancelLock) { if (_children == null) return; foreach (var child in _children) { var ctx = child.Context; if (ctx != null) ctx.ExecutionStatus = force ? TestExecutionStatus.AbortRequested : TestExecutionStatus.StopRequested; if (child.State == WorkItemState.Running) child.Cancel(force); } } } #endregion } }
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.VisualStudio.FSharp.LanguageService { using System.Runtime.InteropServices; using System; using System.Security.Permissions; using System.Collections; using System.IO; using System.Text; using System.Diagnostics.CodeAnalysis; [ System.Security.SuppressUnmanagedCodeSecurityAttribute() ] internal class UnsafeNativeMethods { // APIS [DllImport(ExternDll.Kernel32, CharSet=CharSet.Unicode, SetLastError=true)] internal static extern int GetFileAttributes(String name); [DllImport(ExternDll.Kernel32, CharSet = CharSet.Unicode)] public static extern void GetTempFileName(string tempDirName, string prefixName, int unique, StringBuilder sb); [DllImport(ExternDll.Kernel32, CharSet=CharSet.Auto)] [SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api")] public static extern void DebugBreak(); [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)] public static extern bool CloseHandle(HandleRef handle); [DllImport(ExternDll.User32, SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool LoadString(HandleRef hInstance, int uID, StringBuilder lpBuffer, int nBufferMax); //GetWindowLong won't work correctly for 64-bit: we should use GetWindowLongPtr instead. On //32-bit, GetWindowLongPtr is just #defined as GetWindowLong. GetWindowLong really should //take/return int instead of IntPtr/HandleRef, but since we're running this only for 32-bit //it'll be OK. public static IntPtr GetWindowLong(IntPtr hWnd, int nIndex) { if (IntPtr.Size == 4) { return GetWindowLong32(hWnd, nIndex); } return GetWindowLongPtr64(hWnd, nIndex); } [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] [DllImport(ExternDll.User32, CharSet = CharSet.Auto, EntryPoint = "GetWindowLong")] public static extern IntPtr GetWindowLong32(IntPtr hWnd, int nIndex); [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] [SuppressMessage("Microsoft.Interoperability", "CA1400:PInvokeEntryPointsShouldExist")] [DllImport(ExternDll.User32, CharSet = CharSet.Auto, EntryPoint = "GetWindowLongPtr")] public static extern IntPtr GetWindowLongPtr64(IntPtr hWnd, int nIndex); [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] internal static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam); [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] internal static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); [DllImport(ExternDll.User32, CharSet = System.Runtime.InteropServices.CharSet.Auto)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable")] public static extern IntPtr SendMessage(IntPtr hwnd, int msg, bool wparam, int lparam); [DllImport(ExternDll.User32, CharSet = CharSet.Unicode)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable")] public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, string lParam); [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] internal static extern IntPtr SetParent(IntPtr hWnd, IntPtr hWndParent); //SetWindowLong won't work correctly for 64-bit: we should use SetWindowLongPtr instead. On //32-bit, SetWindowLongPtr is just #defined as SetWindowLong. SetWindowLong really should //take/return int instead of IntPtr/HandleRef, but since we're running this only for 32-bit //it'll be OK. public static IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong) { if (IntPtr.Size == 4) { return SetWindowLongPtr32(hWnd, nIndex, dwNewLong); } return SetWindowLongPtr64(hWnd, nIndex, dwNewLong); } [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] [SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable")] [DllImport(ExternDll.User32, CharSet = CharSet.Auto, EntryPoint = "SetWindowLong")] public static extern IntPtr SetWindowLongPtr32(IntPtr hWnd, int nIndex, IntPtr dwNewLong); [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] [SuppressMessage("Microsoft.Interoperability", "CA1400:PInvokeEntryPointsShouldExist")] [DllImport(ExternDll.User32, CharSet = CharSet.Auto, EntryPoint = "SetWindowLongPtr")] public static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, IntPtr dwNewLong); public static IntPtr SetWindowLong(IntPtr hWnd, short nIndex, IntPtr dwNewLong) { if (IntPtr.Size == 4) { return SetWindowLongPtr32(hWnd, nIndex, dwNewLong); } return SetWindowLongPtr64(hWnd, (int)nIndex, dwNewLong); } [SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable")] [DllImport(ExternDll.User32, CharSet = CharSet.Auto, EntryPoint = "SetWindowLong")] public static extern IntPtr SetWindowLongPtr32(IntPtr hWnd, short nIndex, IntPtr dwNewLong); [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] internal static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, int flags); [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); /// IDataObject stuff [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] internal static extern IntPtr GlobalAlloc(int uFlags, int dwBytes); [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] internal static extern IntPtr GlobalReAlloc(HandleRef handle, int bytes, int flags); [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] internal static extern IntPtr GlobalLock(HandleRef handle); [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] internal static extern bool GlobalUnlock(HandleRef handle); [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] internal static extern IntPtr GlobalFree(HandleRef handle); [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] internal static extern int GlobalSize(HandleRef handle); [DllImport(ExternDll.Kernel32, EntryPoint = "GlobalLock", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] internal static extern IntPtr GlobalLock(IntPtr h); [DllImport(ExternDll.Kernel32, EntryPoint = "GlobalUnlock", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] internal static extern bool GlobalUnLock(IntPtr h); [DllImport(ExternDll.Kernel32, EntryPoint = "GlobalSize", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] internal static extern int GlobalSize(IntPtr h); [DllImport(ExternDll.Kernel32, ExactSpelling=true, EntryPoint="RtlMoveMemory", CharSet=CharSet.Unicode)] internal static extern void CopyMemoryW(IntPtr pdst, string psrc, int cb); [DllImport(ExternDll.Kernel32, ExactSpelling=true, EntryPoint="RtlMoveMemory", CharSet=CharSet.Unicode)] internal static extern void CopyMemoryW(IntPtr pdst, char[] psrc, int cb); [DllImport(ExternDll.Kernel32, ExactSpelling=true, EntryPoint="RtlMoveMemory", CharSet=CharSet.Unicode)] internal static extern void CopyMemoryW(StringBuilder pdst, HandleRef psrc, int cb); [DllImport(ExternDll.Kernel32, ExactSpelling=true, EntryPoint="RtlMoveMemory", CharSet=CharSet.Unicode)] internal static extern void CopyMemoryW(char[] pdst, HandleRef psrc, int cb); [DllImport(ExternDll.Kernel32, ExactSpelling=true, EntryPoint="RtlMoveMemory")] internal static extern void CopyMemory(IntPtr pdst, byte[] psrc, int cb); [DllImport(ExternDll.Kernel32, ExactSpelling=true, EntryPoint="RtlMoveMemory")] internal static extern void CopyMemory(byte[] pdst, HandleRef psrc, int cb); [DllImport(ExternDll.Kernel32, ExactSpelling=true, EntryPoint="RtlMoveMemory")] internal static extern void CopyMemory(IntPtr pdst, HandleRef psrc, int cb); [DllImport(ExternDll.Kernel32, ExactSpelling=true, EntryPoint="RtlMoveMemory", CharSet=CharSet.Unicode)] internal static extern void CopyMemory(IntPtr pdst, string psrc, int cb); [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Unicode)] internal static extern int WideCharToMultiByte(int codePage, int flags, [MarshalAs(UnmanagedType.LPWStr)]string wideStr, int chars, [In,Out]byte[] pOutBytes, int bufferBytes, IntPtr defaultChar, IntPtr pDefaultUsed); [DllImport(ExternDll.Ole32, ExactSpelling = true, CharSet = CharSet.Unicode)] internal static extern int OleSetClipboard(Microsoft.VisualStudio.OLE.Interop.IDataObject dataObject); [DllImport(ExternDll.Ole32, ExactSpelling = true, CharSet = CharSet.Unicode)] internal static extern int OleGetClipboard(out Microsoft.VisualStudio.OLE.Interop.IDataObject dataObject); [DllImport(ExternDll.Ole32, ExactSpelling = true, CharSet = CharSet.Unicode)] internal static extern int OleFlushClipboard(); [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Unicode)] internal static extern int OpenClipboard(IntPtr newOwner); [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Unicode)] internal static extern int EmptyClipboard(); [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Unicode)] internal static extern int CloseClipboard(); [DllImport(ExternDll.User32, EntryPoint = "RegisterClipboardFormatW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] internal static extern ushort RegisterClipboardFormat(string format); // endof IDataObject stuff [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] [DllImport("comctl32.dll", CharSet = CharSet.Auto)] public static extern IntPtr ImageList_Duplicate(HandleRef himl); [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] [DllImport("comctl32.dll", CharSet = CharSet.Auto)] public static extern int ImageList_GetImageCount(HandleRef himl); [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] [DllImport("comctl32.dll", CharSet = CharSet.Auto)] public static extern bool ImageList_Draw(HandleRef himl, int i, HandleRef hdcDst, int x, int y, int fStyle); [DllImport("shell32.dll", EntryPoint = "DragQueryFileW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern uint DragQueryFile(IntPtr hDrop, uint iFile, char[] lpszFile, uint cch); } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Microsoft Public License. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Microsoft Public License, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Microsoft Public License. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ namespace System.Runtime.InteropServices { using System.Diagnostics; /// <summary> /// Variant is the basic COM type for late-binding. It can contain any other COM data type. /// This type definition precisely matches the unmanaged data layout so that the struct can be passed /// to and from COM calls. /// </summary> [StructLayout(LayoutKind.Explicit)] [System.Security.SecurityCritical] internal struct Variant { #if DEBUG static Variant() { // Variant size is the size of 4 pointers (16 bytes) on a 32-bit processor, // and 3 pointers (24 bytes) on a 64-bit processor. int variantSize = Marshal.SizeOf(typeof(Variant)); if (IntPtr.Size == 4) { BCLDebug.Assert(variantSize == (4 * IntPtr.Size), "variant"); } else { BCLDebug.Assert(IntPtr.Size == 8, "variant"); BCLDebug.Assert(variantSize == (3 * IntPtr.Size), "variant"); } } #endif // Most of the data types in the Variant are carried in _typeUnion [FieldOffset(0)] private TypeUnion _typeUnion; // Decimal is the largest data type and it needs to use the space that is normally unused in TypeUnion._wReserved1, etc. // Hence, it is declared to completely overlap with TypeUnion. A Decimal does not use the first two bytes, and so // TypeUnion._vt can still be used to encode the type. [FieldOffset(0)] private Decimal _decimal; [StructLayout(LayoutKind.Sequential)] private struct TypeUnion { internal ushort _vt; internal ushort _wReserved1; internal ushort _wReserved2; internal ushort _wReserved3; internal UnionTypes _unionTypes; } [StructLayout(LayoutKind.Sequential)] private struct Record { private IntPtr _record; private IntPtr _recordInfo; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable")] [StructLayout(LayoutKind.Explicit)] private struct UnionTypes { #region Generated Variant union types // *** BEGIN GENERATED CODE *** // generated by function: gen_UnionTypes from: generate_comdispatch.py [FieldOffset(0)] internal SByte _i1; [FieldOffset(0)] internal Int16 _i2; [FieldOffset(0)] internal Int32 _i4; [FieldOffset(0)] internal Int64 _i8; [FieldOffset(0)] internal Byte _ui1; [FieldOffset(0)] internal UInt16 _ui2; [FieldOffset(0)] internal UInt32 _ui4; [FieldOffset(0)] internal UInt64 _ui8; [FieldOffset(0)] internal Int32 _int; [FieldOffset(0)] internal UInt32 _uint; [FieldOffset(0)] internal Int16 _bool; [FieldOffset(0)] internal Int32 _error; [FieldOffset(0)] internal Single _r4; [FieldOffset(0)] internal Double _r8; [FieldOffset(0)] internal Int64 _cy; [FieldOffset(0)] internal double _date; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] [FieldOffset(0)] internal IntPtr _bstr; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] [FieldOffset(0)] internal IntPtr _unknown; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] [FieldOffset(0)] internal IntPtr _dispatch; // *** END GENERATED CODE *** #endregion [FieldOffset(0)] internal IntPtr _pvarVal; [FieldOffset(0)] internal IntPtr _byref; [FieldOffset(0)] internal Record _record; } /// <summary> /// Primitive types are the basic COM types. It includes valuetypes like ints, but also reference types /// like BStrs. It does not include composite types like arrays and user-defined COM types (IUnknown/IDispatch). /// </summary> internal static bool IsPrimitiveType(VarEnum varEnum) { switch(varEnum) { #region Generated Variant IsPrimitiveType // *** BEGIN GENERATED CODE *** // generated by function: gen_IsPrimitiveType from: generate_comdispatch.py case VarEnum.VT_I1: case VarEnum.VT_I2: case VarEnum.VT_I4: case VarEnum.VT_I8: case VarEnum.VT_UI1: case VarEnum.VT_UI2: case VarEnum.VT_UI4: case VarEnum.VT_UI8: case VarEnum.VT_INT: case VarEnum.VT_UINT: case VarEnum.VT_BOOL: case VarEnum.VT_R4: case VarEnum.VT_R8: case VarEnum.VT_DECIMAL: case VarEnum.VT_DATE: case VarEnum.VT_BSTR: // *** END GENERATED CODE *** #endregion return true; } return false; } unsafe public void CopyFromIndirect(object value) { VarEnum vt = (VarEnum)(((int)this.VariantType) & ~((int)VarEnum.VT_BYREF)); if (value == null) { if (vt == VarEnum.VT_DISPATCH || vt == VarEnum.VT_UNKNOWN || vt == VarEnum.VT_BSTR) { *(IntPtr*)this._typeUnion._unionTypes._byref = IntPtr.Zero; } return; } switch (vt) { case VarEnum.VT_I1: *(sbyte*)this._typeUnion._unionTypes._byref = (sbyte)value; break; case VarEnum.VT_UI1: *(byte*)this._typeUnion._unionTypes._byref = (byte)value; break; case VarEnum.VT_I2: *(short*)this._typeUnion._unionTypes._byref = (short)value; break; case VarEnum.VT_UI2: *(ushort*)this._typeUnion._unionTypes._byref = (ushort)value; break; case VarEnum.VT_BOOL: *(short*)this._typeUnion._unionTypes._byref = (bool)value ? (short)-1 : (short)0; break; case VarEnum.VT_I4: case VarEnum.VT_INT: *(int*)this._typeUnion._unionTypes._byref = (int)value; break; case VarEnum.VT_UI4: case VarEnum.VT_UINT: *(uint*)this._typeUnion._unionTypes._byref = (uint)value; break; case VarEnum.VT_ERROR: *(int*)this._typeUnion._unionTypes._byref = ((ErrorWrapper)value).ErrorCode; break; case VarEnum.VT_I8: *(Int64*)this._typeUnion._unionTypes._byref = (Int64)value; break; case VarEnum.VT_UI8: *(UInt64*)this._typeUnion._unionTypes._byref = (UInt64)value; break; case VarEnum.VT_R4: *(float*)this._typeUnion._unionTypes._byref = (float)value; break; case VarEnum.VT_R8: *(double*)this._typeUnion._unionTypes._byref = (double)value; break; case VarEnum.VT_DATE: *(double*)this._typeUnion._unionTypes._byref = ((DateTime)value).ToOADate(); break; case VarEnum.VT_UNKNOWN: *(IntPtr*)this._typeUnion._unionTypes._byref = Marshal.GetIUnknownForObject(value); break; case VarEnum.VT_DISPATCH: *(IntPtr*)this._typeUnion._unionTypes._byref = Marshal.GetIDispatchForObject(value); break; case VarEnum.VT_BSTR: *(IntPtr*)this._typeUnion._unionTypes._byref = Marshal.StringToBSTR((string)value); break; case VarEnum.VT_CY: *(long*)this._typeUnion._unionTypes._byref = decimal.ToOACurrency((decimal)value); break; case VarEnum.VT_DECIMAL: *(decimal*)this._typeUnion._unionTypes._byref = (decimal)value; break; case VarEnum.VT_VARIANT: Marshal.GetNativeVariantForObject(value, this._typeUnion._unionTypes._byref); break; default: throw new ArgumentException("invalid argument type"); } } /// <summary> /// Get the managed object representing the Variant. /// </summary> /// <returns></returns> public object ToObject() { // Check the simple case upfront if (IsEmpty) { return null; } switch (VariantType) { case VarEnum.VT_NULL: return DBNull.Value; #region Generated Variant ToObject // *** BEGIN GENERATED CODE *** // generated by function: gen_ToObject from: generate_comdispatch.py case VarEnum.VT_I1: return AsI1; case VarEnum.VT_I2: return AsI2; case VarEnum.VT_I4: return AsI4; case VarEnum.VT_I8: return AsI8; case VarEnum.VT_UI1: return AsUi1; case VarEnum.VT_UI2: return AsUi2; case VarEnum.VT_UI4: return AsUi4; case VarEnum.VT_UI8: return AsUi8; case VarEnum.VT_INT: return AsInt; case VarEnum.VT_UINT: return AsUint; case VarEnum.VT_BOOL: return AsBool; case VarEnum.VT_ERROR: return AsError; case VarEnum.VT_R4: return AsR4; case VarEnum.VT_R8: return AsR8; case VarEnum.VT_DECIMAL: return AsDecimal; case VarEnum.VT_CY: return AsCy; case VarEnum.VT_DATE: return AsDate; case VarEnum.VT_BSTR: return AsBstr; case VarEnum.VT_UNKNOWN: return AsUnknown; case VarEnum.VT_DISPATCH: return AsDispatch; // VarEnum.VT_VARIANT is handled by Marshal.GetObjectForNativeVariant below // *** END GENERATED CODE *** #endregion default: try { unsafe { fixed (void* pThis = &this) { return Marshal.GetObjectForNativeVariant((System.IntPtr)pThis); } } } catch (Exception ex) { throw new NotImplementedException("Variant.ToObject cannot handle" + VariantType, ex); } } } /// <summary> /// Release any unmanaged memory associated with the Variant /// </summary> /// <returns></returns> public void Clear() { // We do not need to call OLE32's VariantClear for primitive types or ByRefs // to safe ourselves the cost of interop transition. // ByRef indicates the memory is not owned by the VARIANT itself while // primitive types do not have any resources to free up. // Hence, only safearrays, BSTRs, interfaces and user types are // handled differently. VarEnum vt = VariantType; if ((vt & VarEnum.VT_BYREF) != 0) { VariantType = VarEnum.VT_EMPTY; } else if ( ((vt & VarEnum.VT_ARRAY) != 0) || ((vt) == VarEnum.VT_BSTR) || ((vt) == VarEnum.VT_UNKNOWN) || ((vt) == VarEnum.VT_DISPATCH) || ((vt) == VarEnum.VT_VARIANT) || ((vt) == VarEnum.VT_RECORD) || ((vt) == VarEnum.VT_VARIANT) ) { unsafe { fixed (void* pThis = &this) { NativeMethods.VariantClear((IntPtr)pThis); } } BCLDebug.Assert(IsEmpty, "variant"); } else { VariantType = VarEnum.VT_EMPTY; } } public VarEnum VariantType { get { return (VarEnum)_typeUnion._vt; } set { _typeUnion._vt = (ushort)value; } } internal bool IsEmpty { get { return _typeUnion._vt == ((ushort)VarEnum.VT_EMPTY); } } internal bool IsByRef { get { return (_typeUnion._vt & ((ushort)VarEnum.VT_BYREF)) != 0; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] // public void SetAsNULL() { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_NULL; } #region Generated Variant accessors // *** BEGIN GENERATED CODE *** // generated by function: gen_accessors from: generate_comdispatch.py // VT_I1 public SByte AsI1 { get { BCLDebug.Assert(VariantType == VarEnum.VT_I1, "variant"); return _typeUnion._unionTypes._i1; } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_I1; _typeUnion._unionTypes._i1 = value; } } // VT_I2 public Int16 AsI2 { get { BCLDebug.Assert(VariantType == VarEnum.VT_I2, "variant"); return _typeUnion._unionTypes._i2; } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_I2; _typeUnion._unionTypes._i2 = value; } } // VT_I4 public Int32 AsI4 { get { BCLDebug.Assert(VariantType == VarEnum.VT_I4, "variant"); return _typeUnion._unionTypes._i4; } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_I4; _typeUnion._unionTypes._i4 = value; } } // VT_I8 public Int64 AsI8 { get { BCLDebug.Assert(VariantType == VarEnum.VT_I8, "variant"); return _typeUnion._unionTypes._i8; } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_I8; _typeUnion._unionTypes._i8 = value; } } // VT_UI1 public Byte AsUi1 { get { BCLDebug.Assert(VariantType == VarEnum.VT_UI1, "variant"); return _typeUnion._unionTypes._ui1; } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_UI1; _typeUnion._unionTypes._ui1 = value; } } // VT_UI2 public UInt16 AsUi2 { get { BCLDebug.Assert(VariantType == VarEnum.VT_UI2, "variant"); return _typeUnion._unionTypes._ui2; } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_UI2; _typeUnion._unionTypes._ui2 = value; } } // VT_UI4 public UInt32 AsUi4 { get { BCLDebug.Assert(VariantType == VarEnum.VT_UI4, "variant"); return _typeUnion._unionTypes._ui4; } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_UI4; _typeUnion._unionTypes._ui4 = value; } } // VT_UI8 public UInt64 AsUi8 { get { BCLDebug.Assert(VariantType == VarEnum.VT_UI8, "variant"); return _typeUnion._unionTypes._ui8; } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_UI8; _typeUnion._unionTypes._ui8 = value; } } // VT_INT public Int32 AsInt { get { BCLDebug.Assert(VariantType == VarEnum.VT_INT, "variant"); return _typeUnion._unionTypes._int; } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_INT; _typeUnion._unionTypes._int = value; } } // VT_UINT public UInt32 AsUint { get { BCLDebug.Assert(VariantType == VarEnum.VT_UINT, "variant"); return _typeUnion._unionTypes._uint; } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_UINT; _typeUnion._unionTypes._uint = value; } } // VT_BOOL public bool AsBool { get { BCLDebug.Assert(VariantType == VarEnum.VT_BOOL, "variant"); return _typeUnion._unionTypes._bool != 0; } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_BOOL; _typeUnion._unionTypes._bool = value ? (short)-1 : (short)0; } } // VT_ERROR public Int32 AsError { get { BCLDebug.Assert(VariantType == VarEnum.VT_ERROR, "variant"); return _typeUnion._unionTypes._error; } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_ERROR; _typeUnion._unionTypes._error = value; } } // VT_R4 public Single AsR4 { get { BCLDebug.Assert(VariantType == VarEnum.VT_R4, "variant"); return _typeUnion._unionTypes._r4; } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_R4; _typeUnion._unionTypes._r4 = value; } } // VT_R8 public Double AsR8 { get { BCLDebug.Assert(VariantType == VarEnum.VT_R8, "variant"); return _typeUnion._unionTypes._r8; } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_R8; _typeUnion._unionTypes._r8 = value; } } // VT_DECIMAL public Decimal AsDecimal { get { BCLDebug.Assert(VariantType == VarEnum.VT_DECIMAL, "variant"); // The first byte of Decimal is unused, but usually set to 0 Variant v = this; v._typeUnion._vt = 0; return v._decimal; } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_DECIMAL; _decimal = value; // _vt overlaps with _decimal, and should be set after setting _decimal _typeUnion._vt = (ushort)VarEnum.VT_DECIMAL; } } // VT_CY public Decimal AsCy { get { BCLDebug.Assert(VariantType == VarEnum.VT_CY, "variant"); return Decimal.FromOACurrency(_typeUnion._unionTypes._cy); } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_CY; _typeUnion._unionTypes._cy = Decimal.ToOACurrency(value); } } // VT_DATE public DateTime AsDate { get { BCLDebug.Assert(VariantType == VarEnum.VT_DATE, "variant"); return DateTime.FromOADate(_typeUnion._unionTypes._date); } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_DATE; _typeUnion._unionTypes._date = value.ToOADate(); } } // VT_BSTR public String AsBstr { get { BCLDebug.Assert(VariantType == VarEnum.VT_BSTR, "variant"); return (string)Marshal.PtrToStringBSTR(this._typeUnion._unionTypes._bstr); } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_BSTR; this._typeUnion._unionTypes._bstr = Marshal.StringToBSTR(value); } } // VT_UNKNOWN public Object AsUnknown { get { BCLDebug.Assert(VariantType == VarEnum.VT_UNKNOWN, "variant"); if (_typeUnion._unionTypes._unknown == IntPtr.Zero) return null; return Marshal.GetObjectForIUnknown(_typeUnion._unionTypes._unknown); } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_UNKNOWN; if (value == null) _typeUnion._unionTypes._unknown = IntPtr.Zero; else _typeUnion._unionTypes._unknown = Marshal.GetIUnknownForObject(value); } } // VT_DISPATCH public Object AsDispatch { get { BCLDebug.Assert(VariantType == VarEnum.VT_DISPATCH, "variant"); if (_typeUnion._unionTypes._dispatch == IntPtr.Zero) return null; return Marshal.GetObjectForIUnknown(_typeUnion._unionTypes._dispatch); } set { BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_DISPATCH; if (value == null) _typeUnion._unionTypes._dispatch = IntPtr.Zero; else _typeUnion._unionTypes._dispatch = Marshal.GetIDispatchForObject(value); } } // *** END GENERATED CODE *** internal IntPtr AsByRefVariant { get { BCLDebug.Assert(VariantType == (VarEnum.VT_BYREF | VarEnum.VT_VARIANT), "variant"); return _typeUnion._unionTypes._pvarVal; } } #endregion } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using Windows.Devices.PointOfService; using System.Threading.Tasks; using Windows.Devices.Enumeration; using SDKTemplate; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace PosPrinterSample { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class Scenario2_ErrorHandling : Page { private MainPage rootPage; PosPrinter printer = null; ClaimedPosPrinter claimedPrinter = null; bool IsAnImportantTransaction = true; public Scenario2_ErrorHandling() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; ResetTheScenarioState(); } /// <summary> /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame /// </summary> /// <param name="e">Provides data for the OnNavigatingFrom callback that can be used to cancel a navigation /// request from origination</param> protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { ResetTheScenarioState(); } private void ResetTheScenarioState() { //Remove releasedevicerequested handler and dispose claimed printer object. if (claimedPrinter != null) { claimedPrinter.ReleaseDeviceRequested -= ClaimedPrinter_ReleaseDeviceRequested; claimedPrinter.Dispose(); claimedPrinter = null; } if (printer != null) { printer.Dispose(); printer = null; } } /// <summary> /// Creates multiple tasks, first to find a receipt printer, then to claim the printer and then to enable and add releasedevicerequested event handler. /// </summary> async void FindClaimEnable_Click(object sender, RoutedEventArgs e) { if (await FindReceiptPrinter()) { if (await ClaimPrinter()) { await EnableAsync(); } } } async void PrintLine_Click(object sender, RoutedEventArgs e) { await PrintLineAndCheckForErrors(); } /// <summary> /// Prints the line that is in the textbox. Then checks for any error conditions and reports the same to user. /// </summary> private async Task<bool> PrintLineAndCheckForErrors() { if (!IsPrinterClaimed()) { return false; } ReceiptPrintJob job = claimedPrinter.Receipt.CreateJob(); job.PrintLine(txtPrintLine.Text); if (await job.ExecuteAsync()) { rootPage.NotifyUser("Printed line", NotifyType.StatusMessage); return true; } else { if (claimedPrinter.Receipt.IsCartridgeEmpty) { rootPage.NotifyUser("Printer is out of ink. Please replace cartridge.", NotifyType.StatusMessage); } else if (claimedPrinter.Receipt.IsCartridgeRemoved) { rootPage.NotifyUser("Printer cartridge is missing. Please replace cartridge.", NotifyType.StatusMessage); } else if (claimedPrinter.Receipt.IsCoverOpen) { rootPage.NotifyUser("Printer cover is open. Please close it.", NotifyType.StatusMessage); } else if (claimedPrinter.Receipt.IsHeadCleaning) { rootPage.NotifyUser("Printer is currently cleaning the cartridge. Please wait until cleaning has completed.", NotifyType.StatusMessage); } else if (claimedPrinter.Receipt.IsPaperEmpty) { rootPage.NotifyUser("Printer is out of paper. Please insert a new roll.", NotifyType.StatusMessage); } else { rootPage.NotifyUser("Was not able to print line", NotifyType.StatusMessage); } } return false; } private void EndScenario_Click(object sender, RoutedEventArgs e) { ResetTheScenarioState(); rootPage.NotifyUser("Disconnected Printer", NotifyType.StatusMessage); } /// <summary> /// Actual claim method task that claims the printer asynchronously /// </summary> private async Task<bool> ClaimPrinter() { if (claimedPrinter == null) { claimedPrinter = await printer.ClaimPrinterAsync(); if (claimedPrinter != null) { rootPage.NotifyUser("Claimed Printer", NotifyType.StatusMessage); } else { rootPage.NotifyUser("Claim Printer failed", NotifyType.ErrorMessage); return false; } } return true; } /// <summary> /// Enable the claimed printer. /// </summary> private async Task<bool> EnableAsync() { if (claimedPrinter == null) { claimedPrinter.ReleaseDeviceRequested += ClaimedPrinter_ReleaseDeviceRequested; rootPage.NotifyUser("No Claimed Printer to enable", NotifyType.ErrorMessage); return false; } if (!await claimedPrinter.EnableAsync()) { rootPage.NotifyUser("Could not enable printer", NotifyType.ErrorMessage); return false; } rootPage.NotifyUser("Enabled Printer", NotifyType.StatusMessage); return true; } /// <summary> /// Check to make sure we still have claim on printer /// </summary> private bool IsPrinterClaimed() { if (printer == null) { rootPage.NotifyUser("Need to find printer first", NotifyType.ErrorMessage); return false; } if (claimedPrinter == null) { rootPage.NotifyUser("No claimed printer.", NotifyType.ErrorMessage); return false; } if (claimedPrinter.Receipt == null) { rootPage.NotifyUser("No receipt printer object in claimed printer.", NotifyType.ErrorMessage); return false; } return true; } private async Task<bool> FindReceiptPrinter() { if (printer == null) { rootPage.NotifyUser("Finding printer", NotifyType.StatusMessage); printer = await DeviceHelpers.GetFirstReceiptPrinterAsync(); if (printer != null) { rootPage.NotifyUser("Got Printer with Device Id : " + printer.DeviceId, NotifyType.StatusMessage); return true; } else { rootPage.NotifyUser("No Printer found", NotifyType.ErrorMessage); return false; } } return true; } async void ClaimedPrinter_ReleaseDeviceRequested(ClaimedPosPrinter sender, PosPrinterReleaseDeviceRequestedEventArgs args) { if (IsAnImportantTransaction) { await sender.RetainDeviceAsync(); } else { ResetTheScenarioState(); } } } }