content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
#region License // // Copyright (c) 2007-2018, Sean Chambers <schambers80@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using FluentMigrator.Infrastructure; namespace FluentMigrator.Builders.Schema.Column { public interface ISchemaColumnSyntax : IFluentSyntax { bool Exists(); } }
29.928571
75
0.739857
[ "Apache-2.0" ]
quesadaao/fluentmigrator
src/FluentMigrator.Abstractions/Builders/Schema/Column/ISchemaColumnSyntax.cs
838
C#
using SimpleInjector; using Study.Algorithms; using Study.Algorithms.Sorters; using Study.Structures; using Study.Structures.PartialFunctions; using Study.Structures.Queues; using Study.Structures.Stacks; using System; namespace UnitTests { static class Common { public static Container Container; static Common() { Container = new Container(); Container.Register<IStack<int>, LinkedListStack<int>>(); Container.Register<IQueue<int>, LinkedListQueue<int>>(); Container.Register<IPartialFunction<string, int>, HashtablePartialFunction<string, int>>(); Container.Register<ISortedPartialFunction<string, int>, SkipListPartialFunction<string, int>>(); Container.Register<ISorter<int>, SortedPartialOrderSorter<int, BinarySearchTreePartialFunction<int, int>>>(); } } }
31.571429
121
0.697964
[ "MIT" ]
landon/InterviewStudy
UnitTests/Common.cs
886
C#
// Copyright (c) Stride contributors (https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Specialized; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Stride.Core; using Stride.Core.Collections; using Stride.Core.Reflection; using Stride.Core.Serialization.Contents; using Stride.Engine.Design; using Stride.Rendering; namespace Stride.Engine { /// <summary> /// Manage a collection of entities within a <see cref="RootScene"/>. /// </summary> public sealed class SceneInstance : EntityManager { /// <summary> /// A property key to get the current scene from the <see cref="RenderContext.Tags"/>. /// </summary> public static readonly PropertyKey<SceneInstance> Current = new PropertyKey<SceneInstance>("SceneInstance.Current", typeof(SceneInstance)); /// <summary> /// A property key to get the current render system from the <see cref="RenderContext.Tags"/>. /// </summary> public static readonly PropertyKey<RenderSystem> CurrentRenderSystem = new PropertyKey<RenderSystem>("SceneInstance.CurrentRenderSystem", typeof(SceneInstance)); /// <summary> /// A property key to get the current visibility group from the <see cref="RenderContext.Tags"/>. /// </summary> public static readonly PropertyKey<VisibilityGroup> CurrentVisibilityGroup = new PropertyKey<VisibilityGroup>("SceneInstance.CurrentVisibilityGroup", typeof(SceneInstance)); private readonly Dictionary<TypeInfo, RegisteredRenderProcessors> registeredRenderProcessorTypes = new Dictionary<TypeInfo, RegisteredRenderProcessors>(); private Scene rootScene; public TrackingCollection<VisibilityGroup> VisibilityGroups { get; } /// <summary> /// Occurs when the scene changed from a scene child component. /// </summary> public event EventHandler<EventArgs> RootSceneChanged; /// <summary> /// Initializes a new instance of the <see cref="EntityManager" /> class. /// </summary> /// <param name="registry">The registry.</param> public SceneInstance(IServiceRegistry registry) : this(registry, null) { } /// <summary> /// Initializes a new instance of the <see cref="SceneInstance" /> class. /// </summary> /// <param name="services">The services.</param> /// <param name="rootScene">The scene entity root.</param> /// <param name="executionMode">The mode that determines which processors are executed.</param> /// <exception cref="System.ArgumentNullException">services /// or /// rootScene</exception> public SceneInstance(IServiceRegistry services, Scene rootScene, ExecutionMode executionMode = ExecutionMode.Runtime) : base(services) { if (services == null) throw new ArgumentNullException(nameof(services)); ExecutionMode = executionMode; VisibilityGroups = new TrackingCollection<VisibilityGroup>(); VisibilityGroups.CollectionChanged += VisibilityGroups_CollectionChanged; RootScene = rootScene; } /// <summary> /// Gets the scene. /// </summary> /// <value>The scene.</value> public Scene RootScene { get { return rootScene; } set { if (rootScene == value) return; if (rootScene != null) { Remove(rootScene); RemoveRendererTypes(); } if (value != null) { Add(value); HandleRendererTypes(); } rootScene = value; OnRootSceneChanged(); } } protected override void Destroy() { RootScene = null; // Cleaning processors should not be necessary anymore, but physics are not properly cleaned up otherwise Reset(); // TODO: Dispose of Scene, graphics compositor...etc. // Currently in Destroy(), not sure if we should clear that list on Reset() as well? VisibilityGroups.Clear(); base.Destroy(); } /// <summary> /// Gets the current scene valid only from a rendering context. May be null. /// </summary> /// <param name="context">The context.</param> /// <returns>Stride.Engine.SceneInstance.</returns> public static SceneInstance GetCurrent(RenderContext context) { return context.Tags.Get(Current); } private void Add(Scene scene) { if (scene.Entities.Count > 0) { var entitiesToAdd = new FastList<Entity>(); // Reverse order, we're adding and removing from the tail to // avoid forcing the list to move all items when removing at [0] for (int i = scene.Entities.Count -1; i >= 0; i-- ) entitiesToAdd.Add(scene.Entities[i]); scene.Entities.CollectionChanged += DealWithTempChanges; while (entitiesToAdd.Count > 0) { int i = entitiesToAdd.Count - 1; var entity = entitiesToAdd[i]; entitiesToAdd.RemoveAt(i); Add(entity); } scene.Entities.CollectionChanged -= DealWithTempChanges; void DealWithTempChanges(object sender, TrackingCollectionChangedEventArgs e) { Entity entity = (Entity)e.Item; if (e.Action == NotifyCollectionChangedAction.Remove) { if (entitiesToAdd.Remove(entity) == false) Remove(entity); } else if (e.Action == NotifyCollectionChangedAction.Add) entitiesToAdd.Add(entity); } } if (scene.Children.Count > 0) { var scenesToAdd = new FastList<Scene>(); // Reverse order, we're adding and removing from the tail to // avoid forcing the list to move all items when removing at [0] for (int i = scene.Children.Count - 1; i >= 0; i--) scenesToAdd.Add(scene.Children[i]); scene.Children.CollectionChanged += DealWithTempChanges; while (scenesToAdd.Count > 0) { int i = scenesToAdd.Count - 1; var entity = scenesToAdd[i]; scenesToAdd.RemoveAt(i); Add(entity); } scene.Children.CollectionChanged -= DealWithTempChanges; void DealWithTempChanges(object sender, TrackingCollectionChangedEventArgs e) { Scene subScene = (Scene)e.Item; if (e.Action == NotifyCollectionChangedAction.Remove) { if (scenesToAdd.Remove(subScene) == false) Remove(subScene); } else if (e.Action == NotifyCollectionChangedAction.Add) scenesToAdd.Add(subScene); } } // Listen to future changes in entities and child scenes scene.Children.CollectionChanged += Children_CollectionChanged; scene.Entities.CollectionChanged += Entities_CollectionChanged; } private void Remove(Scene scene) { scene.Entities.CollectionChanged -= Entities_CollectionChanged; scene.Children.CollectionChanged -= Children_CollectionChanged; if (scene.Children.Count > 0) { var scenesToRemove = new Scene[scene.Children.Count]; scene.Children.CopyTo(scenesToRemove, 0); foreach (var childScene in scenesToRemove) Remove(childScene); } if (scene.Entities.Count > 0) { var entitiesToRemove = new Entity[scene.Entities.Count]; scene.Entities.CopyTo(entitiesToRemove, 0); foreach (var entity in entitiesToRemove) Remove(entity); } } private void Entities_CollectionChanged(object sender, TrackingCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: Add((Entity)e.Item); break; case NotifyCollectionChangedAction.Remove: Remove((Entity)e.Item); break; } } private void Children_CollectionChanged(object sender, TrackingCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: Add((Scene)e.Item); break; case NotifyCollectionChangedAction.Remove: Remove((Scene)e.Item); break; } } private void HandleRendererTypes() { foreach (var componentType in ComponentTypes) { EntitySystemOnComponentTypeAdded(null, componentType); } ComponentTypeAdded += EntitySystemOnComponentTypeAdded; } private void RemoveRendererTypes() { // Unregister render processors ComponentTypeAdded -= EntitySystemOnComponentTypeAdded; foreach (var renderProcessors in registeredRenderProcessorTypes) { foreach (var renderProcessorInstance in renderProcessors.Value.Instances) { Processors.Remove(renderProcessorInstance.Value); } } registeredRenderProcessorTypes.Clear(); } private void VisibilityGroups_CollectionChanged(object sender, TrackingCollectionChangedEventArgs e) { var visibilityGroup = (VisibilityGroup)e.Item; switch (e.Action) { case NotifyCollectionChangedAction.Add: foreach (var registeredRenderProcessorType in registeredRenderProcessorTypes) { var processor = CreateRenderProcessor(registeredRenderProcessorType.Value, visibilityGroup); // Assume we are in middle of a compositor draw so we need to run it manually once (Update/Draw already happened) var renderContext = RenderContext.GetShared(Services); processor.Update(renderContext.Time); processor.Draw(renderContext); } break; case NotifyCollectionChangedAction.Remove: foreach (var registeredRenderProcessorType in registeredRenderProcessorTypes) { // Remove matching entries var instances = registeredRenderProcessorType.Value.Instances; for (int i = 0; i < instances.Count; ++i) { var registeredProcessorInstance = instances[i]; if (registeredProcessorInstance.Key == visibilityGroup) { Processors.Remove(registeredProcessorInstance.Value); instances.RemoveAt(i); break; } } } visibilityGroup.Dispose(); break; } } private void EntitySystemOnComponentTypeAdded(object sender, TypeInfo type) { var rendererTypeAttributes = type.GetCustomAttributes<DefaultEntityComponentRendererAttribute>(); foreach (var rendererTypeAttribute in rendererTypeAttributes) { var processorType = AssemblyRegistry.GetType(rendererTypeAttribute.TypeName); if (processorType == null || !typeof(IEntityComponentRenderProcessor).GetTypeInfo().IsAssignableFrom(processorType.GetTypeInfo())) { continue; } var registeredProcessors = new RegisteredRenderProcessors(processorType, VisibilityGroups.Count); registeredRenderProcessorTypes.Add(type, registeredProcessors); // Create a render processor for each visibility group foreach (var visibilityGroup in VisibilityGroups) { CreateRenderProcessor(registeredProcessors, visibilityGroup); } } } private EntityProcessor CreateRenderProcessor(RegisteredRenderProcessors registeredRenderProcessor, VisibilityGroup visibilityGroup) { // Create var processor = (EntityProcessor)Activator.CreateInstance(registeredRenderProcessor.Type); // Set visibility group ((IEntityComponentRenderProcessor)processor).VisibilityGroup = visibilityGroup; // Add processor Processors.Add(processor); registeredRenderProcessor.Instances.Add(new KeyValuePair<VisibilityGroup, EntityProcessor>(visibilityGroup, processor)); return processor; } private void OnRootSceneChanged() { RootSceneChanged?.Invoke(this, EventArgs.Empty); } private class RegisteredRenderProcessors { public Type Type; public FastListStruct<KeyValuePair<VisibilityGroup, EntityProcessor>> Instances; public RegisteredRenderProcessors(Type type, int instanceCount) { Type = type; Instances = new FastListStruct<KeyValuePair<VisibilityGroup, EntityProcessor>>(instanceCount); } } } }
40.084932
181
0.566947
[ "MIT" ]
Aggror/Stride
sources/engine/Stride.Engine/Engine/SceneInstance.cs
14,631
C#
using Microsoft.AspNetCore.Builder; using System; namespace Lefebvre.eLefebvreOnContainers.Services.Google.Gmail.API.Infrastructure.Middlewares { public static class FailingMiddlewareAppBuilderExtensions { public static IApplicationBuilder UseFailingMiddleware(this IApplicationBuilder builder) { return UseFailingMiddleware(builder, null); } public static IApplicationBuilder UseFailingMiddleware(this IApplicationBuilder builder, Action<FailingOptions> action) { var options = new FailingOptions(); action?.Invoke(options); builder.UseMiddleware<FailingMiddleware>(options); return builder; } } }
34.333333
127
0.705964
[ "MIT" ]
lefevbre-organization/eShopOnContainers
src/Services/Google/GoogleGmail.API/Infrastructure/Middlewares/FailingMiddlewareAppBuilderExtensions.cs
723
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; namespace Tasks { public class B { public static void Main(string[] args) { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); Solve(); Console.Out.Flush(); } public static void Solve() { var (A, B) = Scanner.Scan<int, int>(); var T = new int[11]; if (A > 0) { var P = Scanner.ScanEnumerable<int>().ToArray(); foreach (var p in P) T[p] = 1; } else Console.ReadLine(); if (B > 0) { var Q = Scanner.ScanEnumerable<int>().ToArray(); foreach (var q in Q) T[q] = 2; } else Console.ReadLine(); T[10] = T[0]; static char Convert(int x) => x switch { 0 => 'x', 1 => '.', 2 => 'o', _ => default }; Console.WriteLine(string.Join(" ", T[7..].Select(Convert))); Console.WriteLine($" {string.Join(" ", T[4..7].Select(Convert))}"); Console.WriteLine($" {string.Join(" ", T[2..4].Select(Convert))}"); Console.WriteLine($" {string.Join(" ", T[1..2].Select(Convert))}"); } public static class Scanner { private static Queue<string> queue = new Queue<string>(); public static T Next<T>() { if (!queue.Any()) foreach (var item in Console.ReadLine().Trim().Split(" ")) queue.Enqueue(item); return (T)Convert.ChangeType(queue.Dequeue(), typeof(T)); } public static T Scan<T>() => Next<T>(); public static (T1, T2) Scan<T1, T2>() => (Next<T1>(), Next<T2>()); public static (T1, T2, T3) Scan<T1, T2, T3>() => (Next<T1>(), Next<T2>(), Next<T3>()); public static (T1, T2, T3, T4) Scan<T1, T2, T3, T4>() => (Next<T1>(), Next<T2>(), Next<T3>(), Next<T4>()); public static (T1, T2, T3, T4, T5) Scan<T1, T2, T3, T4, T5>() => (Next<T1>(), Next<T2>(), Next<T3>(), Next<T4>(), Next<T5>()); public static (T1, T2, T3, T4, T5, T6) Scan<T1, T2, T3, T4, T5, T6>() => (Next<T1>(), Next<T2>(), Next<T3>(), Next<T4>(), Next<T5>(), Next<T6>()); public static IEnumerable<T> ScanEnumerable<T>() => Console.ReadLine().Trim().Split(" ").Select(x => (T)Convert.ChangeType(x, typeof(T))); } } }
37.236111
158
0.473704
[ "CC0-1.0" ]
AconCavy/AtCoder.Tasks.CS
Other/CODE-FORMULA-2014-QUALA/Tasks/B.cs
2,681
C#
using System; using System.Collections.Generic; using System.Text; namespace Stategram.Attributes { public class AcceptCallbacksAttribute : Attribute { } }
15.454545
53
0.747059
[ "MIT" ]
swifteg/Stategram
Stategram/Attributes/AcceptCallbacksAttribute.cs
172
C#
/* * 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 inspector-2016-02-16.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.Inspector.Model { /// <summary> /// Container for the parameters to the GetExclusionsPreview operation. /// Retrieves the exclusions preview (a list of ExclusionPreview objects) specified by /// the preview token. You can obtain the preview token by running the CreateExclusionsPreview /// API. /// </summary> public partial class GetExclusionsPreviewRequest : AmazonInspectorRequest { private string _assessmentTemplateArn; private Locale _locale; private int? _maxResults; private string _nextToken; private string _previewToken; /// <summary> /// Gets and sets the property AssessmentTemplateArn. /// <para> /// The ARN that specifies the assessment template for which the exclusions preview was /// requested. /// </para> /// </summary> public string AssessmentTemplateArn { get { return this._assessmentTemplateArn; } set { this._assessmentTemplateArn = value; } } // Check to see if AssessmentTemplateArn property is set internal bool IsSetAssessmentTemplateArn() { return this._assessmentTemplateArn != null; } /// <summary> /// Gets and sets the property Locale. /// <para> /// The locale into which you want to translate the exclusion's title, description, and /// recommendation. /// </para> /// </summary> public Locale Locale { get { return this._locale; } set { this._locale = value; } } // Check to see if Locale property is set internal bool IsSetLocale() { return this._locale != null; } /// <summary> /// Gets and sets the property MaxResults. /// <para> /// You can use this parameter to indicate the maximum number of items you want in the /// response. The default value is 100. The maximum value is 500. /// </para> /// </summary> public int MaxResults { get { return this._maxResults.GetValueOrDefault(); } set { this._maxResults = value; } } // Check to see if MaxResults property is set internal bool IsSetMaxResults() { return this._maxResults.HasValue; } /// <summary> /// Gets and sets the property NextToken. /// <para> /// You can use this parameter when paginating results. Set the value of this parameter /// to null on your first call to the GetExclusionsPreviewRequest action. Subsequent calls /// to the action fill nextToken in the request with the value of nextToken from the previous /// response to continue listing data. /// </para> /// </summary> public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } /// <summary> /// Gets and sets the property PreviewToken. /// <para> /// The unique identifier associated of the exclusions preview. /// </para> /// </summary> public string PreviewToken { get { return this._previewToken; } set { this._previewToken = value; } } // Check to see if PreviewToken property is set internal bool IsSetPreviewToken() { return this._previewToken != null; } } }
32.70922
107
0.605811
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/Inspector/Generated/Model/GetExclusionsPreviewRequest.cs
4,612
C#
using Microsoft.AspNetCore.Mvc; using Portray.Models; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Portray.Hosts.WebApp.Controllers { [Route("api/[controller]")] public class AllocationController : Controller { private readonly IEnumerable<Instrument> _instruments = new List<Instrument> { new Instrument("child1") { Allocations = new List<Allocation> { new Allocation(new Instrument("child1-1") { AssetClassAllocations = new List<AssetClassAllocation> { new AssetClassAllocation(AssetClassCode.Equities, 0.42), new AssetClassAllocation(AssetClassCode.FixedIncome, 0.58) } }, 0.3), new Allocation(new Instrument("child1-2") { AssetClassAllocations = new List<AssetClassAllocation> { new AssetClassAllocation(AssetClassCode.Equities, 0.78), new AssetClassAllocation(AssetClassCode.FixedIncome, 0.22) } }, 0.7), } }, new Instrument("child2") { Allocations = new List<Allocation> { new Allocation(new Instrument("child2-1") { AssetClassAllocations = new List<AssetClassAllocation> { new AssetClassAllocation(AssetClassCode.Equities, 0.37), new AssetClassAllocation(AssetClassCode.FixedIncome, 0.63) } }, 0.4), new Allocation(new Instrument("child2-2") { AssetClassAllocations = new List<AssetClassAllocation> { new AssetClassAllocation(AssetClassCode.Equities, 0.12), new AssetClassAllocation(AssetClassCode.FixedIncome, 0.88) } }, 0.6), } }, new Instrument("child3") { AssetClassAllocations = new List<AssetClassAllocation> { new AssetClassAllocation(AssetClassCode.Equities, 0.51), new AssetClassAllocation(AssetClassCode.FixedIncome, 0.49) } } }; [HttpPost] public async Task<IActionResult> GetAllocationsAsync([FromBody] IEnumerable<AllocationVm> allocationVms) { var instrument = new Instrument("") { Allocations = allocationVms.Select(a => new Allocation( _instruments.SingleOrDefault(i => i.Symbol == a.Symbol), a.Weight)).ToList() }; return Ok(new AllocationOutputVm { AssetClassAllocations = instrument.GetAssetClassAllocations(), SectorAllocations = instrument.GetSectorAllocations(), GeographicAllocations = instrument.GetGeographicAllocations() }); } } public class AllocationOutputVm { public IEnumerable<AssetClassAllocation> AssetClassAllocations { get; set; } public IEnumerable<SectorAllocation> SectorAllocations { get; set; } public IEnumerable<GeographicAllocation> GeographicAllocations { get; set; } } public class AllocationVm { public string Symbol { get; set; } public double Weight { get; set; } } }
38.34
112
0.510694
[ "MIT" ]
AmbroiseCouissin/portray
Portray/Portray.Hosts.WebApp/Controllers/AllocationController.cs
3,836
C#
// Instance generated by TankLibHelper.InstanceBuilder // ReSharper disable All namespace TankLib.STU.Types { [STUAttribute(0xCB3B66C7)] public class STU_CB3B66C7 : STU_CCDF50E7 { } }
21.888889
54
0.746193
[ "MIT" ]
Mike111177/OWLib
TankLib/STU/Types/STU_CB3B66C7.cs
197
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801 { using static Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Extensions; /// <summary> /// The list of user assigned identities associated with the resource. The user identity dictionary key references will be /// ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName} /// </summary> public partial class ManagedServiceIdentityUserAssignedIdentities { /// <summary> /// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json); /// <summary> /// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject" /// /> before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject container); /// <summary> /// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of /// the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> /// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return /// instantly.</param> partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json, ref bool returnNow); /// <summary> /// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the /// object before it is serialized. /// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject container, ref bool returnNow); /// <summary> /// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IManagedServiceIdentityUserAssignedIdentities. /// </summary> /// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode" /> to deserialize from.</param> /// <returns> /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IManagedServiceIdentityUserAssignedIdentities. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IManagedServiceIdentityUserAssignedIdentities FromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode node) { return node is Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json ? new ManagedServiceIdentityUserAssignedIdentities(json) : null; } /// <summary> /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject into a new instance of <see cref="ManagedServiceIdentityUserAssignedIdentities" /// />. /// </summary> /// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject instance to deserialize from.</param> /// <param name="exclusions"></param> internal ManagedServiceIdentityUserAssignedIdentities(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet<string> exclusions = null) { bool returnNow = false; BeforeFromJson(json, ref returnNow); if (returnNow) { return; } Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.IAssociativeArray<Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IComponents1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties>)this).AdditionalProperties, null ,exclusions ); AfterFromJson(json); } /// <summary> /// Serializes this instance of <see cref="ManagedServiceIdentityUserAssignedIdentities" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode" /// />. /// </summary> /// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller /// passes in <c>null</c>, a new instance will be created and returned to the caller.</param> /// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode"/>.</param> /// <returns> /// a serialized instance of <see cref="ManagedServiceIdentityUserAssignedIdentities" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode" /// />. /// </returns> public Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode serializationMode) { container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject(); bool returnNow = false; BeforeToJson(ref container, ref returnNow); if (returnNow) { return container; } Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.IAssociativeArray<Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IComponents1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties>)this).AdditionalProperties, container); AfterToJson(ref container); return container; } } }
71.046296
384
0.706764
[ "MIT" ]
Arsasana/azure-powershell
src/Functions/generated/api/Models/Api20190801/ManagedServiceIdentityUserAssignedIdentities.json.cs
7,566
C#
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.Test.DocumentationRules { using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Helpers; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using StyleCop.Analyzers.DocumentationRules; using TestHelper; using Xunit; /// <summary> /// This class contains unit tests for <see cref="SA1607PartialElementDocumentationMustHaveSummaryText"/>. /// </summary> public class SA1607UnitTests : DiagnosticVerifier { [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] public async Task TestTypeNoDocumentationAsync(string typeName) { var testCode = @" partial {0} TypeName {{ }}"; await this.VerifyCSharpDiagnosticAsync(string.Format(testCode, typeName), EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] public async Task TestTypeWithSummaryDocumentationAsync(string typeName) { var testCode = @" /// <summary> /// Foo /// </summary> partial {0} TypeName {{ }}"; await this.VerifyCSharpDiagnosticAsync(string.Format(testCode, typeName), EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] public async Task TestTypeWithContentDocumentationAsync(string typeName) { var testCode = @" /// <content> /// Foo /// </content> partial {0} TypeName {{ }}"; await this.VerifyCSharpDiagnosticAsync(string.Format(testCode, typeName), EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] public async Task TestTypeWithInheritedDocumentationAsync(string typeName) { var testCode = @" /// <inheritdoc/> partial {0} TypeName {{ }}"; await this.VerifyCSharpDiagnosticAsync(string.Format(testCode, typeName), EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] public async Task TestTypeWithoutSummaryDocumentationAsync(string typeName) { var testCode = @" /// <summary> /// /// </summary> partial {0} TypeName {{ }}"; DiagnosticResult expected = this.CSharpDiagnostic().WithLocation(6, 1); await this.VerifyCSharpDiagnosticAsync(string.Format(testCode, typeName), expected, CancellationToken.None).ConfigureAwait(false); } [Theory] [InlineData("enum")] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] public async Task TestNonPartialTypeWithoutSummaryDocumentationAsync(string typeName) { var testCode = @" /// <summary> /// /// </summary> {0} TypeName {{ }}"; await this.VerifyCSharpDiagnosticAsync(string.Format(testCode, typeName), EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] public async Task TestTypeWithoutContentDocumentationAsync(string typeName) { var testCode = @" /// <content> /// /// </content> partial {0} TypeName {{ }}"; DiagnosticResult expected = this.CSharpDiagnostic().WithLocation(6, 1); await this.VerifyCSharpDiagnosticAsync(string.Format(testCode, typeName), expected, CancellationToken.None).ConfigureAwait(false); } [Theory] [InlineData("enum")] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] public async Task TestNonPartialTypeWithoutContentDocumentationAsync(string typeName) { var testCode = @" /// <content> /// /// </content> {0} TypeName {{ }}"; await this.VerifyCSharpDiagnosticAsync(string.Format(testCode, typeName), EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestMethodNoDocumentationAsync() { var testCode = @" /// <summary> /// Foo /// </summary> public partial class ClassName { partial void Test(); }"; await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestMethodWithSummaryDocumentationAsync() { var testCode = @" /// <summary> /// Foo /// </summary> public partial class ClassName { /// <summary> /// Foo /// </summary> partial void Test(); }"; await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestMethodWithContentDocumentationAsync() { var testCode = @" /// <summary> /// Foo /// </summary> public partial class ClassName { /// <content> /// Foo /// </content> partial void Test(); }"; await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestMethodWithInheritedDocumentationAsync() { var testCode = @" /// <summary> /// Foo /// </summary> public partial class ClassName { /// <inheritdoc/> partial void Test(); }"; await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestMethodWithoutSummaryDocumentationAsync() { var testCode = @" /// <summary> /// Foo /// </summary> public partial class ClassName { /// <summary> /// /// </summary> partial void Test(); }"; DiagnosticResult expected = this.CSharpDiagnostic().WithLocation(10, 18); await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestNonPartialMethodWithoutSummaryDocumentationAsync() { var testCode = @" /// <summary> /// Foo /// </summary> public partial class ClassName { /// <summary> /// /// </summary> public void Test() { } }"; await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestMethodWithoutContentDocumentationAsync() { var testCode = @" /// <summary> /// Foo /// </summary> public partial class ClassName { /// <content> /// /// </content> partial void Test(); }"; DiagnosticResult expected = this.CSharpDiagnostic().WithLocation(10, 18); await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestNonPartialMethodWithoutContentDocumentationAsync() { var testCode = @" /// <summary> /// Foo /// </summary> public partial class ClassName { /// <content> /// /// </content> public void Test() { } }"; await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestIncludedDocumentationWithoutSummaryOrContentAsync() { var testCode = @" /// <summary> /// Foo /// </summary> public partial class ClassName { /// <include file='MethodWithoutSummaryOrContent.xml' path='/ClassName/Test/*'/> partial void Test(); }"; await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestIncludedDocumentationWithEmptySummaryAsync() { var testCode = @" /// <summary> /// Foo /// </summary> public partial class ClassName { /// <include file='MethodWithEmptySummary.xml' path='/ClassName/Test/*'/> partial void Test(); }"; var expected = this.CSharpDiagnostic().WithLocation(8, 18); await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestIncludedDocumentationWithEmptyContentAsync() { var testCode = @" /// <summary> /// Foo /// </summary> public partial class ClassName { /// <include file='MethodWithEmptyContent.xml' path='/ClassName/Test/*'/> partial void Test(); }"; var expected = this.CSharpDiagnostic().WithLocation(8, 18); await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestIncludedDocumentationWithInheritdocAsync() { var testCode = @" /// <summary> /// Foo /// </summary> public partial class ClassName { /// <include file='MethodWithInheritdoc.xml' path='/ClassName/Test/*'/> partial void Test(); }"; await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestIncludedDocumentationWithSummaryAsync() { var testCode = @" /// <summary> /// Foo /// </summary> public partial class ClassName { /// <include file='MethodWithSummary.xml' path='/ClassName/Test/*'/> partial void Test(); }"; await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestIncludedDocumentationWithContentAsync() { var testCode = @" /// <summary> /// Foo /// </summary> public partial class ClassName { /// <include file='MethodWithContent.xml' path='/ClassName/Test/*'/> partial void Test(); }"; await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } /// <inheritdoc/> protected override Project ApplyCompilationOptions(Project project) { var resolver = new TestXmlReferenceResolver(); string contentWithoutSummaryOrContent = @"<?xml version=""1.0"" encoding=""utf-8"" ?> <ClassName> <Test> </Test> </ClassName> "; resolver.XmlReferences.Add("MethodWithoutSummaryOrContent.xml", contentWithoutSummaryOrContent); string contentWithEmptySummary = @"<?xml version=""1.0"" encoding=""utf-8"" ?> <ClassName> <Test> <summary> </summary> </Test> </ClassName> "; resolver.XmlReferences.Add("MethodWithEmptySummary.xml", contentWithEmptySummary); string contentWithEmptyContent = @"<?xml version=""1.0"" encoding=""utf-8"" ?> <ClassName> <Test> <content> </content> </Test> </ClassName> "; resolver.XmlReferences.Add("MethodWithEmptyContent.xml", contentWithEmptyContent); string contentWithInheritdoc = @"<?xml version=""1.0"" encoding=""utf-8"" ?> <ClassName> <Test> <inheritdoc/> </Test> </ClassName> "; resolver.XmlReferences.Add("MethodWithInheritdoc.xml", contentWithInheritdoc); string contentWithSummary = @"<?xml version=""1.0"" encoding=""utf-8"" ?> <ClassName> <Test> <summary> Foo </summary> </Test> </ClassName> "; resolver.XmlReferences.Add("MethodWithSummary.xml", contentWithSummary); string contentWithContent = @"<?xml version=""1.0"" encoding=""utf-8"" ?> <ClassName> <Test> <content> Foo </content> </Test> </ClassName> "; resolver.XmlReferences.Add("MethodWithContent.xml", contentWithContent); project = base.ApplyCompilationOptions(project); project = project.WithCompilationOptions(project.CompilationOptions.WithXmlReferenceResolver(resolver)); return project; } protected override IEnumerable<DiagnosticAnalyzer> GetCSharpDiagnosticAnalyzers() { yield return new SA1607PartialElementDocumentationMustHaveSummaryText(); } } }
27.482979
156
0.637764
[ "Apache-2.0" ]
morsiu/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers.Test/DocumentationRules/SA1607UnitTests.cs
12,919
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Reactive; using Force.DeepCloner; using MessageCommunicator.TestGui.Data; using ReactiveUI; namespace MessageCommunicator.TestGui.ViewServices { public class ConnectionConfigControlViewModel : OwnViewModelBase { private string _validationError = string.Empty; private ConnectionParameters? _originalConnectionParameters; private IEnumerable<ConnectionParameters> _allConnectionParameters; public ConnectionParameters Model { get; } public ConnectionParametersViewModel ModelInteractive { get; } public ReactiveCommand<object?, Unit> Command_OK { get; } public ReactiveCommand<object?, Unit> Command_Cancel { get; } public ConnectionMode[] ConnectionModes => (ConnectionMode[])Enum.GetValues(typeof(ConnectionMode)); public string ValidationError { get => _validationError; set { if (_validationError != value) { _validationError = value; this.RaisePropertyChanged(nameof(this.ValidationError)); this.RaisePropertyChanged(nameof(this.IsValidationErrorVisible)); } } } public bool IsValidationErrorVisible => !string.IsNullOrEmpty(this.ValidationError); public ConnectionConfigControlViewModel(ConnectionParameters? parameters, IEnumerable<ConnectionParameters> allConnectionParameters) { this.Model = parameters != null ? parameters.DeepClone() : new ConnectionParameters(); this.ModelInteractive = new ConnectionParametersViewModel(this.Model); this.Command_OK = ReactiveCommand.Create<object?>(this.OnCommandOK); this.Command_Cancel = ReactiveCommand.Create<object?>( arg => this.CloseWindow(null)); _originalConnectionParameters = parameters; _allConnectionParameters = allConnectionParameters; } private void OnCommandOK(object? arg) { var model = this.Model; // Perform validation this.ValidationError = string.Empty; try { Validator.ValidateObject(this.ModelInteractive, new ValidationContext(this.ModelInteractive), true); Validator.ValidateObject(model.ByteStreamSettings, new ValidationContext(model.ByteStreamSettings), true); Validator.ValidateObject(model.RecognizerSettings, new ValidationContext(model.RecognizerSettings), true); } catch (ValidationException e) { this.ValidationError = e.Message; return; } // Check for duplicate name foreach (var actOtherConnection in _allConnectionParameters) { if(actOtherConnection == _originalConnectionParameters){ continue; } if (actOtherConnection.Name.Trim() == this.Model.Name.Trim()) { this.ValidationError = $"The name '{actOtherConnection.Name}' is already in use!"; return; } } this.CloseWindow(model); } } }
37.177778
140
0.632995
[ "MIT" ]
Pinny93/MessageCommunicator
MessageCommunicator.TestGui/ViewServices/_ConnectionConfigControl/ConnectionConfigControlViewModel.cs
3,348
C#
using System.Threading.Tasks; using MetaBoyTipBot.Configuration; using MetaBoyTipBot.Constants; using MetaBoyTipBot.Repositories; using MetaBoyTipBot.Services; using MetaBoyTipBot.TableEntities; using Microsoft.Extensions.Options; using Moq; using NUnit.Framework; using Telegram.Bot.Types; using Telegram.Bot.Types.ReplyMarkups; namespace MetaBoyTipBot.Tests.Unit.Services { [TestFixture] public class TopUpServiceTests { private TopUpService _sut; private BotConfiguration _botConfigurationMock; private Mock<IBotService> _botServiceMock; private Mock<IWalletUserRepository> _walletUserRepositoryMock; [SetUp] public void BeforeEachTest() { _walletUserRepositoryMock = new Mock<IWalletUserRepository>(); _botServiceMock = new Mock<IBotService>(); _botConfigurationMock = new BotConfiguration(); var botConfigurationOptions = Options.Create(_botConfigurationMock); _sut = new TopUpService(botConfigurationOptions, _walletUserRepositoryMock.Object, _botServiceMock.Object); } [Test] public async Task ShouldInformUserToTopUpWhenExistingWallet() { var userId = 123; var userWalletAddress = "0x123"; var tipWalletAddress = "0x987"; _botConfigurationMock.TipWalletAddress = tipWalletAddress; var chat = new Chat { Id = 123546 }; _walletUserRepositoryMock.Setup(x => x.GetByUserId(userId)).Returns(new WalletUser(userWalletAddress, userId)); await _sut.Handle(chat, userId); _botServiceMock.Verify(x => x.SendTextMessage(chat.Id, string.Format(ReplyConstants.CurrentWallet, userWalletAddress), null), Times.Once); _botServiceMock.Verify(x => x.SendTextMessage(chat.Id, tipWalletAddress, null), Times.Once); _botServiceMock.Verify(x => x.ShowMainButtonMenu(chat.Id, null), Times.Once); _botServiceMock.VerifyNoOtherCalls(); } [Test] public async Task ShouldAskUserForWalletWhenNoExistingWallet() { var userId = 123; var chat = new Chat { Id = 123546 }; _walletUserRepositoryMock.Setup(x => x.GetByUserId(userId)).Returns((WalletUser) null); await _sut.Handle(chat, userId); _botServiceMock.Verify(x => x.SendTextMessage(chat.Id, ReplyConstants.EnterTopUpMetahashWallet, It.Is<ForceReplyMarkup>(x => !x.Selective)), Times.Once); _botServiceMock.VerifyNoOtherCalls(); } } }
38.597015
165
0.683295
[ "MIT" ]
jvanderbiest/MetaBoyTipBot
MetaBoyTipBot.Tests/Unit/Services/TopUpServiceTests.cs
2,588
C#
using System; using System.Collections.Generic; using System.Text; namespace Uno.Foundation.Interop { /// <summary> /// Marks a struct as an interop message for the <see cref="TSBindingsGenerator"/> TypeScript generator. /// </summary> [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)] public class TSInteropMessageAttribute : Attribute { } }
24.466667
105
0.757493
[ "Apache-2.0" ]
06needhamt/uno
src/Uno.Foundation/Interop/TSInteropMessageAttribute.wasm.cs
369
C#
using System; using System.Diagnostics; using System.Linq.Expressions; using System.Reflection; namespace iayos.DapperCRUD { /// <summary> /// How to use nice short type-safe property names on generic classes /// http://ivanz.com/2009/12/04/how-to-avoid-passing-property-names-as-strings-using-c-3-0-expression-trees/ /// </summary> public static class PropertyHelper { /// <summary> /// Get property name for an INSTANCE: /// e.g. /// User user = new User(); /// string propertyName = user.GetPropertyName (u =&gt; u.Email); /// </summary> /// <typeparam name="TObject"></typeparam> /// <param name="type"></param> /// <param name="propertyRefExpr"></param> /// <returns></returns> [DebuggerStepThrough] public static string GetPropertyName<TObject>(this TObject type, Expression<Func<TObject, object>> propertyRefExpr) { return GetPropertyNameCore(propertyRefExpr.Body); } /// <summary> /// Get property name for a TYPE: /// e.g. string propertyName = PropertyUtil.GetName&lt;User&gt; (u =&gt; u.Email); /// </summary> /// <typeparam name="TObject"></typeparam> /// <param name="propertyRefExpr"></param> /// <returns></returns> [DebuggerStepThrough] public static string GetName<TObject>(Expression<Func<TObject, object>> propertyRefExpr) { return GetPropertyNameCore(propertyRefExpr.Body); } /// <summary> /// Get property name for a TYPE: /// e.g. string propertyName = PropertyUtil.GetName&lt;User&gt; (u =&gt; u.Email); /// </summary> /// <typeparam name="TObject"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <param name="propertyRefExpr"></param> /// <returns></returns> [DebuggerStepThrough] public static string GetName<TObject, TProperty>(Expression<Func<TObject, TProperty>> propertyRefExpr) { return GetPropertyNameCore(propertyRefExpr.Body); } [DebuggerStepThrough] private static string GetPropertyNameCore(Expression propertyRefExpr) { if (propertyRefExpr == null) throw new ArgumentNullException("propertyRefExpr", "propertyRefExpr is null."); MemberExpression memberExpr = propertyRefExpr as MemberExpression; if (memberExpr == null) { UnaryExpression unaryExpr = propertyRefExpr as UnaryExpression; if (unaryExpr != null && unaryExpr.NodeType == ExpressionType.Convert) memberExpr = unaryExpr.Operand as MemberExpression; } if (memberExpr != null && memberExpr.Member.MemberType == MemberTypes.Property) return memberExpr.Member.Name; throw new ArgumentException("No property reference expression was found.", "propertyRefExpr"); } } }
31.890244
126
0.70631
[ "MIT" ]
daleholborow/iayos.DapperCRUD
src/iayos.DapperCRUD/PropertyHelper.cs
2,615
C#
using System.Linq.Dynamic.Core.Parser; using System.Linq.Expressions; using NFluent; using Xunit; namespace System.Linq.Dynamic.Core.Tests { public class ConstantExpressionWrapperTests { private readonly IConstantExpressionWrapper _constantExpressionWrapper; public ConstantExpressionWrapperTests() { _constantExpressionWrapper = new ConstantExpressionWrapper(); } [Theory] [InlineData(true)] [InlineData((int)1)] [InlineData((uint)2)] [InlineData((short)3)] [InlineData((ushort)4)] [InlineData(5L)] [InlineData(6UL)] [InlineData(7.1f)] [InlineData(8.1d)] [InlineData('c')] [InlineData((byte) 10)] [InlineData((sbyte) 11)] public void ConstantExpressionWrapper_Wrap_ConstantExpression_PrimitiveTypes<T>(T test) { // Assign var expression = Expression.Constant(test) as Expression; // Act _constantExpressionWrapper.Wrap(ref expression); // Verify Check.That(expression).IsNotNull(); var constantExpression = (expression as MemberExpression).Expression as ConstantExpression; dynamic wrappedObj = constantExpression.Value; T value = wrappedObj.Value; Check.That(value).IsEqualTo(test); } [Fact] public void ConstantExpressionWrapper_Wrap_ConstantExpression_String() { // Assign string test = "abc"; var expression = Expression.Constant(test) as Expression; // Act _constantExpressionWrapper.Wrap(ref expression); // Verify Check.That(expression).IsNotNull(); var constantExpression = (expression as MemberExpression).Expression as ConstantExpression; dynamic wrappedObj = constantExpression.Value; string value = wrappedObj.Value; Check.That(value).IsEqualTo(test); } [Fact] public void ConstantExpressionWrapper_Wrap_ConstantExpression_ComplexTypes() { // Assign var test = DateTime.Now; var expression = Expression.Constant(test) as Expression; // Act _constantExpressionWrapper.Wrap(ref expression); // Verify Check.That(expression).IsNotNull(); var constantExpression = (expression as MemberExpression).Expression as ConstantExpression; dynamic wrappedObj = constantExpression.Value; DateTime value = wrappedObj.Value; Check.That(value).IsEqualTo(test); } } }
29.521739
103
0.610825
[ "Apache-2.0" ]
akrisiun/System.Linq.Dynamic.Core
test/System.Linq.Dynamic.Core.Tests/ConstantExpressionWrapperTests.cs
2,718
C#
// Copyright 2009-2013 Matvei Stefarov <me@matvei.org> using System; using System.Globalization; using System.Text; using JetBrains.Annotations; namespace fCraft { // Helper methods for working with strings and for serialization/parsing static unsafe class FormatUtil { // Quicker StringBuilder.Append(int) by Sam Allen of http://www.dotnetperls.com [NotNull] public static StringBuilder Digits( [NotNull] this StringBuilder builder, int number ) { if( builder == null ) throw new ArgumentNullException( "builder" ); if( number >= 100000000 || number < 0 ) { // Use system ToString. builder.Append( number ); return builder; } int copy; int digit; if( number >= 10000000 ) { // 8. copy = number % 100000000; digit = copy / 10000000; builder.Append( (char)( digit + 48 ) ); } if( number >= 1000000 ) { // 7. copy = number % 10000000; digit = copy / 1000000; builder.Append( (char)( digit + 48 ) ); } if( number >= 100000 ) { // 6. copy = number % 1000000; digit = copy / 100000; builder.Append( (char)( digit + 48 ) ); } if( number >= 10000 ) { // 5. copy = number % 100000; digit = copy / 10000; builder.Append( (char)( digit + 48 ) ); } if( number >= 1000 ) { // 4. copy = number % 10000; digit = copy / 1000; builder.Append( (char)( digit + 48 ) ); } if( number >= 100 ) { // 3. copy = number % 1000; digit = copy / 100; builder.Append( (char)( digit + 48 ) ); } if( number >= 10 ) { // 2. copy = number % 100; digit = copy / 10; builder.Append( (char)( digit + 48 ) ); } if( number >= 0 ) { // 1. copy = number % 10; builder.Append( (char)( copy + 48 ) ); } return builder; } // Quicker Int32.Parse(string) by Karl Seguin public static int Parse( [NotNull] string stringToConvert ) { if( stringToConvert == null ) throw new ArgumentNullException( "stringToConvert" ); int value = 0; int length = stringToConvert.Length; fixed( char* characters = stringToConvert ) { for( int i = 0; i < length; ++i ) { value = 10 * value + ( characters[i] - 48 ); } } return value; } // UppercaseFirst by Sam Allen of http://www.dotnetperls.com [NotNull] public static string UppercaseFirst( this string s ) { if( string.IsNullOrEmpty( s ) ) { return string.Empty; } char[] a = s.ToCharArray(); a[0] = char.ToUpper( a[0] ); return new string( a ); } [NotNull] public static string ToStringInvariant( this int i ) { return i.ToString( CultureInfo.InvariantCulture ); } public static int IndexOfOrdinal( [NotNull] this string haystack, [NotNull] string needle ) { return haystack.IndexOf( needle, StringComparison.Ordinal ); } } }
34.222222
101
0.460498
[ "BSD-3-Clause" ]
AliDeym/Caznowl-Cube-Zombie
fCraft/Utils/FormatUtil.cs
3,698
C#
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ namespace System.ServiceModel.Discovery.Configuration { using System; using System.ComponentModel; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.Runtime; using System.ServiceModel.Configuration; using System.ServiceModel.Description; public class UdpDiscoveryEndpointElement : DiscoveryEndpointElement { ConfigurationPropertyCollection properties; public UdpDiscoveryEndpointElement() : base() { } [ConfigurationProperty(ConfigurationStrings.MaxResponseDelay, DefaultValue = DiscoveryDefaults.Udp.AppMaxDelayString)] [TypeConverter(typeof(TimeSpanOrInfiniteConverter))] [ServiceModelTimeSpanValidator(MinValueString = ConfigurationStrings.TimeSpanZero)] public new TimeSpan MaxResponseDelay { get { return base.MaxResponseDelay; } set { base.MaxResponseDelay = value; } } [ConfigurationProperty(ConfigurationStrings.DiscoveryMode, DefaultValue = ServiceDiscoveryMode.Adhoc)] [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule)] public new ServiceDiscoveryMode DiscoveryMode { get { return base.DiscoveryMode; } set { base.DiscoveryMode = value; } } [ConfigurationProperty(ConfigurationStrings.MulticastAddress, DefaultValue = ProtocolStrings.Udp.MulticastIPv4Address)] [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule)] public Uri MulticastAddress { get { return (Uri)base[ConfigurationStrings.MulticastAddress]; } set { if (value == null) { throw FxTrace.Exception.ArgumentNull("value"); } base[ConfigurationStrings.MulticastAddress] = value; } } [ConfigurationProperty(ConfigurationStrings.TransportSettings)] public UdpTransportSettingsElement TransportSettings { get { return (UdpTransportSettingsElement)base[ConfigurationStrings.TransportSettings]; } } protected internal override Type EndpointType { get { return typeof(UdpDiscoveryEndpoint); } } protected override ConfigurationPropertyCollection Properties { get { if (this.properties == null) { ConfigurationPropertyCollection properties = base.Properties; properties.Remove(ConfigurationStrings.DiscoveryMode); properties.Remove(ConfigurationStrings.MaxResponseDelay); properties.Add( new ConfigurationProperty( ConfigurationStrings.MaxResponseDelay, typeof(TimeSpan), DiscoveryDefaults.Udp.AppMaxDelay, new TimeSpanOrInfiniteConverter(), new TimeSpanOrInfiniteValidator(TimeSpan.Zero, TimeSpan.MaxValue), ConfigurationPropertyOptions.None)); properties.Add( new ConfigurationProperty( ConfigurationStrings.DiscoveryMode, typeof(ServiceDiscoveryMode), ServiceDiscoveryMode.Adhoc, null, null, ConfigurationPropertyOptions.None)); properties.Add( new ConfigurationProperty( ConfigurationStrings.MulticastAddress, typeof(Uri), UdpDiscoveryEndpoint.DefaultIPv4MulticastAddress, null, null, ConfigurationPropertyOptions.None)); properties.Add( new ConfigurationProperty( ConfigurationStrings.TransportSettings, typeof(UdpTransportSettingsElement), null, null, null, ConfigurationPropertyOptions.None)); this.properties = properties; } return this.properties; } } protected internal override ServiceEndpoint CreateServiceEndpoint(ContractDescription contractDescription) { return new UdpDiscoveryEndpoint(this.DiscoveryVersion, this.MulticastAddress); } protected internal override void InitializeFrom(ServiceEndpoint endpoint) { base.InitializeFrom(endpoint); UdpDiscoveryEndpoint source = (UdpDiscoveryEndpoint)endpoint; this.MaxResponseDelay = source.MaxResponseDelay; this.DiscoveryMode = source.DiscoveryMode; this.MulticastAddress = source.MulticastAddress; #pragma warning disable 0618 this.TransportSettings.InitializeFrom(source.TransportSettings); #pragma warning restore 0618 } protected override void OnInitializeAndValidate(ChannelEndpointElement channelEndpointElement) { base.OnInitializeAndValidate(channelEndpointElement); ConfigurationUtility.InitializeAndValidateUdpChannelEndpointElement(channelEndpointElement); } protected override void OnInitializeAndValidate(ServiceEndpointElement serviceEndpointElement) { base.OnInitializeAndValidate(serviceEndpointElement); ConfigurationUtility.InitializeAndValidateUdpServiceEndpointElement(serviceEndpointElement); } protected override void OnApplyConfiguration(ServiceEndpoint endpoint, ServiceEndpointElement serviceEndpointElement) { base.OnApplyConfiguration(endpoint, serviceEndpointElement); ApplyConfiguration(endpoint); } protected override void OnApplyConfiguration(ServiceEndpoint endpoint, ChannelEndpointElement serviceEndpointElement) { base.OnApplyConfiguration(endpoint, serviceEndpointElement); ApplyConfiguration(endpoint); } void ApplyConfiguration(ServiceEndpoint endpoint) { UdpDiscoveryEndpoint udpDiscoveryEndpoint = (UdpDiscoveryEndpoint)endpoint; udpDiscoveryEndpoint.MulticastAddress = this.MulticastAddress; #pragma warning disable 0618 this.TransportSettings.ApplyConfiguration(udpDiscoveryEndpoint.TransportSettings); #pragma warning restore 0618 } } }
37.117949
127
0.592705
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/cdf/src/NetFx40/System.ServiceModel.Discovery/System/ServiceModel/Discovery/Configuration/UdpDiscoveryEndpointElement.cs
7,238
C#
using System.Reflection; [assembly: AssemblyTitle("Expression Blend 2012 SortedResourcesPane Extension")] [assembly: AssemblyDescription("A Microsoft Expression Blend extension to automatically order the list of resources in the Resources pane.")]
50.8
142
0.811024
[ "Apache-2.0" ]
mhoyer/SortedResourcePane.Extension
SortedResourcePane.Blend2012/Properties/AssemblyInfo.cs
256
C#
#pragma checksum "..\..\App.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "D45EE6B304881A0C2F9608C746A532685867CCF2" //------------------------------------------------------------------------------ // <auto-generated> // 이 코드는 도구를 사용하여 생성되었습니다. // 런타임 버전:4.0.30319.42000 // // 파일 내용을 변경하면 잘못된 동작이 발생할 수 있으며, 코드를 다시 생성하면 // 이러한 변경 내용이 손실됩니다. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; using test; namespace test { /// <summary> /// App /// </summary> public partial class App : System.Windows.Application { /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { #line 5 "..\..\App.xaml" this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative); #line default #line hidden } /// <summary> /// Application Entry Point. /// </summary> [System.STAThreadAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public static void Main() { test.App app = new test.App(); app.InitializeComponent(); app.Run(); } } }
30.56338
118
0.602765
[ "Apache-2.0" ]
minji-o-j/Healing-Machine-with-BrainWave
test (2)/test/obj/Debug/App.g.cs
2,306
C#
// 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. #nullable disable using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { public abstract class AbstractCodeType : AbstractCodeMember, EnvDTE.CodeType { internal AbstractCodeType( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } internal AbstractCodeType( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } private SyntaxNode GetNamespaceOrTypeNode() { return LookupNode().Ancestors() .Where(n => CodeModelService.IsNamespace(n) || CodeModelService.IsType(n)) .FirstOrDefault(); } private SyntaxNode GetNamespaceNode() { return LookupNode().Ancestors() .Where(n => CodeModelService.IsNamespace(n)) .FirstOrDefault(); } internal INamedTypeSymbol LookupTypeSymbol() => (INamedTypeSymbol)LookupSymbol(); protected override object GetExtenderNames() => CodeModelService.GetTypeExtenderNames(); protected override object GetExtender(string name) => CodeModelService.GetTypeExtender(name, this); public override object Parent { get { var containingNamespaceOrType = GetNamespaceOrTypeNode(); return containingNamespaceOrType != null ? FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(containingNamespaceOrType) : this.FileCodeModel; } } public override EnvDTE.CodeElements Children { get { return UnionCollection.Create(this.State, this, (ICodeElements)this.Attributes, (ICodeElements)InheritsImplementsCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey), (ICodeElements)this.Members); } } public EnvDTE.CodeElements Bases { get { return BasesCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey, interfaces: false); } } public EnvDTE80.vsCMDataTypeKind DataTypeKind { get { return CodeModelService.GetDataTypeKind(LookupNode(), (INamedTypeSymbol)LookupSymbol()); } set { UpdateNode(FileCodeModel.UpdateDataTypeKind, value); } } public EnvDTE.CodeElements DerivedTypes { get { throw new NotImplementedException(); } } public EnvDTE.CodeElements ImplementedInterfaces { get { return BasesCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey, interfaces: true); } } public EnvDTE.CodeElements Members { get { return TypeCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey); } } public EnvDTE.CodeNamespace Namespace { get { var namespaceNode = GetNamespaceNode(); return namespaceNode != null ? FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeNamespace>(namespaceNode) : null; } } /// <returns>True if the current type inherits from or equals the type described by the /// given full name.</returns> /// <remarks>Equality is included in the check as per Dev10 Bug #725630</remarks> public bool get_IsDerivedFrom(string fullName) { var currentType = LookupTypeSymbol(); if (currentType == null) { return false; } var baseType = GetSemanticModel().Compilation.GetTypeByMetadataName(fullName); if (baseType == null) { return false; } return currentType.InheritsFromOrEquals(baseType); } public override bool IsCodeType { get { return true; } } public void RemoveMember(object element) { // Is this an EnvDTE.CodeElement that we created? If so, try to get the underlying code element object. var abstractCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element); if (abstractCodeElement == null) { if (element is EnvDTE.CodeElement codeElement) { // Is at least an EnvDTE.CodeElement? If so, try to retrieve it from the Members collection by name. // Note: This might throw an ArgumentException if the name isn't found in the collection. abstractCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.Members.Item(codeElement.Name)); } else if (element is string or int) { // Is this a string or int? If so, try to retrieve it from the Members collection. Again, this will // throw an ArgumentException if the name or index isn't found in the collection. abstractCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.Members.Item(element)); } } if (abstractCodeElement == null) { throw new ArgumentException(ServicesVSResources.Element_is_not_valid, nameof(element)); } abstractCodeElement.Delete(); } public EnvDTE.CodeElement AddBase(object @base, object position) { return FileCodeModel.EnsureEditor(() => { FileCodeModel.AddBase(LookupNode(), @base, position); var codeElements = this.Bases as ICodeElements; var hr = codeElements.Item(1, out var element); if (ErrorHandler.Succeeded(hr)) { return element; } return null; }); } public EnvDTE.CodeInterface AddImplementedInterface(object @base, object position) { return FileCodeModel.EnsureEditor(() => { var name = FileCodeModel.AddImplementedInterface(LookupNode(), @base, position); var codeElements = this.ImplementedInterfaces as ICodeElements; var hr = codeElements.Item(name, out var element); if (ErrorHandler.Succeeded(hr)) { return element as EnvDTE.CodeInterface; } return null; }); } public void RemoveBase(object element) { FileCodeModel.EnsureEditor(() => { FileCodeModel.RemoveBase(LookupNode(), element); }); } public void RemoveInterface(object element) { FileCodeModel.EnsureEditor(() => { FileCodeModel.RemoveImplementedInterface(LookupNode(), element); }); } } }
33.112903
133
0.572577
[ "MIT" ]
AlexanderSemenyak/roslyn
src/VisualStudio/Core/Impl/CodeModel/InternalElements/AbstractCodeType.cs
8,214
C#
using Namotion.Storage; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Namotion.Messaging.Storage.Internal { internal class BlobMessagePublisher<T> : MessagePublisher<T> { internal const string StorageKey = "Namotion.Messaging.Storage.Key"; internal const int StorageKeyLength = 67; private readonly IBlobContainer _blobContainer; private readonly int _maxMessageSize; public BlobMessagePublisher(IMessagePublisher messagePublisher, IBlobContainer blobContainer, int maxMessageSize) : base(messagePublisher) { _blobContainer = blobContainer; _maxMessageSize = maxMessageSize; } public override async Task PublishAsync(IEnumerable<Message> messages, CancellationToken cancellationToken = default) { messages = await Task.WhenAll(messages // TODO: Use batches here .Select(message => { if (message.Content.Length > _maxMessageSize) { return Task.Run(async () => { var key = Guid.NewGuid().ToString(); using (var stream = await _blobContainer.OpenWriteAsync(key, cancellationToken)) { await stream.WriteAsync(message.Content, 0, message.Content.Length); var content = Encoding.UTF8.GetBytes(StorageKey + ":" + key); return new Message(message.Id, content, message.Properties, message.SystemProperties, message.PartitionId); } }); } else { return Task.FromResult(message); } })); await base.PublishAsync(messages, cancellationToken); } } }
38.314815
139
0.555824
[ "MIT" ]
RicoSuter/Namotion.Messaging
src/Namotion.Messaging.Storage/Internal/BlobMessagePublisher.cs
2,071
C#
using System; using System.Collections; using System.Collections.Generic; /// <summary> /// <para>A dynamic type implementation for JavaScript style objects and primitives in Unity C# (with no System.dynamic support) /// /// Implements some functionality of a dynamic type with the class JSObject since Unity does not support dynamic types. /// Designed to work with JSONParser (JSONObject parser specifically) as is, but is expandable. /// /// Supports string, float, int, bool, List{JSObject} and List{string, JSObject}. Doubles are automatically converted to floats. Nests infinitely. </para> /// <para>Usage: </para> /// <para>Values or references can be directly assigned from or to this JSObject object. Loosely typed, so most cast errors only show up at run time as an exception. </para> /// <para> JSObject d = "squid"; </para> /// <para> string s = d; //No cast necessary </para> /// <para> d = 1; //Converted to int </para> /// <para> s = (d + 4) % 5; //Supports standard math and string operations + - * / % and +(concat) </para> /// <para> float f = d * 5; //and type conversions </para> /// <para> Console.Write(d.ToString()); //Unfortunately ToString() is necessary due to a C# bug in Console. Other uses, like Debug.Log(d), Debug.Write(d), work perfectly. </para> /// /// <para> Some common methods and properties are implemented for List and Dictionary. The rest can be accessed by assigning it to a correct type reference. </para> /// <para> JSObject d = new Dictionary{string, JSObject}(); </para> /// <para> d.Add("key", new List{JSObject}); </para> /// <para> d["key"].Count; //0 Gets the Count for the list </para> /// <para> d.ContainsKey("key"); //true </para> /// <para> d["key"] = 15; //Converts the list in the dictionary to int with value 15 </para> /// /// <para> Dictionary{string, JSObject}.KeyCollection keys = d.Keys; //Gets the usual list of keys </para> /// <para> Dictionary{string, JSObject} dict = d; //Gets the actual dictionary </para> /// <para> //Additional methods available after conversion </para> /// </summary> public class JSObject : IEnumerable { enum Type { UNKNOWN, STRING, FLOAT, INT, BOOL, LIST, DICTIONARY, DOUBLE } private Type type; private readonly string stringValue; private readonly float floatValue; private readonly int intValue; private readonly bool boolValue; private readonly List<JSObject> listValue; private readonly Dictionary<string, JSObject> dictionaryValue; //Constructors public JSObject(double value) { type = Type.DOUBLE; floatValue = (float)value; } public JSObject(string value) { type = Type.STRING; stringValue = value; } public JSObject(int value) { type = Type.INT; intValue = value; } public JSObject(float value) { type = Type.FLOAT; floatValue = value; } public JSObject(bool value) { type = Type.BOOL; boolValue = value; } public JSObject(List<JSObject> value) { type = Type.LIST; listValue = value; } public JSObject(Dictionary<string, JSObject> value) { type = Type.DICTIONARY; dictionaryValue = value; } //Implicit setters public static implicit operator JSObject(double value) { return new JSObject(value); } public static implicit operator JSObject(string value) { return new JSObject(value); } public static implicit operator JSObject(float value) { return new JSObject(value); } public static implicit operator JSObject(int value) { return new JSObject(value); } public static implicit operator JSObject(bool value) { return new JSObject(value); } public static implicit operator JSObject(List<JSObject> value) { return new JSObject(value); } public static implicit operator JSObject(Dictionary<string, JSObject> value) { return new JSObject(value); } //Implicit getters public static implicit operator string (JSObject v) { if (v.type == Type.STRING) return v.stringValue; else if (v.type == Type.FLOAT || v.type == Type.DOUBLE) return v.floatValue.ToString(); else if (v.type == Type.INT) return v.intValue.ToString(); else if (v.type == Type.BOOL) return v.boolValue.ToString(); else throw new InvalidCastException(); } public static implicit operator float (JSObject v) { if (v.type == Type.FLOAT || v.type == Type.DOUBLE) return v.floatValue; else if (v.type == Type.INT) return v.intValue; else throw new InvalidCastException(); } public static implicit operator int (JSObject v) { if (v.type == Type.INT) return v.intValue; else throw new InvalidCastException(); } public static implicit operator bool (JSObject v) { if (v.type == Type.BOOL) return v.boolValue; else throw new InvalidCastException(); } public static implicit operator List<JSObject>(JSObject v) { if (v.type == Type.LIST) return v.listValue; else throw new InvalidCastException(); } public static implicit operator Dictionary<string, JSObject>(JSObject v) { if (v.type == Type.DICTIONARY) return v.dictionaryValue; else throw new InvalidCastException(); } //Operators override public static JSObject operator +(JSObject first, JSObject second) { if (first.type == Type.INT && second.type == Type.INT) { return new JSObject(first.intValue + second.intValue); } else if ((first.type == Type.FLOAT || first.type == Type.DOUBLE) && (second.type == Type.FLOAT || second.type == Type.DOUBLE)) { return new JSObject(first.floatValue + second.floatValue); } else if (first.type == Type.INT && (second.type == Type.FLOAT || second.type == Type.DOUBLE)) { return new JSObject(first.intValue + second.floatValue); } else if ((first.type == Type.FLOAT || first.type == Type.DOUBLE) && second.type == Type.INT) { return new JSObject(first.floatValue + second.intValue); } else if (first.type == Type.STRING || second.type == Type.STRING) { return first.ToString() + second.ToString(); } else { throw new ArgumentException("Incompatible types"); } } public static JSObject operator -(JSObject first, JSObject second) { if (first.type == Type.INT && second.type == Type.INT) { return new JSObject(first.intValue - second.intValue); } else if ((first.type == Type.FLOAT || first.type == Type.DOUBLE) && (second.type == Type.FLOAT || second.type == Type.DOUBLE)) { return new JSObject(first.floatValue - second.floatValue); } else if (first.type == Type.INT && (second.type == Type.FLOAT || second.type == Type.DOUBLE)) { return new JSObject(first.intValue - second.floatValue); } else if ((first.type == Type.FLOAT || first.type == Type.DOUBLE) && second.type == Type.INT) { return new JSObject(first.floatValue - second.intValue); } else { throw new ArgumentException("Incompatible types"); } } public static JSObject operator *(JSObject first, JSObject second) { if (first.type == Type.INT && second.type == Type.INT) { return new JSObject(first.intValue * second.intValue); } else if ((first.type == Type.FLOAT || first.type == Type.DOUBLE) && (second.type == Type.FLOAT || second.type == Type.DOUBLE)) { return new JSObject(first.floatValue * second.floatValue); } else if (first.type == Type.INT && (second.type == Type.FLOAT || second.type == Type.DOUBLE)) { return new JSObject(first.intValue * second.floatValue); } else if ((first.type == Type.FLOAT || first.type == Type.DOUBLE) && second.type == Type.INT) { return new JSObject(first.floatValue * second.intValue); } else { throw new ArgumentException("Incompatible types"); } } public static JSObject operator /(JSObject first, JSObject second) { if (first.type == Type.INT && second.type == Type.INT) { return new JSObject(first.intValue / second.intValue); } else if ((first.type == Type.FLOAT || first.type == Type.DOUBLE) && (second.type == Type.FLOAT || second.type == Type.DOUBLE)) { return new JSObject(first.floatValue / second.floatValue); } else if (first.type == Type.INT && (second.type == Type.FLOAT || second.type == Type.DOUBLE)) { return new JSObject(first.intValue / second.floatValue); } else if ((first.type == Type.FLOAT || first.type == Type.DOUBLE) && second.type == Type.INT) { return new JSObject(first.floatValue / second.intValue); } else { throw new ArgumentException("Incompatible types"); } } public static JSObject operator %(JSObject first, JSObject second) { if (first.type == Type.INT && second.type == Type.INT) { return new JSObject(first.intValue % second.intValue); } else { throw new ArgumentException("Incompatible types"); } } public static JSObject operator >(JSObject first, JSObject second) { if (first.type == Type.INT && second.type == Type.INT) { return first.intValue > second.intValue; } else if ((first.type == Type.FLOAT || first.type == Type.DOUBLE) && (second.type == Type.FLOAT || second.type == Type.DOUBLE)) { return first.floatValue > second.floatValue; } else if (first.type == Type.INT && (second.type == Type.FLOAT || second.type == Type.DOUBLE)) { return first.intValue > second.floatValue; } else if ((first.type == Type.FLOAT || first.type == Type.DOUBLE) && second.type == Type.INT) { return first.floatValue > second.intValue; } else { throw new ArgumentException("Incompatible types"); } } public static JSObject operator <(JSObject first, JSObject second) { if (first.type == Type.INT && second.type == Type.INT) { return first.intValue < second.intValue; } else if ((first.type == Type.FLOAT || first.type == Type.DOUBLE) && (second.type == Type.FLOAT || second.type == Type.DOUBLE)) { return first.floatValue < second.floatValue; } else if (first.type == Type.INT && (second.type == Type.FLOAT || second.type == Type.DOUBLE)) { return first.intValue < second.floatValue; } else if ((first.type == Type.FLOAT || first.type == Type.DOUBLE) && second.type == Type.INT) { return first.floatValue < second.intValue; } else { throw new ArgumentException("Incompatible types"); } } public static JSObject operator >=(JSObject first, JSObject second) { if (first.type == Type.INT && second.type == Type.INT) { return first.intValue >= second.intValue; } else if ((first.type == Type.FLOAT || first.type == Type.DOUBLE) && (second.type == Type.FLOAT || second.type == Type.DOUBLE)) { return first.floatValue >= second.floatValue; } else if (first.type == Type.INT && (second.type == Type.FLOAT || second.type == Type.DOUBLE)) { return first.intValue >= second.floatValue; } else if ((first.type == Type.FLOAT || first.type == Type.DOUBLE) && second.type == Type.INT) { return first.floatValue >= second.intValue; } else { throw new ArgumentException("Incompatible types"); } } public static JSObject operator <=(JSObject first, JSObject second) { if (first.type == Type.INT && second.type == Type.INT) { return first.intValue <= second.intValue; } else if ((first.type == Type.FLOAT || first.type == Type.DOUBLE) && (second.type == Type.FLOAT || second.type == Type.DOUBLE)) { return first.floatValue <= second.floatValue; } else if (first.type == Type.INT && (second.type == Type.FLOAT || second.type == Type.DOUBLE)) { return first.intValue <= second.floatValue; } else if ((first.type == Type.FLOAT || first.type == Type.DOUBLE) && second.type == Type.INT) { return first.floatValue <= second.intValue; } else { throw new ArgumentException("Incompatible types"); } } public static JSObject operator ==(JSObject first, JSObject second) { if (first.type != second.type) { return false; } else { switch (first.type) { case Type.STRING: return first.stringValue == second.stringValue; case Type.FLOAT: return first.floatValue == second.floatValue; case Type.INT: return first.intValue == second.intValue; case Type.BOOL: return first.boolValue == second.boolValue; case Type.LIST: return first.listValue == second.listValue; case Type.DICTIONARY: return first.dictionaryValue == second.dictionaryValue; default: return false; } } } public static JSObject operator !=(JSObject first, JSObject second) { if (first.type != second.type) { return true; } else { switch (first.type) { case Type.STRING: return first.stringValue != second.stringValue; case Type.FLOAT: return first.floatValue != second.floatValue; case Type.INT: return first.intValue != second.intValue; case Type.BOOL: return first.boolValue != second.boolValue; case Type.LIST: return first.listValue != second.listValue; case Type.DICTIONARY: return first.dictionaryValue != second.dictionaryValue; default: return false; } } } public static JSObject operator &(JSObject first, JSObject second) { if (first.type == Type.BOOL && second.type == Type.BOOL) { return first.boolValue && second.boolValue; } else { throw new ArgumentException("Incompatible types"); } } public static JSObject operator |(JSObject first, JSObject second) { if (first.type == Type.BOOL && second.type == Type.BOOL) { return first.boolValue || second.boolValue; } else { throw new ArgumentException("Incompatible types"); } } public static JSObject operator ++(JSObject first) { if (first.type == Type.INT) { return new JSObject(first.intValue + 1); } else { throw new ArgumentException("Incompatible types"); } } public static JSObject operator !(JSObject first) { if (first.type == Type.INT) { return new JSObject(!first.boolValue); } else { throw new ArgumentException("Incompatible types"); } } public static JSObject operator --(JSObject first) { if (first.type == Type.INT) { return new JSObject(first.intValue - 1); } else { throw new ArgumentException("Incompatible types"); } } //Shared methods IEnumerator IEnumerable.GetEnumerator() { if (type == Type.LIST) { return listValue.GetEnumerator(); } else if (type == Type.DICTIONARY) { return dictionaryValue.GetEnumerator(); } else { throw new ArgumentException("Incompatible types"); } } public override string ToString() { switch (type) { case Type.STRING: return stringValue.ToString(); case Type.FLOAT: return floatValue.ToString(); case Type.INT: return intValue.ToString(); case Type.BOOL: return boolValue.ToString(); case Type.LIST: return listValue.ToString(); case Type.DICTIONARY: return dictionaryValue.ToString(); default: return "Error"; } } /// <summary> /// Same as ==, checks value equality for value types and references for objects. /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { return this == (JSObject)obj; } public override int GetHashCode() { return base.GetHashCode(); } //List and Dictionary method public int Count { get { if (type == Type.LIST) { return listValue.Count; } else if (type == Type.DICTIONARY) { return dictionaryValue.Count; } else { throw new ArgumentException("Incompatible types"); } } } //List<JSObject> properties and methods public void Add(JSObject value) { if (type == Type.LIST) { listValue.Add(value); } else { throw new ArgumentException("Incompatible types"); } } public JSObject this[int key] { get { if (type == Type.LIST) { return listValue[key]; } else { throw new ArgumentException("Incompatible types"); } } set { if (type == Type.LIST) { listValue[key] = value; } else { throw new ArgumentException("Incompatible types"); } } } public bool Contains(JSObject value) { if (type == Type.LIST) { return listValue.Contains(value); } else { throw new ArgumentException("Incompatible types"); } } //Dictionary properties and methods public Dictionary<string, JSObject>.KeyCollection Keys { get { if (type == Type.DICTIONARY) { return dictionaryValue.Keys; } else { throw new ArgumentException("Incompatible types"); } } } public JSObject this[string key] { get { if (type == Type.DICTIONARY) { return dictionaryValue[key]; } else { throw new ArgumentException("Incompatible types"); } } set { if (type == Type.DICTIONARY) { dictionaryValue[key] = value; } else { throw new ArgumentException("Incompatible types"); } } } public void Add(string key, JSObject value) { if (type == Type.DICTIONARY) { dictionaryValue.Add(key, value); } else { throw new ArgumentException("Incompatible types"); } } public bool ContainsKey(string key) { if (type == Type.DICTIONARY) { return dictionaryValue.ContainsKey(key); } else { throw new ArgumentException("Incompatible types"); } } public bool ContainsValue(JSObject value) { if (type == Type.DICTIONARY) { return dictionaryValue.ContainsValue(value); } else { throw new ArgumentException("Incompatible types"); } } }
33.02439
186
0.531065
[ "MIT" ]
SouICry/JSObject_For_Unity_CSharp
JSObject.cs
21,664
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Diagnostics; namespace Microsoft.CodeAnalysis.Emit { internal struct EmitContext { public readonly CommonPEModuleBuilder Module; public readonly SyntaxNode SyntaxNodeOpt; public readonly DiagnosticBag Diagnostics; public EmitContext(CommonPEModuleBuilder module, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Debug.Assert(module != null); Debug.Assert(diagnostics != null); Module = module; SyntaxNodeOpt = syntaxNodeOpt; Diagnostics = diagnostics; } } }
31.791667
161
0.68021
[ "MIT" ]
1Crazymoney/cs2cpp
CoreSource/Emit/Context.cs
765
C#
using System; namespace SKIT.FlurlHttpClient.Wechat.Api.Models { /// <summary> /// <para>表示 [POST] /shop/order/get_list_by_finder 接口的请求。</para> /// </summary> public class ShopOrderGetListByFinderRequest : WechatApiRequest, IInferable<ShopOrderGetListByFinderRequest, ShopOrderGetListByFinderResponse> { /// <summary> /// 获取或设置支付时间的开始时间。 /// </summary> [Newtonsoft.Json.JsonProperty("start_pay_time")] [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.RegularNullableDateTimeOffsetConverter))] [System.Text.Json.Serialization.JsonPropertyName("start_pay_time")] [System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Converters.RegularNullableDateTimeOffsetConverter))] public DateTimeOffset? StartPayTime { get; set; } /// <summary> /// 获取或设置支付时间的结束时间。 /// </summary> [Newtonsoft.Json.JsonProperty("end_pay_time")] [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.RegularNullableDateTimeOffsetConverter))] [System.Text.Json.Serialization.JsonPropertyName("end_pay_time")] [System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Converters.RegularNullableDateTimeOffsetConverter))] public DateTimeOffset? EndPayTime { get; set; } /// <summary> /// 获取或设置推广员 ID。 /// </summary> [Newtonsoft.Json.JsonProperty("promoter_id")] [System.Text.Json.Serialization.JsonPropertyName("promoter_id")] public string? PromoterId { get; set; } /// <summary> /// 获取或设置推广员 OpenId。 /// </summary> [Newtonsoft.Json.JsonProperty("promoter_openid")] [System.Text.Json.Serialization.JsonPropertyName("promoter_openid")] public string? PromoterOpenId { get; set; } /// <summary> /// 获取或设置分页页数(从 1 开始)。 /// </summary> [Newtonsoft.Json.JsonProperty("page")] [System.Text.Json.Serialization.JsonPropertyName("page")] public int Page { get; set; } = 1; /// <summary> /// 获取或设置分页每页数量。 /// </summary> [Newtonsoft.Json.JsonProperty("page_size")] [System.Text.Json.Serialization.JsonPropertyName("page_size")] public int Limit { get; set; } = 10; } }
40.859649
146
0.657364
[ "MIT" ]
OrchesAdam/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Api/Models/Shop/Order/ShopOrderGetListByFinderRequest.cs
2,497
C#
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Runtime.Serialization; using SAEA.Common.Newtonsoft.Json.Linq; using SAEA.Common.Newtonsoft.Json.Utilities; namespace SAEA.Common.Newtonsoft.Json.Serialization { internal enum JsonContractType { None = 0, Object = 1, Array = 2, Primitive = 3, String = 4, Dictionary = 5, Dynamic = 6, Serializable = 7, Linq = 8 } /// <summary> /// Handles <see cref="JsonSerializer"/> serialization callback events. /// </summary> /// <param name="o">The object that raised the callback event.</param> /// <param name="context">The streaming context.</param> public delegate void SerializationCallback(object o, StreamingContext context); /// <summary> /// Handles <see cref="JsonSerializer"/> serialization error callback events. /// </summary> /// <param name="o">The object that raised the callback event.</param> /// <param name="context">The streaming context.</param> /// <param name="errorContext">The error context.</param> public delegate void SerializationErrorCallback(object o, StreamingContext context, ErrorContext errorContext); /// <summary> /// Sets extension data for an object during deserialization. /// </summary> /// <param name="o">The object to set extension data on.</param> /// <param name="key">The extension data key.</param> /// <param name="value">The extension data value.</param> public delegate void ExtensionDataSetter(object o, string key, object value); /// <summary> /// Gets extension data for an object during serialization. /// </summary> /// <param name="o">The object to set extension data on.</param> public delegate IEnumerable<KeyValuePair<object, object>> ExtensionDataGetter(object o); /// <summary> /// Contract details for a <see cref="Type"/> used by the <see cref="JsonSerializer"/>. /// </summary> public abstract class JsonContract { internal bool IsNullable; internal bool IsConvertable; internal bool IsEnum; internal Type NonNullableUnderlyingType; internal ReadType InternalReadType; internal JsonContractType ContractType; internal bool IsReadOnlyOrFixedSize; internal bool IsSealed; internal bool IsInstantiable; private List<SerializationCallback> _onDeserializedCallbacks; private IList<SerializationCallback> _onDeserializingCallbacks; private IList<SerializationCallback> _onSerializedCallbacks; private IList<SerializationCallback> _onSerializingCallbacks; private IList<SerializationErrorCallback> _onErrorCallbacks; private Type _createdType; /// <summary> /// Gets the underlying type for the contract. /// </summary> /// <value>The underlying type for the contract.</value> public Type UnderlyingType { get; private set; } /// <summary> /// Gets or sets the type created during deserialization. /// </summary> /// <value>The type created during deserialization.</value> public Type CreatedType { get { return _createdType; } set { _createdType = value; IsSealed = _createdType.IsSealed(); IsInstantiable = !(_createdType.IsInterface() || _createdType.IsAbstract()); } } /// <summary> /// Gets or sets whether this type contract is serialized as a reference. /// </summary> /// <value>Whether this type contract is serialized as a reference.</value> public bool? IsReference { get; set; } /// <summary> /// Gets or sets the default <see cref="JsonConverter" /> for this contract. /// </summary> /// <value>The converter.</value> public JsonConverter Converter { get; set; } // internally specified JsonConverter's to override default behavour // checked for after passed in converters and attribute specified converters internal JsonConverter InternalConverter { get; set; } /// <summary> /// Gets or sets all methods called immediately after deserialization of the object. /// </summary> /// <value>The methods called immediately after deserialization of the object.</value> public IList<SerializationCallback> OnDeserializedCallbacks { get { if (_onDeserializedCallbacks == null) _onDeserializedCallbacks = new List<SerializationCallback>(); return _onDeserializedCallbacks; } } /// <summary> /// Gets or sets all methods called during deserialization of the object. /// </summary> /// <value>The methods called during deserialization of the object.</value> public IList<SerializationCallback> OnDeserializingCallbacks { get { if (_onDeserializingCallbacks == null) _onDeserializingCallbacks = new List<SerializationCallback>(); return _onDeserializingCallbacks; } } /// <summary> /// Gets or sets all methods called after serialization of the object graph. /// </summary> /// <value>The methods called after serialization of the object graph.</value> public IList<SerializationCallback> OnSerializedCallbacks { get { if (_onSerializedCallbacks == null) _onSerializedCallbacks = new List<SerializationCallback>(); return _onSerializedCallbacks; } } /// <summary> /// Gets or sets all methods called before serialization of the object. /// </summary> /// <value>The methods called before serialization of the object.</value> public IList<SerializationCallback> OnSerializingCallbacks { get { if (_onSerializingCallbacks == null) _onSerializingCallbacks = new List<SerializationCallback>(); return _onSerializingCallbacks; } } /// <summary> /// Gets or sets all method called when an error is thrown during the serialization of the object. /// </summary> /// <value>The methods called when an error is thrown during the serialization of the object.</value> public IList<SerializationErrorCallback> OnErrorCallbacks { get { if (_onErrorCallbacks == null) _onErrorCallbacks = new List<SerializationErrorCallback>(); return _onErrorCallbacks; } } /// <summary> /// Gets or sets the method called immediately after deserialization of the object. /// </summary> /// <value>The method called immediately after deserialization of the object.</value> [Obsolete("This property is obsolete and has been replaced by the OnDeserializedCallbacks collection.")] public MethodInfo OnDeserialized { get { return (OnDeserializedCallbacks.Count > 0) ? OnDeserializedCallbacks[0].Method() : null; } set { OnDeserializedCallbacks.Clear(); OnDeserializedCallbacks.Add(CreateSerializationCallback(value)); } } /// <summary> /// Gets or sets the method called during deserialization of the object. /// </summary> /// <value>The method called during deserialization of the object.</value> [Obsolete("This property is obsolete and has been replaced by the OnDeserializingCallbacks collection.")] public MethodInfo OnDeserializing { get { return (OnDeserializingCallbacks.Count > 0) ? OnDeserializingCallbacks[0].Method() : null; } set { OnDeserializingCallbacks.Clear(); OnDeserializingCallbacks.Add(CreateSerializationCallback(value)); } } /// <summary> /// Gets or sets the method called after serialization of the object graph. /// </summary> /// <value>The method called after serialization of the object graph.</value> [Obsolete("This property is obsolete and has been replaced by the OnSerializedCallbacks collection.")] public MethodInfo OnSerialized { get { return (OnSerializedCallbacks.Count > 0) ? OnSerializedCallbacks[0].Method() : null; } set { OnSerializedCallbacks.Clear(); OnSerializedCallbacks.Add(CreateSerializationCallback(value)); } } /// <summary> /// Gets or sets the method called before serialization of the object. /// </summary> /// <value>The method called before serialization of the object.</value> [Obsolete("This property is obsolete and has been replaced by the OnSerializingCallbacks collection.")] public MethodInfo OnSerializing { get { return (OnSerializingCallbacks.Count > 0) ? OnSerializingCallbacks[0].Method() : null; } set { OnSerializingCallbacks.Clear(); OnSerializingCallbacks.Add(CreateSerializationCallback(value)); } } /// <summary> /// Gets or sets the method called when an error is thrown during the serialization of the object. /// </summary> /// <value>The method called when an error is thrown during the serialization of the object.</value> [Obsolete("This property is obsolete and has been replaced by the OnErrorCallbacks collection.")] public MethodInfo OnError { get { return (OnErrorCallbacks.Count > 0) ? OnErrorCallbacks[0].Method() : null; } set { OnErrorCallbacks.Clear(); OnErrorCallbacks.Add(CreateSerializationErrorCallback(value)); } } /// <summary> /// Gets or sets the default creator method used to create the object. /// </summary> /// <value>The default creator method used to create the object.</value> public Func<object> DefaultCreator { get; set; } /// <summary> /// Gets or sets a value indicating whether the default creator is non public. /// </summary> /// <value><c>true</c> if the default object creator is non-public; otherwise, <c>false</c>.</value> public bool DefaultCreatorNonPublic { get; set; } internal JsonContract(Type underlyingType) { ValidationUtils.ArgumentNotNull(underlyingType, "underlyingType"); UnderlyingType = underlyingType; IsNullable = ReflectionUtils.IsNullable(underlyingType); NonNullableUnderlyingType = (IsNullable && ReflectionUtils.IsNullableType(underlyingType)) ? Nullable.GetUnderlyingType(underlyingType) : underlyingType; CreatedType = NonNullableUnderlyingType; IsConvertable = ConvertUtils.IsConvertible(NonNullableUnderlyingType); IsEnum = NonNullableUnderlyingType.IsEnum(); if (NonNullableUnderlyingType == typeof(byte[])) { InternalReadType = ReadType.ReadAsBytes; } else if (NonNullableUnderlyingType == typeof(int)) { InternalReadType = ReadType.ReadAsInt32; } else if (NonNullableUnderlyingType == typeof(decimal)) { InternalReadType = ReadType.ReadAsDecimal; } else if (NonNullableUnderlyingType == typeof(string)) { InternalReadType = ReadType.ReadAsString; } else if (NonNullableUnderlyingType == typeof(DateTime)) { InternalReadType = ReadType.ReadAsDateTime; } #if !NET20 else if (NonNullableUnderlyingType == typeof(DateTimeOffset)) { InternalReadType = ReadType.ReadAsDateTimeOffset; } #endif else { InternalReadType = ReadType.Read; } } internal void InvokeOnSerializing(object o, StreamingContext context) { if (_onSerializingCallbacks != null) { foreach (SerializationCallback callback in _onSerializingCallbacks) { callback(o, context); } } } internal void InvokeOnSerialized(object o, StreamingContext context) { if (_onSerializedCallbacks != null) { foreach (SerializationCallback callback in _onSerializedCallbacks) { callback(o, context); } } } internal void InvokeOnDeserializing(object o, StreamingContext context) { if (_onDeserializingCallbacks != null) { foreach (SerializationCallback callback in _onDeserializingCallbacks) { callback(o, context); } } } internal void InvokeOnDeserialized(object o, StreamingContext context) { if (_onDeserializedCallbacks != null) { foreach (SerializationCallback callback in _onDeserializedCallbacks) { callback(o, context); } } } internal void InvokeOnError(object o, StreamingContext context, ErrorContext errorContext) { if (_onErrorCallbacks != null) { foreach (SerializationErrorCallback callback in _onErrorCallbacks) { callback(o, context, errorContext); } } } internal static SerializationCallback CreateSerializationCallback(MethodInfo callbackMethodInfo) { return (o, context) => callbackMethodInfo.Invoke(o, new object[] { context }); } internal static SerializationErrorCallback CreateSerializationErrorCallback(MethodInfo callbackMethodInfo) { return (o, context, econtext) => callbackMethodInfo.Invoke(o, new object[] { context, econtext }); } } }
38.705596
165
0.610196
[ "Apache-2.0" ]
cty901/SAEA
Src/SAEA.Common/Newtonsoft.Json/Serialization/JsonContract.cs
15,910
C#
namespace DFC.Composite.Shell.Models { public class ActionGetRequestModel { public string Path { get; set; } public string Data { get; set; } } }
19.444444
40
0.617143
[ "MIT" ]
SkillsFundingAgency/dfc-composite-shell
DFC.Composite.Shell.Models/ActionGetRequestModel.cs
177
C#
using System.Threading; using System.Threading.Tasks; namespace MSFramework.Application { public interface IRequestHandler<in TRequest> where TRequest : IRequest { Task HandleAsync(TRequest request, CancellationToken cancellationToken = default); } public interface IRequestHandler<in TRequest, TResponse> where TRequest : IRequest<TResponse> { Task<TResponse> HandleAsync(TRequest request, CancellationToken cancellationToken = default); } }
30.266667
95
0.80837
[ "MIT" ]
jonechenug/MSFramework
src/MSFramework/Application/IRequestHandler.cs
454
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Data.SQLite; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; namespace pRoom { public static class appInfo { public static string serverID = "123"; public static string ConnectionString = ""; public static string secret = ""; public static string host = ""; public static int isHost = 1; public static string exitUrl; public static string dbType = "sqlserver1"; public static string env = "proom"; public static string path; public static string mediaServer= "t5.salampnu.com"; public static string mediaServerPass= "aaaaa"; public static string domainName; public static int record = 0; public static int live = 0; public static string lang = "en"; public static int demoMeetID = 2; public static string officeServer = ""; public static string officeServerWopi = ""; public static string mqttServer = ""; public static string pdfConverter = ""; public static string recordServer = ""; public static Process ppp = null; public static StreamWriter myStreamWriter = null; public static string Prefix = "psd"; public static IDbConnection GetDbconnection() { IDbConnection db; string _connectionString = "";// "Server=127.0.0.1;Database=s12;User=root;Password=;SslMode=none;";//"Server=127.0.0.1;Database=proom;Uid=root;Pwd=;";// IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(appInfo.ConnectionString); return connection; if (dbType== "sqlserver") db = new SqlConnection(ConnectionString); else db = new SQLiteConnection(ConnectionString); db = new SqlConnection(_connectionString); //using (var connection = new SqlConnection("Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;")) //{ // connection.Query<MyTable>("SELECT * FROM MyTable"); //} return db; } // public static string ConnectionString = "Data Source=DESKTOP-68K4RUU;Initial Catalog=msg;Persist Security Info=True;User ID=sa;Password=passA1!"; } public class appInfo1 { public string ConnectionString = ""; public string secret = ""; public int isHost = 0; public string exitUrl; } }
37.385714
164
0.635078
[ "Apache-2.0" ]
torkashvand630/room
Models/appInfo.cs
2,619
C#
using System; using System.Windows.Input; namespace BindingEngine.Benchmark { public class DelegateCommand : ICommand { #region Constructors public DelegateCommand(Action executeMethod) : this(executeMethod, null) { } public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod) { _executeMethod = executeMethod; _canExecuteMethod = canExecuteMethod; } #endregion #region Public Methods public bool CanExecute() { if(_canExecuteMethod != null) { return _canExecuteMethod(); } return true; } public void Execute() { if(_executeMethod != null) { _executeMethod(); } } public void RaiseCanExecuteChanged() { if(CanExecuteChanged != null) { CanExecuteChanged(this, EventArgs.Empty); } } #endregion #region ICommand Members public event EventHandler CanExecuteChanged; bool ICommand.CanExecute(object parameter) { return CanExecute(); } void ICommand.Execute(object parameter) { Execute(); } #endregion #region Data private readonly Func<bool> _canExecuteMethod; private readonly Action _executeMethod; #endregion } public class DelegateCommand<T> : ICommand { #region Constructors public DelegateCommand(Action<T> executeMethod) : this(executeMethod, null) { } public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod) { if(executeMethod == null) { throw new ArgumentNullException("executeMethod"); } _executeMethod = executeMethod; _canExecuteMethod = canExecuteMethod; } #endregion #region Public Methods public bool CanExecute(T parameter) { if(_canExecuteMethod != null) { return _canExecuteMethod(parameter); } return true; } public void Execute(T parameter) { if(_executeMethod != null) { _executeMethod(parameter); } } public void RaiseCanExecuteChanged() { OnCanExecuteChanged(); } protected virtual void OnCanExecuteChanged() { if(CanExecuteChanged != null) { CanExecuteChanged(this, EventArgs.Empty); } } #endregion #region ICommand Members public event EventHandler CanExecuteChanged; bool ICommand.CanExecute(object parameter) { if(parameter == null && typeof(T).IsValueType) { return (_canExecuteMethod == null); } return CanExecute((T)parameter); } void ICommand.Execute(object parameter) { Execute((T)parameter); } #endregion #region Data private readonly Func<T, bool> _canExecuteMethod; private readonly Action<T> _executeMethod; #endregion } }
21.725
87
0.519563
[ "MIT" ]
zhouyongh/BindingEngine
BindingEngine.Benchmark/Helpers/DelegateCommand.cs
3,478
C#
// *** WARNING: this file was generated by crd2pulumi. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Kubernetes.Types.Inputs.Keda.V1Alpha1 { /// <summary> /// SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field. /// </summary> public class ScaledObjectSpecJobTargetRefTemplateSpecSecurityContextArgs : Pulumi.ResourceArgs { /// <summary> /// A special supplemental group that applies to all containers in a pod. Some volume types allow the Kubelet to change the ownership of that volume to be owned by the pod: /// 1. The owning GID will be the FSGroup 2. The setgid bit is set (new files created in the volume will be owned by FSGroup) 3. The permission bits are OR'd with rw-rw---- /// If unset, the Kubelet will not modify the ownership and permissions of any volume. /// </summary> [Input("fsGroup")] public Input<int>? FsGroup { get; set; } /// <summary> /// The GID to run the entrypoint of the container process. Uses runtime default if unset. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container. /// </summary> [Input("runAsGroup")] public Input<int>? RunAsGroup { get; set; } /// <summary> /// Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. If unset or false, no such validation will be performed. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. /// </summary> [Input("runAsNonRoot")] public Input<bool>? RunAsNonRoot { get; set; } /// <summary> /// The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container. /// </summary> [Input("runAsUser")] public Input<int>? RunAsUser { get; set; } /// <summary> /// The SELinux context to be applied to all containers. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container. /// </summary> [Input("seLinuxOptions")] public Input<Pulumi.Kubernetes.Types.Inputs.Keda.V1Alpha1.ScaledObjectSpecJobTargetRefTemplateSpecSecurityContextSeLinuxOptionsArgs>? SeLinuxOptions { get; set; } [Input("supplementalGroups")] private InputList<int>? _supplementalGroups; /// <summary> /// A list of groups applied to the first process run in each container, in addition to the container's primary GID. If unspecified, no groups will be added to any container. /// </summary> public InputList<int> SupplementalGroups { get => _supplementalGroups ?? (_supplementalGroups = new InputList<int>()); set => _supplementalGroups = value; } [Input("sysctls")] private InputList<Pulumi.Kubernetes.Types.Inputs.Keda.V1Alpha1.ScaledObjectSpecJobTargetRefTemplateSpecSecurityContextSysctlsArgs>? _sysctls; /// <summary> /// Sysctls hold a list of namespaced sysctls used for the pod. Pods with unsupported sysctls (by the container runtime) might fail to launch. /// </summary> public InputList<Pulumi.Kubernetes.Types.Inputs.Keda.V1Alpha1.ScaledObjectSpecJobTargetRefTemplateSpecSecurityContextSysctlsArgs> Sysctls { get => _sysctls ?? (_sysctls = new InputList<Pulumi.Kubernetes.Types.Inputs.Keda.V1Alpha1.ScaledObjectSpecJobTargetRefTemplateSpecSecurityContextSysctlsArgs>()); set => _sysctls = value; } public ScaledObjectSpecJobTargetRefTemplateSpecSecurityContextArgs() { } } }
58.025316
422
0.703316
[ "Apache-2.0" ]
pulumi/pulumi-kubernetes-crds
operators/keda/dotnet/Kubernetes/Crds/Operators/Keda/Keda/V1Alpha1/Inputs/ScaledObjectSpecJobTargetRefTemplateSpecSecurityContextArgs.cs
4,584
C#
using System.Collections.Generic; namespace Plivo.XML { public class Conference : PlivoElement { public Conference(string body, Dictionary<string, string> parameters) : base(body, parameters) { Nestables = new List<string>() { "" }; ValidAttributes = new List<string>() { "sendDigits", "muted", "enterSound", "exitSound", "startConferenceOnEnter", "endConferenceOnExit", "stayAlone", "waitSound", "maxMembers", "timeLimit", "hangupOnStar", "action", "method", "callbackUrl", "callbackMethod", "digitsMatch", "floorEvent", "redirect", "Record", "recordFileFormat","recordWhenAlone", "transcriptionType", "transcriptionUrl", "transcriptionMethod","relayDTMF" }; addAttributes(); } } }
42
134
0.573696
[ "MIT" ]
EIrwin/plivo-dotnet
Plivo/XML/Conference.cs
884
C#
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel.DataAnnotations.Schema; using CodeGenerator.Infra.Common.Entity; namespace CodeGenerator.Core.Entities { /// <summary> /// 角色授权 /// </summary> public class RoleAuthorize : BaseEntity { /// <summary> /// 角色主键 /// </summary> public long ApplicationRoleId { get; set; } /// <summary> /// 应用菜单主键 /// </summary> public long ApplicationMenuId { get; set; } /// <summary> /// 可用功能:以json数组保存 /// </summary> public string AvailableActions { get; set; } /// <summary> /// 角色 /// </summary> public virtual ApplicationRole ApplicationRole { get; set; } /// <summary> /// 应用菜单 /// </summary> public virtual ApplicationMenu ApplicationMenu { get; set; } } }
21.891892
62
0.640741
[ "MIT" ]
ileego/CodeGenerator
src/CodeGenerator.Core/Entities/RoleAuthorize.cs
870
C#
using System; using System.Linq; using System.Threading.Tasks; using Hangfire; using Hangfire.Console; using Hangfire.Server; using Novinichka.Common; using Novinichka.Data.Common.Repositories; using Novinichka.Data.Models; using Novinichka.Services.Data.Interfaces; using Novinichka.Services.NewsSources; namespace Novinichka.Services.CronJobs { public class GetLatestNewsCronJob { private readonly IDeletableEntityRepository<Source> sourcesRepository; private readonly INewsService newsService; public GetLatestNewsCronJob( IDeletableEntityRepository<Source> sourcesRepository, INewsService newsService) { this.sourcesRepository = sourcesRepository; this.newsService = newsService; } [AutomaticRetry(Attempts = 3)] public async Task StartWorking(string typeName, PerformContext context) { var source = this.sourcesRepository .AllWithDeleted() .FirstOrDefault(x => x.TypeName == typeName); if (source == null) { throw new Exception($"Source {typeName} has not found in the database!"); } var instance = ReflectionHelpers .GetInstance<BaseSource>(typeName); var news = instance .GetRecentNews() .ToList(); foreach (var currentNews in news.WithProgress(context.WriteProgressBar())) { var newsId = await this.newsService.AddAsync(currentNews, source.Id); if (newsId.HasValue && currentNews != null) { context.WriteLine($"[ID:{newsId}] Successfully imported news with title: {currentNews.Title}"); } } } } }
31.084746
115
0.615049
[ "MIT" ]
georgidelchev/novini4ka
Novinichka.Services.CronJobs/GetLatestNewsCronJob.cs
1,836
C#
namespace Orc.Controls { public enum ExpandDirection { Down = 0, Up = 1, Left = 2, Right = 3, } }
13
31
0.447552
[ "MIT" ]
Orcomp/Orc.Controls
src/Orc.Controls/Controls/Expander/Models/ExpandDirection.cs
145
C#
// Copyright 2017 the original author or 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 // // 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. namespace Steeltoe.CircuitBreaker { public enum RequestCollapserScope { REQUEST, GLOBAL } }
31.608696
75
0.730399
[ "Apache-2.0" ]
FrancisChung/steeltoe
src/CircuitBreaker/src/Abstractions/RequestCollapserScope.cs
729
C#
using FluentAssertions; using Microsoft.AspNetCore.Mvc; using Sfa.Tl.ResultsAndCertification.Common.Helpers; using Sfa.Tl.ResultsAndCertification.Web.ViewModel.TrainingProvider.Manual; using BreadcrumbContent = Sfa.Tl.ResultsAndCertification.Web.Content.ViewComponents.Breadcrumb; using Xunit; namespace Sfa.Tl.ResultsAndCertification.Web.UnitTests.Controllers.TrainingProviderControllerTests.SearchLearnerRecordGet { public class When_Cache_NotFound : TestSetup { public override void Given() { } [Fact] public void Then_Returns_Expected_Results() { Result.Should().NotBeNull(); (Result as ViewResult).Model.Should().NotBeNull(); var model = (Result as ViewResult).Model as SearchLearnerRecordViewModel; model.SearchUln.Should().BeNull(); model.Breadcrumb.Should().NotBeNull(); model.Breadcrumb.BreadcrumbItems.Count.Should().Be(1); model.Breadcrumb.BreadcrumbItems[0].DisplayName.Should().Be(BreadcrumbContent.Home); model.Breadcrumb.BreadcrumbItems[0].RouteName.Should().Be(RouteConstants.Home); } } }
39.931034
121
0.716753
[ "MIT" ]
SkillsFundingAgency/tl-result-and-certification
src/Tests/Sfa.Tl.ResultsAndCertification.Web.UnitTests/Controllers/TrainingProviderControllerTests/SearchLearnerRecordGet/When_Cache_NotFound.cs
1,160
C#
using GMap.NET; using GMap.NET.WindowsForms; using GMap.NET.WindowsForms.Markers; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TaskSimulator.Forms { public partial class FlyPathMapMonitor : MapMonitorBase { /// <summary> /// 船标识 /// </summary> public GMarkerGoogle BoatMarker { get; set; } /// <summary> /// 航行路径文本 /// </summary> public string FlyPathText { get; set; } /// <summary> /// 船的初始位置 /// </summary> public TaskSimulatorLib.Entitys.LatAndLng BoatDefaultPoint { get; set; } /// <summary> /// 线开始坐标(初始) /// </summary> private PointLatLng DefaultLineStartPoint { get; set; } /// <summary> /// 飞行线路 /// </summary> private List<FlyPathLine> flyPathLines = new List<FlyPathLine>(); /// <summary> /// 用于存储跟随鼠标而动的线 /// </summary> private FlyPathLine TempFlyLine = null; /// <summary> /// 线开始坐标 /// </summary> private PointLatLng LineStartPoint; /// <summary> /// 是否允许绘制航行路径 /// </summary> private bool IsEnabledDrawFlyPath { get; set; } /// <summary> /// 每秒钟前进步数 /// </summary> public double StepWithSecond { get; set; } public FlyPathMapMonitor() { InitializeComponent(); //初始化地图 InitMap(new GMap.NET.PointLatLng(24.2120, 135.4603), 6, 3, 21, false); MapControl.MouseDoubleClick += MapControl_MouseDoubleClick; MapControl.MouseClick += MapControl_MouseClick; MapControl.MouseDown += MapControl_MouseDown; MapControl.MouseUp += MapControl_MouseUp; MapControl.MouseMove += MapControl_MouseMove; MapControl.OnPolygonLeave += MapControl_OnPolygonLeave; MapControl.OnPolygonEnter += MapControl_OnPolygonEnter; } void MapControl_OnPolygonLeave(GMapPolygon item) { } void MapControl_OnPolygonEnter(GMapPolygon item) { } void MapControl_MouseDown(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Right) { } } void MapControl_MouseMove(object sender, MouseEventArgs e) { if (IsEnabledDrawFlyPath) { if (TempFlyLine != null) { DefaultOverlay.Routes.Remove(TempFlyLine.RouteObject); } TempFlyLine = new FlyPathLine(LineStartPoint, MapControl.FromLocalToLatLng(e.X, e.Y), Color.Red, 2); DefaultOverlay.Routes.Add(TempFlyLine.RouteObject); } } void MapControl_MouseUp(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Right) { } } void MapControl_MouseClick(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Right) { if (TempFlyLine != null) { LineStartPoint = TempFlyLine.EndPoints; flyPathLines.Add(TempFlyLine); TempFlyLine = null; } } } void MapControl_MouseDoubleClick(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { StringBuilder sb = new StringBuilder(); foreach (FlyPathLine fpl in flyPathLines) { //sb.Append(fpl.StartPoints.Lat).Append(":").Append(fpl.StartPoints.Lng).Append("\n"); sb.Append(fpl.EndPoints.Lat).Append(":").Append(fpl.EndPoints.Lng).Append("\n"); } FlyPathText = sb.ToString(); this.DialogResult = System.Windows.Forms.DialogResult.OK; } } protected override void OnActivated(EventArgs e) { base.OnActivated(e); DefaultLineStartPoint = new PointLatLng(BoatDefaultPoint.Lat, BoatDefaultPoint.Lng); LineStartPoint = new PointLatLng(BoatDefaultPoint.Lat, BoatDefaultPoint.Lng); //显示船 BoatMarker = new GMarkerGoogle(LineStartPoint, new Bitmap(Bitmap.FromFile(System.IO.Path.Combine(Application.StartupPath, "ship.png")))); BoatMarker.ToolTipMode = MarkerTooltipMode.Always; BoatMarker.ToolTipText = "船"; DefaultOverlay.Markers.Add(BoatMarker); if (string.IsNullOrEmpty(FlyPathText)) { //还没有规划航行路线 IsEnabledDrawFlyPath = true; } else { //已经规划航行路线 IsEnabledDrawFlyPath = false; //加载已有的方案 string[] flyPaths = FlyPathText.Split(new string[] { "\n" }, StringSplitOptions.None); if (flyPaths != null) { //将Text文本转化成Point列表 List<PointLatLng> tempPoints = new List<PointLatLng>(); foreach (string fp in flyPaths) { string[] points = fp.Split(new string[] { ":" }, StringSplitOptions.None); if (points != null && points.Length >= 2) { double lat = double.Parse(points[0]); double lng = double.Parse(points[1]); tempPoints.Add(new PointLatLng(lat, lng)); } } //绘制航行路线 PointLatLng firstPoint = DefaultLineStartPoint; foreach (PointLatLng point in tempPoints) { FlyPathLine fpl = new FlyPathLine(firstPoint, point, Color.Red, 2); DefaultOverlay.Routes.Add(fpl.RouteObject); firstPoint = point; } } } } private void btnDarwNewPath_Click(object sender, EventArgs e) { IsEnabledDrawFlyPath = true; flyPathLines.Clear(); TempFlyLine = null; DefaultOverlay.Routes.Clear(); LineStartPoint = DefaultLineStartPoint; } } /// <summary> /// 飞行线 /// </summary> public class FlyPathLine { public FlyPathLine() { } public FlyPathLine(PointLatLng pointLatLng_S, PointLatLng pointLatLng_E, Color penColor, int width) { StartPoints = pointLatLng_S; EndPoints = pointLatLng_E; PenColor = penColor; RouteObject = new GMapRoute(new PointLatLng[] { StartPoints, EndPoints }, ""); RouteObject.Stroke = new Pen(PenColor, width); } /// <summary> /// 线颜色 /// </summary> public Color PenColor { get; set; } /// <summary> /// 线对象 /// </summary> public GMapRoute RouteObject { get; set; } /// <summary> /// 开始点 /// </summary> public PointLatLng StartPoints { get; set; } /// <summary> /// 结束点 /// </summary> public PointLatLng EndPoints { get; set; } } }
30.557769
149
0.527119
[ "MIT" ]
wcss2010/TaskSimulator-DotNet
TaskSimulator/TaskSimulator/Forms/FlyPathMapMonitor.cs
7,920
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DCT.TestDataGenerator.Functor { internal class PriorAttainWithAppProgTypeAim { public PriorAttain Attain; public ApprenticeshipProgrammeTypeAim PTA; } }
20.6
50
0.760518
[ "MIT" ]
Amos-A/DC-ILR-1819-Test-Data-Generation
src/ESFA.DC.ILR.TestDataGenerator.Functors/Learner/PriorAttain/PriorAttainWithAppProgTypeAim.cs
311
C#
/** * Copyright 2015 Canada Health Infoway, 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. * * Author: $LastChangedBy: tmcgrady $ * Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $ * Revision: $LastChangedRevision: 2623 $ */ /* This class was auto-generated by the message builder generator tools. */ namespace Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_05_00.Common.Coct_mt270010ca { using Ca.Infoway.Messagebuilder.Annotation; using Ca.Infoway.Messagebuilder.Datatype; using Ca.Infoway.Messagebuilder.Datatype.Impl; using Ca.Infoway.Messagebuilder.Domainvalue; using Ca.Infoway.Messagebuilder.Model; using System; /** * <summary>Business Name: Additional SIG Instruction</summary> * * <p>Adds further constraint or flexibility to the primary * administration instruction.</p> <p>This is a modifier for a * specific dosage line or for the entire SIG. Examples are: On * empty stomach, At breakfast, before bedtime, etc.</p> */ [Hl7PartTypeMappingAttribute(new string[] {"COCT_MT270010CA.SupplementalInstruction"})] public class AdditionalSIGInstruction : MessagePartBean { private CS moodCode; private ST text; public AdditionalSIGInstruction() { this.moodCode = new CSImpl(); this.text = new STImpl(); } /** * <summary>Business Name: Dosage Usage Context</summary> * * <remarks>Relationship: * COCT_MT270010CA.SupplementalInstruction.moodCode * Conformance/Cardinality: MANDATORY (1) <p>- moodCode must be * DEFN for drug definitions (such as as monographs) - moodCode * must be RQO for orders; - moodCode must be EVN for dispenses * and recording of other medications { x.; }</p> <p>Puts the * class in context, and is therefore mandatory.</p> * <p>Indicates the context of the * administration.</p><p>moodCode = RQO, for administration * instruction on orders</p><p>moodCode = EVN, for * administration instruction on dispenses</p><p>moodCode = * DEF, for administration instruction on medication definition * documents/references (typically, monographs).</p></remarks> */ [Hl7XmlMappingAttribute(new string[] {"moodCode"})] public x_ActMoodDefEvnRqo MoodCode { get { return (x_ActMoodDefEvnRqo) this.moodCode.Value; } set { this.moodCode.Value = value; } } /** * <summary>Business Name: F:Additional Dosage Instruction</summary> * * <remarks>Relationship: * COCT_MT270010CA.SupplementalInstruction.text * Conformance/Cardinality: MANDATORY (1) <p>ZDP.13.8</p> * <p>Allows for expression of non-codable qualifiers such as: * 'on an empty stomach', 'add water' etc; which do not affect * calculations of frequencies or quantity.</p><p>This * attribute is marked as 'mandatory' as it is the only * information that can be specified here.</p> <p>A free form * textual description of extended instruction regarding the * administration of the drug.</p></remarks> */ [Hl7XmlMappingAttribute(new string[] {"text"})] public String Text { get { return this.text.Value; } set { this.text.Value = value; } } } }
44.16129
92
0.637448
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-r02_05_00/Main/Ca/Infoway/Messagebuilder/Model/Pcs_mr2009_r02_05_00/Common/Coct_mt270010ca/AdditionalSIGInstruction.cs
4,107
C#
using System; using System.Collections.Generic; using System.Xml; using IntelligentComments.Comments.Calculations.Core.DocComments.Utils; using JetBrains.Annotations; using JetBrains.ReSharper.Psi.Tree; using JetBrains.ReSharper.Psi.Util; namespace IntelligentComments.Comments.Calculations.Core.DocComments; public abstract class XmlDocVisitorWitCustomElements : XmlDocVisitor { [NotNull] private readonly IDictionary<string, Action<XmlElement>> myAdditionalHandlers; [NotNull] protected readonly ISet<XmlNode> VisitedNodes; [NotNull] protected readonly IDocCommentBlock InitialComment; [NotNull] protected IDocCommentBlock AdjustedComment { get; set; } // ReSharper disable once NotNullMemberIsNotInitialized protected XmlDocVisitorWitCustomElements([NotNull] IDocCommentBlock comment) { InitialComment = comment; VisitedNodes = new HashSet<XmlNode>(); myAdditionalHandlers = new Dictionary<string, Action<XmlElement>> { [DocCommentsBuilderUtil.PTagName] = VisitP, [DocCommentsBuilderUtil.ImageTagName] = VisitImage, [DocCommentsBuilderUtil.ReferenceTagName] = VisitReference, [DocCommentsBuilderUtil.InvariantTagName] = VisitInvariant, [DocCommentsBuilderUtil.TodoTagName] = VisitTodo, [DocCommentsBuilderUtil.HackTagName] = VisitHack, }; } public sealed override void VisitUnknownTag(XmlElement element) { VisitedNodes.Add(element); if (myAdditionalHandlers.TryGetValue(element.LocalName, out var handler)) { handler?.Invoke(element); } } protected abstract void VisitHack([NotNull] XmlElement element); protected abstract void VisitImage([NotNull] XmlElement element); protected abstract void VisitInvariant([NotNull] XmlElement element); protected abstract void VisitReference([NotNull] XmlElement element); protected abstract void VisitTodo([NotNull] XmlElement element); protected abstract void VisitP([NotNull] XmlElement element); }
37.037736
90
0.784513
[ "MIT" ]
aerooneqq/IntelligentComments
src/dotnet/IntelligentComments/src/Comments/Calculations/Core/DocComments/XmlDocVisitorWitCustomElements.cs
1,963
C#
// 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. #nullable disable using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Undo { /// <summary> /// A service that allows consumers to register undo transactions for a supplied /// <see cref="SourceText"/> with a supplied description. The description is the /// display string by which the IDE's undo stack UI will subsequently refer to the transaction. /// </summary> internal interface ISourceTextUndoService : IWorkspaceService { /// <summary> /// Registers undo transaction for the supplied <see cref="SourceText"/>. /// </summary> /// <param name="sourceText">The <see cref="SourceText"/> for which undo transaction is being registered.</param> /// <param name="description">The display string by which the IDE's undo stack UI will subsequently refer to the transaction.</param> ISourceTextUndoTransaction RegisterUndoTransaction(SourceText sourceText, string description); /// <summary> /// Starts previously registered undo transaction for the supplied <see cref="ITextSnapshot"/> (if any). /// </summary> /// <param name="snapshot">The <see cref="ITextSnapshot"/> for the <see cref="SourceText"/> for undo transaction being started.</param> /// <remarks> /// This method will handle the translation from <see cref="ITextSnapshot"/> to <see cref="SourceText"/> /// and update the IDE's undo stack UI with the transaction's previously registered description string. /// </remarks> bool BeginUndoTransaction(ITextSnapshot snapshot); /// <summary> /// Completes and deletes the supplied undo transaction. /// </summary> /// <param name="transaction">The undo transaction that is being ended.</param> bool EndUndoTransaction(ISourceTextUndoTransaction transaction); } }
49.136364
143
0.694265
[ "MIT" ]
333fred/roslyn
src/EditorFeatures/Core/Undo/ISourceTextUndoService.cs
2,164
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Irony.Parsing { /// <summary>Base class for more specific reduce actions. </summary> public partial class ReduceParserAction: ParserAction { public readonly Production Production; public ReduceParserAction(Production production) { Production = production; } public override string ToString() { return string.Format(Resources.LabelActionReduce, Production.ToStringQuoted()); } /// <summary>Factory method for creating a proper type of reduce parser action. </summary> /// <param name="production">A Production to reduce.</param> /// <returns>Reduce action.</returns> public static ReduceParserAction Create(Production production) { var nonTerm = production.LValue; //List builder (non-empty production for list non-terminal) is a special case var isList = nonTerm.Flags.IsSet(TermFlags.IsList); var isListBuilderProduction = isList && production.RValues.Count > 0 && production.RValues[0] == production.LValue; if (isListBuilderProduction) return new ReduceListBuilderParserAction(production); else if (nonTerm.Flags.IsSet(TermFlags.IsListContainer)) return new ReduceListContainerParserAction(production); else if (nonTerm.Flags.IsSet(TermFlags.IsTransient)) return new ReduceTransientParserAction(production); else return new ReduceParserAction(production); } public override void Execute(ParsingContext context) { var savedParserInput = context.CurrentParserInput; context.CurrentParserInput = GetResultNode(context); CompleteReduce(context); context.CurrentParserInput = savedParserInput; } protected virtual ParseTreeNode GetResultNode(ParsingContext context) { var childCount = Production.RValues.Count; int firstChildIndex = context.ParserStack.Count - childCount; var span = context.ComputeStackRangeSpan(childCount); var newNode = new ParseTreeNode(Production.LValue, span); for (int i = 0; i < childCount; i++) { var childNode = context.ParserStack[firstChildIndex + i]; if (childNode.IsPunctuationOrEmptyTransient()) continue; //skip punctuation or empty transient nodes newNode.ChildNodes.Add(childNode); }//for i return newNode; } //Completes reduce: pops child nodes from the stack and pushes result node into the stack protected void CompleteReduce(ParsingContext context) { var resultNode = context.CurrentParserInput; var childCount = Production.RValues.Count; //Pop stack context.ParserStack.Pop(childCount); //Copy comment block from first child; if comments precede child node, they precede the parent as well. if (resultNode.ChildNodes.Count > 0) resultNode.Comments = resultNode.ChildNodes[0].Comments; //Inherit precedence and associativity, to cover a standard case: BinOp->+|-|*|/; // BinOp node should inherit precedence from underlying operator symbol. //TODO: this special case will be handled differently. A ToTerm method should be expanded to allow "combined" terms like "NOT LIKE". // OLD COMMENT: A special case is SQL operator "NOT LIKE" which consists of 2 tokens. We therefore inherit "max" precedence from any children if (Production.LValue.Flags.IsSet(TermFlags.InheritPrecedence)) InheritPrecedence(resultNode); //Push new node into stack and move to new state //First read the state from top of the stack context.CurrentParserState = context.ParserStack.Top.State; if (context.TracingEnabled) context.AddTrace(Resources.MsgTracePoppedState, Production.LValue.Name); #region comments on special case //Special case: if a non-terminal is Transient (ex: BinOp), then result node is not this NonTerminal, but its its child (ex: symbol). // Shift action will invoke OnShifting on actual term being shifted (symbol); we need to invoke Shifting even on NonTerminal itself // - this would be more expected behavior in general. ImpliedPrecHint relies on this #endregion if (resultNode.Term != Production.LValue) //special case Production.LValue.OnShifting(context.SharedParsingEventArgs); // Shift to new state - execute shift over the non-terminal of the production. var shift = context.CurrentParserState.Actions[Production.LValue]; // Execute shift to new state shift.Execute(context); //Invoke Reduce event Production.LValue.OnReduced(context, Production, resultNode); } //This operation helps in situation when Bin expression is declared as BinExpr.Rule = expr + BinOp + expr; // where BinOp is an OR-combination of operators. // During parsing, when 'expr, BinOp, expr' is on the top of the stack, // and incoming symbol is operator, we need to use precedence rule for deciding on the action. private void InheritPrecedence(ParseTreeNode node) { for (int i = 0; i < node.ChildNodes.Count; i++) { var child = node.ChildNodes[i]; if (child.Precedence == Terminal.NoPrecedence) continue; node.Precedence = child.Precedence; node.Associativity = child.Associativity; return; } } }//class /// <summary>Reduces non-terminal marked as Transient by MarkTransient method. </summary> public class ReduceTransientParserAction : ReduceParserAction { public ReduceTransientParserAction(Production production) : base(production) { } protected override ParseTreeNode GetResultNode(ParsingContext context) { var topIndex = context.ParserStack.Count - 1; var childCount = Production.RValues.Count; for (int i = 0; i < childCount; i++) { var child = context.ParserStack[topIndex - i]; if (child.IsPunctuationOrEmptyTransient()) continue; return child; } //Otherwise return an empty transient node; if it is part of the list, the list will skip it var span = context.ComputeStackRangeSpan(childCount); return new ParseTreeNode(Production.LValue, span); } }//class /// <summary>Reduces list created by MakePlusRule or MakeListRule methods. </summary> public class ReduceListBuilderParserAction : ReduceParserAction { public ReduceListBuilderParserAction(Production production) : base(production) { } protected override ParseTreeNode GetResultNode(ParsingContext context) { int childCount = Production.RValues.Count; int firstChildIndex = context.ParserStack.Count - childCount; var listNode = context.ParserStack[firstChildIndex]; //get the list already created - it is the first child node listNode.Span = context.ComputeStackRangeSpan(childCount); var listMember = context.ParserStack.Top; //next list member is the last child - at the top of the stack if (listMember.IsPunctuationOrEmptyTransient()) return listNode; listNode.ChildNodes.Add(listMember); return listNode; } }//class //List container is an artificial non-terminal created by MakeStarRule method; the actual list is a direct child. public class ReduceListContainerParserAction : ReduceParserAction { public ReduceListContainerParserAction(Production production) : base(production) { } protected override ParseTreeNode GetResultNode(ParsingContext context) { int childCount = Production.RValues.Count; int firstChildIndex = context.ParserStack.Count - childCount; var span = context.ComputeStackRangeSpan(childCount); var newNode = new ParseTreeNode(Production.LValue, span); if (childCount > 0) { //if it is not empty production - might happen for MakeStarRule var listNode = context.ParserStack[firstChildIndex]; //get the transient list with all members - it is the first child node newNode.ChildNodes.AddRange(listNode.ChildNodes); //copy all list members } return newNode; } }//class }//ns
50.650307
148
0.703004
[ "MIT" ]
ArsenShnurkov/Irony-GtkSharpExplorer
Irony/Parsing/Parser/ParserActions/ReduceParserActions.cs
8,258
C#
using MediatR; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using EventSorcery.Events.Application; using EventSorcery.Events.Measuring; using EventSorcery.Events.Mqtt; using EventSorcery.Infrastructure.DependencyInjection; namespace EventSorcery.Components.Measuring { internal class MeasurementRequestGenerator : ISingletonComponent, INotificationHandler<SensorMeasurement>, INotificationHandler<OutboundMeasurement>, IMeasurementTimingService, INotificationHandler<ApplicationStartCompleted>, INotificationHandler<ApplicationShutdownRequested>, INotificationHandler<ApplicationShutdownCompleted>, INotificationHandler<ConnectionEstablished>, INotificationHandler<ConnectionLost> { protected IMediator Mediator { get; } protected Configuration.Generic Generic { get; } protected CancellationTokenSource CancellationTokenSource { get; set; } protected bool IsConnected { get; set; } protected IDictionary<ISensorScanRateItem, Stopwatch> LastMeasurement { get; } protected IDictionary<ISensorScanRateItem, Func<IEnumerable<ISensorScanRateItem>, CancellationToken, Task>> IsDueCallback { get; } public MeasurementRequestGenerator(IMediator mediator, Configuration.Generic generic) { Mediator = mediator ?? throw new ArgumentNullException(nameof(mediator)); Generic = generic ?? throw new ArgumentNullException(nameof(generic)); LastMeasurement = new Dictionary<ISensorScanRateItem, Stopwatch>(); IsDueCallback = new Dictionary<ISensorScanRateItem, Func<IEnumerable<ISensorScanRateItem>, CancellationToken, Task>>(); } public Task Handle(ApplicationStartCompleted notification, CancellationToken cancellationToken) { CancellationTokenSource = new CancellationTokenSource(); Task.Run(() => Main(CancellationTokenSource.Token)); return Task.CompletedTask; } public Task Handle(ConnectionEstablished notification, CancellationToken cancellationToken) { IsConnected = true; return Task.CompletedTask; } public Task Handle(ConnectionLost notification, CancellationToken cancellationToken) { IsConnected = false; return Task.CompletedTask; } public Task Handle(ApplicationShutdownRequested notification, CancellationToken cancellationToken) { CancellationTokenSource.Cancel(); return Task.CompletedTask; } public Task Handle(ApplicationShutdownCompleted notification, CancellationToken cancellationToken) { // dispose cancellation token CancellationTokenSource.Dispose(); return Task.CompletedTask; } public Task Handle(SensorMeasurement notification, CancellationToken cancellationToken) { // discard publish if not connected if (!IsConnected) { Console.WriteLine($"Not connected, discarding sensor measurement of sensor '{notification.Sensor}' .."); return Task.CompletedTask; } return Mediator.Publish(new PublishRequest() { Topic = $"{Generic.TopicPrefix}/{notification.Sensor}", Payload = Encoding.UTF8.GetBytes(notification.Value), Qos = Generic.Measurements.Qos, Retain = false, }, cancellationToken); } public Task Handle(OutboundMeasurement notification, CancellationToken cancellationToken) { // discard publish if not connected if (!IsConnected) { Console.WriteLine($"Not connected, discarding outbound measurement named '{notification.Name}' .."); return Task.CompletedTask; } return Mediator.Publish(new PublishAsJsonRequest() { Topic = $"event/measurement/{notification.Name}", Payload = notification.Item, Qos = Generic.Measurements.Qos, Retain = false, }, cancellationToken); } public void Register<T>(T item, Func<T, CancellationToken, Task> isDueCallback) where T : ISensorScanRateItem { LastMeasurement[item] = Stopwatch.StartNew(); IsDueCallback[item] = (IEnumerable<ISensorScanRateItem> items, CancellationToken cancellationToken) => { // if this doesn't work, it is a bug var itemsAsT = items.Where(t => t is T).Cast<T>().ToList(); var itemAsT = itemsAsT.FirstOrDefault(); return isDueCallback(itemAsT, cancellationToken); }; } public void Register<T>(IEnumerable<T> items, Func<IEnumerable<T>, CancellationToken, Task> isDueCallback) where T : ISensorScanRateItem { Func<IEnumerable<ISensorScanRateItem>, CancellationToken, Task> callback = (IEnumerable<ISensorScanRateItem> items, CancellationToken cancellationToken) => { // if this doesn't work, it is a bug var itemsAsT = items.Where(t => t is T).Cast<T>().ToList(); return isDueCallback(itemsAsT, cancellationToken); }; foreach (var item in items) { LastMeasurement[item] = Stopwatch.StartNew(); IsDueCallback[item] = callback; } } public bool IsDue<T>(T item) where T : ISensorScanRateItem { if (!LastMeasurement.ContainsKey(item)) { throw new InvalidOperationException("Sensor configuration item has not been registered earlier"); } var stopwatch = LastMeasurement[item]; return stopwatch.Elapsed >= item.ScanRate; } public void ResetDue<T>(T item) where T : ISensorScanRateItem { if (!LastMeasurement.ContainsKey(item)) { throw new InvalidOperationException("Sensor configuration item has not been registered earlier"); } LastMeasurement[item].Restart(); } public void ResetDue<T>(IEnumerable<T> items) where T : ISensorScanRateItem { foreach (var item in items) { ResetDue(item); } } private Task OnIsDue(IEnumerable<ISensorScanRateItem> items, CancellationToken cancellationToken) { // inform any due items var callbacks = items .Where(t => IsDueCallback.ContainsKey(t)) .Select(t => IsDueCallback[t]) .Distinct(); return Task.WhenAll(callbacks.Select(t => t(items, cancellationToken))); } private async Task Main(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { try { if (IsConnected) { // collect due items var dueItems = LastMeasurement .Where(t => IsDue(t.Key)) .Select(t => t.Key) .ToList(); if (dueItems.Any()) { await OnIsDue(dueItems, cancellationToken); } else { // no items due } } else { // do not request measurements while disconnected // we have to delay in this situation at least for some // time to avoid hot looping Console.WriteLine($"Not connected, delaying new measurements for one second .."); await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken); } // delay and wait for next cycle var nextDueTimes = LastMeasurement .Select(t => t.Key.ScanRate - t.Value.Elapsed) .Distinct() .OrderBy(t => t) .ToList(); if (nextDueTimes.Count > 0) { var minDueTime = nextDueTimes.First(); // this delay is a smart guess observing that a Task.Delay() won't // be accurate enough to accomodate a delay shorter than this interval. // better avoid unnecessary delays if the smallest delay is shorter than this // upon reaching this interval it is better to skip the delay and straight // check if any item is due var smallestPossibleDelay = TimeSpan.Zero; if (minDueTime < smallestPossibleDelay) { // another item is already due, skip delay } else { await Task.Delay(minDueTime, cancellationToken); } } else { await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken); } } catch (TaskCanceledException) { // ignore } catch (Exception ex) { Console.WriteLine($"Measurement request generator caught exception and resumes operation: {ex}"); } } } } }
39.401544
167
0.55316
[ "Apache-2.0" ]
dpsenner/event-sorcery
src/csharp/Components.Measuring/MeasurementRequestGenerator.cs
10,207
C#
using System; using System.Collections.Generic; using System.Linq; using Autodesk.Revit.DB; using Speckle.Core.Kits; using Speckle.Core.Models; using BE = Objects.BuiltElements; using BER = Objects.BuiltElements.Revit; using BERC = Objects.BuiltElements.Revit.Curve; using DB = Autodesk.Revit.DB; namespace Objects.Converter.Revit { public partial class ConverterRevit : ISpeckleConverter { #if REVIT2023 public static string RevitAppName = Applications.Revit2023; #elif REVIT2022 public static string RevitAppName = Applications.Revit2022; #elif REVIT2021 public static string RevitAppName = Applications.Revit2021; #elif REVIT2020 public static string RevitAppName = Applications.Revit2020; #else public static string RevitAppName = Applications.Revit2019; #endif #region ISpeckleConverter props public string Description => "Default Speckle Kit for Revit"; public string Name => nameof(ConverterRevit); public string Author => "Speckle"; public string WebsiteOrEmail => "https://speckle.systems"; public IEnumerable<string> GetServicedApplications() => new string[] { RevitAppName }; #endregion ISpeckleConverter props public Document Doc { get; private set; } /// <summary> /// <para>To know which other objects are being converted, in order to sort relationships between them. /// For example, elements that have children use this to determine whether they should send their children out or not.</para> /// </summary> public List<ApplicationPlaceholderObject> ContextObjects { get; set; } = new List<ApplicationPlaceholderObject>(); /// <summary> /// <para>To keep track of previously received objects from a given stream in here. If possible, conversions routines /// will edit an existing object, otherwise they will delete the old one and create the new one.</para> /// </summary> public List<ApplicationPlaceholderObject> PreviousContextObjects { get; set; } = new List<ApplicationPlaceholderObject>(); /// <summary> /// Keeps track of the current host element that is creating any sub-objects it may have. /// </summary> public HostObject CurrentHostElement { get; set; } /// <summary> /// Used when sending; keeps track of all the converted objects so far. Child elements first check in here if they should convert themselves again (they may have been converted as part of a parent's hosted elements). /// </summary> public List<string> ConvertedObjectsList { get; set; } = new List<string>(); public HashSet<Exception> ConversionErrors { get; private set; } = new HashSet<Exception>(); public Dictionary<string, BE.Level> Levels { get; private set; } = new Dictionary<string, BE.Level>(); public ConverterRevit() { } public void SetContextDocument(object doc) => Doc = (Document)doc; public void SetContextObjects(List<ApplicationPlaceholderObject> objects) => ContextObjects = objects; public void SetPreviousContextObjects(List<ApplicationPlaceholderObject> objects) => PreviousContextObjects = objects; public Base ConvertToSpeckle(object @object) { Base returnObject = null; switch (@object) { case DB.DetailCurve o: returnObject = DetailCurveToSpeckle(o); break; case DB.DirectShape o: returnObject = DirectShapeToSpeckle(o); break; case DB.FamilyInstance o: returnObject = FamilyInstanceToSpeckle(o); break; case DB.Floor o: returnObject = FloorToSpeckle(o); break; case DB.Level o: returnObject = LevelToSpeckle(o); break; case DB.View o: returnObject = ViewToSpeckle(o); break; case DB.ModelCurve o: if ((BuiltInCategory)o.Category.Id.IntegerValue == BuiltInCategory.OST_RoomSeparationLines) { returnObject = RoomBoundaryLineToSpeckle(o); } else { returnObject = ModelCurveToSpeckle(o); } break; case DB.Opening o: returnObject = OpeningToSpeckle(o); break; case DB.RoofBase o: returnObject = RoofToSpeckle(o); break; case DB.Area o: returnObject = AreaToSpeckle(o); break; case DB.Architecture.Room o: returnObject = RoomToSpeckle(o); break; case DB.Architecture.TopographySurface o: returnObject = TopographyToSpeckle(o); break; case DB.Wall o: returnObject = WallToSpeckle(o); break; case DB.Mechanical.Duct o: returnObject = DuctToSpeckle(o); break; case DB.Plumbing.Pipe o: returnObject = PipeToSpeckle(o); break; case DB.Electrical.Wire o: returnObject = WireToSpeckle(o); break; //these should be handled by curtain walls case DB.CurtainGridLine _: returnObject = null; break; case DB.Architecture.BuildingPad o: returnObject = BuildingPadToSpeckle(o); break; case DB.Architecture.Stairs o: returnObject = StairToSpeckle(o); break; //these are handled by Stairs case DB.Architecture.StairsRun _: returnObject = null; break; case DB.Architecture.StairsLanding _: returnObject = null; break; case DB.Architecture.Railing o: returnObject = RailingToSpeckle(o); break; case DB.Architecture.TopRail _: returnObject = null; break; case DB.Ceiling o: returnObject = CeilingToSpeckle(o); break; case DB.PointCloudInstance o: returnObject = PointcloudToSpeckle(o); break; case DB.ProjectInfo o: returnObject = ProjectInfoToSpeckle(o); break; case DB.ElementType o: returnObject = ElementTypeToSpeckle(o); break; case DB.Grid o: returnObject = GridLineToSpeckle(o); break; default: // if we don't have a direct conversion, still try to send this element as a generic RevitElement if ((@object as Element).IsElementSupported()) { returnObject = RevitElementToSpeckle(@object as Element); break; } ConversionErrors.Add(new Exception($"Skipping not supported type: {@object.GetType()}{GetElemInfo(@object)}")); returnObject = null; break; } // NOTE: Only try generic method assignment if there is no existing render material from conversions; // we might want to try later on to capture it more intelligently from inside conversion routines. if (returnObject != null && returnObject["renderMaterial"] == null) { var material = GetElementRenderMaterial(@object as DB.Element); returnObject["renderMaterial"] = material; } return returnObject; } private string GetElemInfo(object o) { if (o is Element e) { return $", name: {e.Name}, id: {e.UniqueId}"; } return ""; } public object ConvertToNative(Base @object) { // schema check var speckleSchema = @object["@SpeckleSchema"] as Base; if (speckleSchema != null) { // find self referential prop and set value to @object if it is null (happens when sent from gh) if (CanConvertToNative(speckleSchema)) { var prop = speckleSchema.GetInstanceMembers().Where(o => speckleSchema[o.Name] == null)?.Where(o => o.PropertyType.IsAssignableFrom(@object.GetType()))?.FirstOrDefault(); if (prop != null) speckleSchema[prop.Name] = @object; @object = speckleSchema; } } switch (@object) { //geometry case ICurve o: return ModelCurveToNative(o); case Geometry.Brep o: return DirectShapeToNative(o); case Geometry.Mesh o: return DirectShapeToNative(o); //built elems case BER.AdaptiveComponent o: return AdaptiveComponentToNative(o); case BE.Beam o: return BeamToNative(o); case BE.Brace o: return BraceToNative(o); case BE.Column o: return ColumnToNative(o); #if REVIT2022 case BE.Ceiling o: return CeilingToNative(o); #endif case BERC.DetailCurve o: return DetailCurveToNative(o); case BER.DirectShape o: return DirectShapeToNative(o); case BER.FreeformElement o: return FreeformElementToNative(o); case BER.FamilyInstance o: return FamilyInstanceToNative(o); case BE.Floor o: return FloorToNative(o); case BE.Level o: return LevelToNative(o); case BERC.ModelCurve o: return ModelCurveToNative(o); case BE.Opening o: return OpeningToNative(o); case BERC.RoomBoundaryLine o: return RoomBoundaryLineToNative(o); case BE.Roof o: return RoofToNative(o); case BE.Topography o: return TopographyToNative(o); case BER.RevitProfileWall o: return ProfileWallToNative(o); case BER.RevitFaceWall o: return FaceWallToNative(o); case BE.Wall o: return WallToNative(o); case BE.Duct o: return DuctToNative(o); case BE.Pipe o: return PipeToNative(o); case BE.Wire o: return WireToNative(o); case BE.Revit.RevitRailing o: return RailingToNative(o); case BER.ParameterUpdater o: UpdateParameter(o); return null; case BE.View3D o: return ViewToNative(o); case BE.Room o: return RoomToNative(o); case BE.GridLine o: return GridLineToNative(o); // other case Other.BlockInstance o: return BlockInstanceToNative(o); default: return null; } } public List<Base> ConvertToSpeckle(List<object> objects) => objects.Select(ConvertToSpeckle).ToList(); public List<object> ConvertToNative(List<Base> objects) => objects.Select(ConvertToNative).ToList(); public bool CanConvertToSpeckle(object @object) { return @object switch { DB.DetailCurve _ => true, DB.DirectShape _ => true, DB.FamilyInstance _ => true, DB.Floor _ => true, DB.Level _ => true, DB.View _ => true, DB.ModelCurve _ => true, DB.Opening _ => true, DB.RoofBase _ => true, DB.Area _ => true, DB.Architecture.Room _ => true, DB.Architecture.TopographySurface _ => true, DB.Wall _ => true, DB.Mechanical.Duct _ => true, DB.Plumbing.Pipe _ => true, DB.Electrical.Wire _ => true, DB.CurtainGridLine _ => true, //these should be handled by curtain walls DB.Architecture.BuildingPad _ => true, DB.Architecture.Stairs _ => true, DB.Architecture.StairsRun _ => true, DB.Architecture.StairsLanding _ => true, DB.Architecture.Railing _ => true, DB.Architecture.TopRail _ => true, DB.Ceiling _ => true, DB.PointCloudInstance _ => true, DB.Group _ => true, DB.ProjectInfo _ => true, DB.ElementType _ => true, DB.Grid _ => true, _ => (@object as Element).IsElementSupported() }; } public bool CanConvertToNative(Base @object) { var schema = @object["@SpeckleSchema"] as Base; // check for contained schema if (schema != null) return CanConvertToNative(schema); return @object switch { //geometry ICurve _ => true, Geometry.Brep _ => true, Geometry.Mesh _ => true, //built elems BER.AdaptiveComponent _ => true, BE.Beam _ => true, BE.Brace _ => true, BE.Column _ => true, #if REVIT2022 BE.Ceiling _ => true, #endif BERC.DetailCurve _ => true, BER.DirectShape _ => true, BER.FreeformElement _ => true, BER.FamilyInstance _ => true, BE.Floor _ => true, BE.Level _ => true, BERC.ModelCurve _ => true, BE.Opening _ => true, BERC.RoomBoundaryLine _ => true, BE.Roof _ => true, BE.Topography _ => true, BER.RevitFaceWall _ => true, BER.RevitProfileWall _ => true, BE.Wall _ => true, BE.Duct _ => true, BE.Pipe _ => true, BE.Wire _ => true, BE.Revit.RevitRailing _ => true, BER.ParameterUpdater _ => true, BE.View3D _ => true, BE.Room _ => true, BE.GridLine _ => true, Other.BlockInstance _ => true, _ => false }; } } }
30.886525
220
0.606582
[ "Apache-2.0" ]
pkratten/speckle-sharp
Objects/Converters/ConverterRevit/ConverterRevitShared/ConverterRevit.cs
13,067
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataStructures.Solutions.Fundamentals.ListsAndComplexity { public static class _05CountOfOccurences { public static Dictionary<int, int> CountOfOccurences(this int[] numbers) { List<int> countedNumbers = new List<int>(); Dictionary<int, int> occurences = new Dictionary<int, int>(); for (int i = 0; i < numbers.Length; i++) { int currentOccurences = 1; if (countedNumbers.Contains(numbers[i])) continue; for (int j = i + 1; j < numbers.Length; j++) { if (numbers[j] == numbers[i]) currentOccurences++; } occurences.Add(numbers[i], currentOccurences); countedNumbers.Add(numbers[i]); } return occurences; } } }
28.5
80
0.537037
[ "MIT" ]
Givko/DataStructures
DataStructuresSolutions/DataStructures.Solutions/Fundamentals/ListsAndComplexity/05CountOfOccurences.cs
1,028
C#
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using PureCloudPlatform.Client.V2.Client; namespace PureCloudPlatform.Client.V2.Model { /// <summary> /// LocationDefinition /// </summary> [DataContract] public partial class LocationDefinition : IEquatable<LocationDefinition> { /// <summary> /// Current state of the location entity /// </summary> /// <value>Current state of the location entity</value> [JsonConverter(typeof(UpgradeSdkEnumConverter))] public enum StateEnum { /// <summary> /// Your SDK version is out of date and an unknown enum value was encountered. /// Please upgrade the SDK using the command "Upgrade-Package PureCloudApiSdk" /// in the Package Manager Console /// </summary> [EnumMember(Value = "OUTDATED_SDK_VERSION")] OutdatedSdkVersion, /// <summary> /// Enum Active for "active" /// </summary> [EnumMember(Value = "active")] Active, /// <summary> /// Enum Deleted for "deleted" /// </summary> [EnumMember(Value = "deleted")] Deleted } /// <summary> /// Current state of the location entity /// </summary> /// <value>Current state of the location entity</value> [DataMember(Name="state", EmitDefaultValue=false)] public StateEnum? State { get; set; } /// <summary> /// Initializes a new instance of the <see cref="LocationDefinition" /> class. /// </summary> /// <param name="Name">Name.</param> /// <param name="ContactUser">Site contact for the location entity.</param> /// <param name="EmergencyNumber">Emergency number for the location entity.</param> /// <param name="Address">Address.</param> /// <param name="State">Current state of the location entity.</param> /// <param name="Notes">Notes for the location entity.</param> /// <param name="Version">Current version of the location entity, value to be supplied should be retrieved by a GET or on create/update response.</param> /// <param name="Path">A list of ancestor IDs in order.</param> /// <param name="ProfileImage">Profile image of the location entity, retrieved with ?expand=images query parameter.</param> /// <param name="FloorplanImage">Floorplan images of the location entity, retrieved with ?expand=images query parameter.</param> /// <param name="AddressVerificationDetails">Address verification information, retrieve dwith the ?expand=addressVerificationDetails query parameter.</param> /// <param name="Images">Images.</param> public LocationDefinition(string Name = null, AddressableEntityRef ContactUser = null, LocationEmergencyNumber EmergencyNumber = null, LocationAddress Address = null, StateEnum? State = null, string Notes = null, int? Version = null, List<string> Path = null, List<LocationImage> ProfileImage = null, List<LocationImage> FloorplanImage = null, LocationAddressVerificationDetails AddressVerificationDetails = null, string Images = null) { this.Name = Name; this.ContactUser = ContactUser; this.EmergencyNumber = EmergencyNumber; this.Address = Address; this.State = State; this.Notes = Notes; this.Version = Version; this.Path = Path; this.ProfileImage = ProfileImage; this.FloorplanImage = FloorplanImage; this.AddressVerificationDetails = AddressVerificationDetails; this.Images = Images; } /// <summary> /// The globally unique identifier for the object. /// </summary> /// <value>The globally unique identifier for the object.</value> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; private set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Site contact for the location entity /// </summary> /// <value>Site contact for the location entity</value> [DataMember(Name="contactUser", EmitDefaultValue=false)] public AddressableEntityRef ContactUser { get; set; } /// <summary> /// Emergency number for the location entity /// </summary> /// <value>Emergency number for the location entity</value> [DataMember(Name="emergencyNumber", EmitDefaultValue=false)] public LocationEmergencyNumber EmergencyNumber { get; set; } /// <summary> /// Gets or Sets Address /// </summary> [DataMember(Name="address", EmitDefaultValue=false)] public LocationAddress Address { get; set; } /// <summary> /// Notes for the location entity /// </summary> /// <value>Notes for the location entity</value> [DataMember(Name="notes", EmitDefaultValue=false)] public string Notes { get; set; } /// <summary> /// Current version of the location entity, value to be supplied should be retrieved by a GET or on create/update response /// </summary> /// <value>Current version of the location entity, value to be supplied should be retrieved by a GET or on create/update response</value> [DataMember(Name="version", EmitDefaultValue=false)] public int? Version { get; set; } /// <summary> /// A list of ancestor IDs in order /// </summary> /// <value>A list of ancestor IDs in order</value> [DataMember(Name="path", EmitDefaultValue=false)] public List<string> Path { get; set; } /// <summary> /// Profile image of the location entity, retrieved with ?expand=images query parameter /// </summary> /// <value>Profile image of the location entity, retrieved with ?expand=images query parameter</value> [DataMember(Name="profileImage", EmitDefaultValue=false)] public List<LocationImage> ProfileImage { get; set; } /// <summary> /// Floorplan images of the location entity, retrieved with ?expand=images query parameter /// </summary> /// <value>Floorplan images of the location entity, retrieved with ?expand=images query parameter</value> [DataMember(Name="floorplanImage", EmitDefaultValue=false)] public List<LocationImage> FloorplanImage { get; set; } /// <summary> /// Address verification information, retrieve dwith the ?expand=addressVerificationDetails query parameter /// </summary> /// <value>Address verification information, retrieve dwith the ?expand=addressVerificationDetails query parameter</value> [DataMember(Name="addressVerificationDetails", EmitDefaultValue=false)] public LocationAddressVerificationDetails AddressVerificationDetails { get; set; } /// <summary> /// Boolean field which states if the address has been verified as an actual address /// </summary> /// <value>Boolean field which states if the address has been verified as an actual address</value> [DataMember(Name="addressVerified", EmitDefaultValue=false)] public bool? AddressVerified { get; private set; } /// <summary> /// Boolean field which states if the address has been stored for E911 /// </summary> /// <value>Boolean field which states if the address has been stored for E911</value> [DataMember(Name="addressStored", EmitDefaultValue=false)] public bool? AddressStored { get; private set; } /// <summary> /// Gets or Sets Images /// </summary> [DataMember(Name="images", EmitDefaultValue=false)] public string Images { get; set; } /// <summary> /// The URI for this object /// </summary> /// <value>The URI for this object</value> [DataMember(Name="selfUri", EmitDefaultValue=false)] public string SelfUri { get; private 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 LocationDefinition {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" ContactUser: ").Append(ContactUser).Append("\n"); sb.Append(" EmergencyNumber: ").Append(EmergencyNumber).Append("\n"); sb.Append(" Address: ").Append(Address).Append("\n"); sb.Append(" State: ").Append(State).Append("\n"); sb.Append(" Notes: ").Append(Notes).Append("\n"); sb.Append(" Version: ").Append(Version).Append("\n"); sb.Append(" Path: ").Append(Path).Append("\n"); sb.Append(" ProfileImage: ").Append(ProfileImage).Append("\n"); sb.Append(" FloorplanImage: ").Append(FloorplanImage).Append("\n"); sb.Append(" AddressVerificationDetails: ").Append(AddressVerificationDetails).Append("\n"); sb.Append(" AddressVerified: ").Append(AddressVerified).Append("\n"); sb.Append(" AddressStored: ").Append(AddressStored).Append("\n"); sb.Append(" Images: ").Append(Images).Append("\n"); sb.Append(" SelfUri: ").Append(SelfUri).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, new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore, Formatting = 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 LocationDefinition); } /// <summary> /// Returns true if LocationDefinition instances are equal /// </summary> /// <param name="other">Instance of LocationDefinition to be compared</param> /// <returns>Boolean</returns> public bool Equals(LocationDefinition other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return true && ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.ContactUser == other.ContactUser || this.ContactUser != null && this.ContactUser.Equals(other.ContactUser) ) && ( this.EmergencyNumber == other.EmergencyNumber || this.EmergencyNumber != null && this.EmergencyNumber.Equals(other.EmergencyNumber) ) && ( this.Address == other.Address || this.Address != null && this.Address.Equals(other.Address) ) && ( this.State == other.State || this.State != null && this.State.Equals(other.State) ) && ( this.Notes == other.Notes || this.Notes != null && this.Notes.Equals(other.Notes) ) && ( this.Version == other.Version || this.Version != null && this.Version.Equals(other.Version) ) && ( this.Path == other.Path || this.Path != null && this.Path.SequenceEqual(other.Path) ) && ( this.ProfileImage == other.ProfileImage || this.ProfileImage != null && this.ProfileImage.SequenceEqual(other.ProfileImage) ) && ( this.FloorplanImage == other.FloorplanImage || this.FloorplanImage != null && this.FloorplanImage.SequenceEqual(other.FloorplanImage) ) && ( this.AddressVerificationDetails == other.AddressVerificationDetails || this.AddressVerificationDetails != null && this.AddressVerificationDetails.Equals(other.AddressVerificationDetails) ) && ( this.AddressVerified == other.AddressVerified || this.AddressVerified != null && this.AddressVerified.Equals(other.AddressVerified) ) && ( this.AddressStored == other.AddressStored || this.AddressStored != null && this.AddressStored.Equals(other.AddressStored) ) && ( this.Images == other.Images || this.Images != null && this.Images.Equals(other.Images) ) && ( this.SelfUri == other.SelfUri || this.SelfUri != null && this.SelfUri.Equals(other.SelfUri) ); } /// <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.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.ContactUser != null) hash = hash * 59 + this.ContactUser.GetHashCode(); if (this.EmergencyNumber != null) hash = hash * 59 + this.EmergencyNumber.GetHashCode(); if (this.Address != null) hash = hash * 59 + this.Address.GetHashCode(); if (this.State != null) hash = hash * 59 + this.State.GetHashCode(); if (this.Notes != null) hash = hash * 59 + this.Notes.GetHashCode(); if (this.Version != null) hash = hash * 59 + this.Version.GetHashCode(); if (this.Path != null) hash = hash * 59 + this.Path.GetHashCode(); if (this.ProfileImage != null) hash = hash * 59 + this.ProfileImage.GetHashCode(); if (this.FloorplanImage != null) hash = hash * 59 + this.FloorplanImage.GetHashCode(); if (this.AddressVerificationDetails != null) hash = hash * 59 + this.AddressVerificationDetails.GetHashCode(); if (this.AddressVerified != null) hash = hash * 59 + this.AddressVerified.GetHashCode(); if (this.AddressStored != null) hash = hash * 59 + this.AddressStored.GetHashCode(); if (this.Images != null) hash = hash * 59 + this.Images.GetHashCode(); if (this.SelfUri != null) hash = hash * 59 + this.SelfUri.GetHashCode(); return hash; } } } }
35.576108
443
0.503791
[ "MIT" ]
F-V-L/platform-client-sdk-dotnet
build/src/PureCloudPlatform.Client.V2/Model/LocationDefinition.cs
18,464
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Shinomotazh.Logic { class TireService { Random _random = new Random(); Ads _ads = new Ads(); List<Demands> _demands = new List<Demands>();//Список заказов по дням (каждый элемент - список заказов в i день) Season _season; double rent_cost; double salaries_cost; double equipment_maintenance; AutherShine autherShine = new AutherShine(); double rest; public double comPlat; public double strax; Boolean weHaveNewShineAround; public TireService(DateTime simulated_date, double rent, double salaries) { rent_cost = rent; salaries_cost = salaries; _season = new Season(simulated_date); _demands.Add(GetDailyDemands()); } public Demands GetDailyDemands() { int ads_clients = _ads.GetClientQuantity(); double season_eff = _season.getCurrentSeasonEfficiency(); int daily_demands_quantity = (int)((_random.Next(5, 25) + ads_clients) * season_eff); return new Demands(daily_demands_quantity); } public double GetDailyProfit(int A) { equipment_maintenance = _demands.Last().GetSize() * 10; if (A == 2) rest = 0; else rest = rent_cost + salaries_cost + comPlat + strax; double res = _demands.Last().getProfit() - equipment_maintenance - rest + autherShine.dopMoneyForPrice; weHaveNewShineAround = autherShine.NewShineGo(res); if (weHaveNewShineAround == true) { autherShine.NewShine(); } return res > 0 ? res * 0.7 : res; } public double GetADSBudget() { double ads_budget = 0.0 >= GetDailyProfit(2) ? 0.0 : GetDailyProfit(2) * 0.3; return ads_budget; } public void NextDay() { _demands.Add(GetDailyDemands()); _ads.GiveMoneyForADS(GetADSBudget()); _season.addDay(); } public double newYear() { var rand = new Random(); double money=rand.Next(1, 5)*200; //вероятность поломки оборудования и его закупка return money; } } }
28.455696
120
0.625445
[ "MIT" ]
Zeleno-glazka/github-slideshow
Shinomotazh(1)/Logic/TireService.cs
2,339
C#
using System; namespace AbstractIO { /// <summary> /// A base class implementing the IDisposable interface and pattern and letting the dipose happen in a virtual /// method. /// </summary> public abstract class DisposableResourceBase : IDisposable { /// <summary> /// Disposes the disposable managed ressource. This method will be called by the Dispose() method when /// appropriate. Inheritors should still take care of not disposing the same resource multiple times if that /// could cause problems, as this method might be called more than once for the same object. /// </summary> protected abstract void DisposeResource(); /// <summary> /// Gets whether this object has been disposed. /// </summary> protected bool IsDisposed { get { return _disposedValue; } } #region IDisposable Support private bool _disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). DisposeResource(); } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. _disposedValue = true; } } // This code added to correctly implement the disposable pattern. void IDisposable.Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); // TODO: uncomment the following line if the finalizer is overridden above. // GC.SuppressFinalize(this); } #endregion } }
31.693548
116
0.569975
[ "MIT" ]
piwi1263/AbstractIO
source/AbstractIO/DisposableResourceBase.cs
1,967
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace web { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); }); } } }
28.18
107
0.567069
[ "MIT" ]
pollirrata/memoru
source/web/Startup.cs
1,409
C#
// Decompiled with JetBrains decompiler // Type: BlueStacks.BlueStacksUI.TopBar // Assembly: Bluestacks, Version=4.250.0.1070, Culture=neutral, PublicKeyToken=null // MVID: 99F027F6-79F1-4BCA-896C-81F7B404BE8F // Assembly location: C:\Program Files\BlueStacks\Bluestacks.exe using BlueStacks.BlueStacksUI.BTv; using BlueStacks.Common; using Microsoft.VisualBasic.Devices; using Newtonsoft.Json.Linq; using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Shapes; using System.Windows.Threading; namespace BlueStacks.BlueStacksUI { public class TopBar : UserControl, ITopBar, IComponentConnector { private SortedList<int, KeyValuePair<FrameworkElement, double>> mOptionsPriorityPanel = new SortedList<int, KeyValuePair<FrameworkElement, double>>(); internal double mMinimumExpectedTopBarWidth = 320.0; private ulong MB_MULTIPLIER = 1048576; private MainWindow mMainWindow; internal PerformanceState mSnailMode; private DispatcherTimer mMacroRunningPopupTimer; private DispatcherTimer mMacroRecordingPopupTimer; internal Grid mMainGrid; internal Grid WindowHeaderGrid; internal CustomPictureBox mTitleIcon; internal Grid mTitleTextGrid; internal TextBlock mTitleText; internal TextBlock mVersionText; internal DockPanel mOptionsDockPanel; internal CustomPictureBox mSidebarButton; internal CustomPictureBox mCloseButton; internal CustomPictureBox mMaximizeButton; internal CustomPictureBox mMinimizeButton; internal Grid mConfigButtonGrid; internal CustomPictureBox mConfigButton; internal Ellipse mSettingsBtnNotification; internal CustomPopUp mSettingsMenuPopup; internal Border mPreferenceDropDownBorder; internal Grid mGrid; internal Border mMaskBorder; internal PreferenceDropDownControl mPreferenceDropDownControl; internal CustomPictureBox mHelpButton; internal CustomPictureBox mUserAccountBtn; internal Grid mNotificationGrid; internal CustomPictureBox mNotificationCentreButton; internal Canvas mNotificationCountBadge; internal CustomPopUp mNotificationCentrePopup; internal Path mNotificationCaret; internal Border mNotificationCentreDropDownBorder; internal Border mMaskBorder1; internal NotificationDrawer mNotificationDrawerControl; internal CustomPictureBox mBtvButton; internal CustomPictureBox mWarningButton; internal Grid mOperationsSyncGrid; internal Border mSyncMaskBorder; internal CustomPictureBox mPlayPauseSyncButton; internal CustomPictureBox mStopSyncButton; internal CustomPopUp mSyncInstancesToolTipPopup; internal Grid mDummyGrid; internal Border mMaskBorder2; internal Path mUpwardArrow; internal CustomPictureBox mLocalConfigIndicator; internal AppTabButtons mAppTabButtons; internal Grid mVideoRecordingStatusGrid; internal VideoRecordingStatus mVideoRecordStatusControl; internal Grid mMacroGrid; internal MacroTopBarRecordControl mMacroRecordControl; internal MacroTopBarPlayControl mMacroPlayControl; internal CustomPopUp mMacroRecorderToolTipPopup; internal Grid dummyGrid; internal Border mMaskBorder3; internal TextBlock mMacroRecordingTooltip; internal Path mUpArrow; internal CustomPopUp mMacroRunningToolTipPopup; internal Grid grid; internal Border mMaskBorder4; internal TextBlock mMacroRunningTooltip; private bool _contentLoaded; public MainWindow ParentWindow { get { if (this.mMainWindow == null) this.mMainWindow = Window.GetWindow((DependencyObject) this) as MainWindow; return this.mMainWindow; } } public event PercentageChangedEventHandler PercentChanged; string ITopBar.AppName { get { return (string) null; } set { } } string ITopBar.CharacterName { get { return (string) null; } set { } } public static Point GetMousePosition() { NativeMethods.Win32Point pt = new NativeMethods.Win32Point(); NativeMethods.GetCursorPos(ref pt); return new Point((double) pt.X, (double) pt.Y); } public TopBar() { this.InitializeComponent(); if (FeatureManager.Instance.IsCustomUIForDMMSandbox) { this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mUserAccountBtn, false); this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mWarningButton, false); this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mHelpButton, false); } else { if (!FeatureManager.Instance.IsUserAccountBtnEnabled) this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mUserAccountBtn, false); if (!FeatureManager.Instance.IsWarningBtnEnabled) this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mWarningButton, false); this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mHelpButton, FeatureManager.Instance.IsTopbarHelpEnabled); } if (Oem.IsOEMDmm) { this.mConfigButton.Visibility = Visibility.Collapsed; this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mNotificationGrid, false); this.WindowHeaderGrid.Visibility = Visibility.Collapsed; this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mUserAccountBtn, false); this.mWarningButton.ToolTip = (object) null; this.mSidebarButton.Visibility = Visibility.Collapsed; this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mHelpButton, false); } if (RegistryManager.Instance.InstallationType == InstallationTypes.GamingEdition) { this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mUserAccountBtn, false); this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mNotificationGrid, false); } if (!string.Equals(this.mTitleIcon.ImageName, BlueStacks.Common.Strings.TitleBarIconImageName, StringComparison.InvariantCulture)) this.mTitleIcon.ImageName = BlueStacks.Common.Strings.TitleBarIconImageName; double? nullable = BlueStacks.Common.Strings.TitleBarProductIconWidth; if (nullable.HasValue) { CustomPictureBox mTitleIcon = this.mTitleIcon; nullable = BlueStacks.Common.Strings.TitleBarProductIconWidth; double num = nullable.Value; mTitleIcon.Width = num; } nullable = BlueStacks.Common.Strings.TitleBarTextMaxWidth; if (nullable.HasValue) { TextBlock mTitleText = this.mTitleText; nullable = BlueStacks.Common.Strings.TitleBarTextMaxWidth; double num = nullable.Value; mTitleText.MaxWidth = num; } this.mVersionText.Text = RegistryManager.Instance.ClientVersion; } private void ParentWindow_GuestBootCompletedEvent(object sender, EventArgs args) { if (!this.ParentWindow.EngineInstanceRegistry.IsSidebarVisible || this.Visibility != Visibility.Visible || (this.ParentWindow.mSidebar.Visibility == Visibility.Visible || Oem.IsOEMDmm)) return; this.ParentWindow.Dispatcher.Invoke((Delegate) (() => this.ParentWindow.mCommonHandler.FlipSidebarVisibility(this.mSidebarButton, (TextBlock) null))); } internal void ChangeDownloadPercent(int percent) { PercentageChangedEventHandler percentChanged = this.PercentChanged; if (percentChanged == null) return; percentChanged((object) this, new PercentageChangedEventArgs() { Percentage = percent }); } internal void InitializeSnailButton() { if (FeatureManager.Instance.IsCustomUIForDMMSandbox || !FeatureManager.Instance.IsWarningBtnEnabled) return; string deviceCaps = RegistryManager.Instance.DeviceCaps; if (string.IsNullOrEmpty(deviceCaps)) { this.mSnailMode = PerformanceState.VtxEnabled; this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mWarningButton, false); } else { JObject deviceCapsData = JObject.Parse(deviceCaps); this.Dispatcher.Invoke((Delegate) (() => { if (deviceCapsData["cpu_hvm"].ToString().Equals("True", StringComparison.OrdinalIgnoreCase) && deviceCapsData["bios_hvm"].ToString().Equals("False", StringComparison.OrdinalIgnoreCase)) { if (deviceCapsData["engine_enabled"].ToString().Equals(EngineState.raw.ToString(), StringComparison.OrdinalIgnoreCase)) { this.mSnailMode = PerformanceState.VtxDisabled; this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mWarningButton, true); } } else if (deviceCapsData["cpu_hvm"].ToString().Equals("False", StringComparison.OrdinalIgnoreCase)) { this.mSnailMode = PerformanceState.NoVtxSupport; this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mWarningButton, true); } else if (deviceCapsData["cpu_hvm"].ToString().Equals("True", StringComparison.OrdinalIgnoreCase) && deviceCapsData["bios_hvm"].ToString().Equals("True", StringComparison.OrdinalIgnoreCase)) { this.mSnailMode = PerformanceState.VtxEnabled; this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mWarningButton, false); } this.RefreshWarningButton(); })); } } internal void RefreshWarningButton() { if (FeatureManager.Instance.IsCustomUIForDMMSandbox || !FeatureManager.Instance.IsWarningBtnEnabled) return; if (this.mSnailMode != PerformanceState.VtxEnabled) { this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mWarningButton, true); this.AddVtxNotification(); } else this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mWarningButton, false); } internal void AddVtxNotification() { if (Oem.IsOEMDmm) return; this.Dispatcher.Invoke((Delegate) (() => { bool dontOverwrite = true; GenericNotificationItem notificationItem = new GenericNotificationItem() { CreationTime = DateTime.Now, IsDeferred = false, Priority = NotificationPriority.Important, ShowRibbon = false, Id = "VtxNotification", NotificationMenuImageName = "SlowPerformance.png", Title = LocaleStrings.GetLocalizedString("STRING_DISABLED_VT_TITLE", ""), Message = LocaleStrings.GetLocalizedString("STRING_DISABLED_VT", "") }; SerializableDictionary<string, string> serializableDictionary = new SerializableDictionary<string, string>() { { "click_generic_action", "UserBrowser" }, { "click_action_value", WebHelper.GetUrlWithParams(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "{0}/{1}", (object) WebHelper.GetServerHost(), (object) "help_articles"), (string) null, (string) null, (string) null) + "&article=enable_virtualization" } }; notificationItem.ExtraPayload.ClearAddRange<string, string>((Dictionary<string, string>) serializableDictionary); GenericNotificationManager.AddNewNotification(notificationItem, dontOverwrite); this.RefreshNotificationCentreButton(); })); } internal void AddRamNotification() { this.Dispatcher.Invoke((Delegate) (() => { bool dontOverwrite = true; GenericNotificationItem notificationItem = new GenericNotificationItem() { IsDeferred = false, Priority = NotificationPriority.Important, ShowRibbon = false, Id = "ramNotification", NotificationMenuImageName = "SlowPerformance.png", Title = LocaleStrings.GetLocalizedString("STRING_RAM_NOTIF_TITLE", ""), Message = LocaleStrings.GetLocalizedString("STRING_RAM_NOTIF", "") }; SerializableDictionary<string, string> serializableDictionary = new SerializableDictionary<string, string>() { { "click_generic_action", "UserBrowser" }, { "click_action_value", WebHelper.GetUrlWithParams(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "{0}/{1}", (object) WebHelper.GetServerHost(), (object) "help_articles"), (string) null, (string) null, (string) null) + "&article=bs3_nougat_min_requirements" } }; notificationItem.ExtraPayload.ClearAddRange<string, string>((Dictionary<string, string>) serializableDictionary); GenericNotificationManager.AddNewNotification(notificationItem, dontOverwrite); this.RefreshNotificationCentreButton(); })); } private void UserAccountButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { Logger.Info("Clicked account button"); if (!this.ParentWindow.mGuestBootCompleted || !this.ParentWindow.mAppHandler.IsOneTimeSetupCompleted) return; if (FeatureManager.Instance.IsOpenActivityFromAccountIcon) this.mAppTabButtons.AddAppTab("STRING_ACCOUNT", BlueStacksUIUtils.sUserAccountPackageName, BlueStacksUIUtils.sUserAccountActivityName, "account_tab", true, true, false); else this.mAppTabButtons.AddWebTab(WebHelper.GetUrlWithParams(WebHelper.GetServerHost() + "/bluestacks_account", (string) null, (string) null, (string) null) + "&email=" + RegistryManager.Instance.RegisteredEmail + "&token=" + RegistryManager.Instance.Token, "STRING_ACCOUNT", "account_tab", true, "account_tab", false); } private void ConfigButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { this.mPreferenceDropDownControl.LateInit(); this.mSettingsMenuPopup.IsOpen = true; this.mSettingsMenuPopup.HorizontalOffset = -(this.mPreferenceDropDownBorder.ActualWidth - 40.0); this.mConfigButton.ImageName = "cfgmenu_hover"; } private void MinimizeButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { Logger.Info("Clicked minimize button"); this.ParentWindow.MinimizeWindow(); } internal void MaxmizeButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { Logger.Info("Clicked Maximize\\Restore button"); if (this.ParentWindow.WindowState == WindowState.Normal && !this.ParentWindow.mIsDmmMaximised) this.ParentWindow.MaximizeWindow(); else this.ParentWindow.RestoreWindows(false); } internal void SetConfigIndicator(string config) { this.mLocalConfigIndicator.Visibility = string.Equals(config, ".config_user.db", StringComparison.InvariantCultureIgnoreCase) ? Visibility.Visible : Visibility.Collapsed; } private void CloseButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { Logger.Info("Clicked close Bluestacks button"); BlueStacks.Common.Stats.SendCommonClientStatsAsync("notification_mode", "BlueStacks_close", this.ParentWindow.mVmName, "", "", "", ""); if (RegistryManager.Instance.IsNotificationModeAlwaysOn && string.Compare("Android", this.ParentWindow.mVmName, StringComparison.InvariantCultureIgnoreCase) == 0) { if (this.ParentWindow.Utils.CheckQuitPopupLocal()) return; BlueStacks.Common.Stats.SendCommonClientStatsAsync("notification_mode", "notification_mode", this.ParentWindow.mVmName, string.Empty, "on", "", ""); this.ParentWindow.EngineInstanceRegistry.IsMinimizeSelectedOnReceiveGameNotificationPopup = true; this.ParentWindow.IsInNotificationMode = true; foreach (string key in this.ParentWindow.AppNotificationCountDictForEachVM.Keys) BlueStacks.Common.Stats.SendCommonClientStatsAsync("notification_mode", "notification_number", this.ParentWindow.mVmName, key, this.ParentWindow.AppNotificationCountDictForEachVM[key].ToString((IFormatProvider) CultureInfo.InvariantCulture), "NM_Off", ""); this.ParentWindow.AppNotificationCountDictForEachVM.Clear(); this.ParentWindow.MinimizeWindowHandler(); } else { BlueStacks.Common.Stats.SendCommonClientStatsAsync("notification_mode", "notification_mode", this.ParentWindow.mVmName, string.Empty, "off", "", ""); this.ParentWindow.CloseWindow(); } } private void NotificationPopup_Opened(object sender, EventArgs e) { this.mConfigButton.IsEnabled = false; } private void NotificationPopup_Closed(object sender, EventArgs e) { this.mConfigButton.IsEnabled = true; this.mConfigButton.ImageName = "cfgmenu"; } internal void ChangeUserPremiumButton(bool isPremium) { if (isPremium) this.mUserAccountBtn.ImageName = BlueStacksUIUtils.sPremiumUserImageName; else this.mUserAccountBtn.ImageName = BlueStacksUIUtils.sLoggedInImageName; } private void PreferenceDropDownControl_MouseDoubleClick(object sender, MouseButtonEventArgs e) { e.Handled = true; } private void mWarningButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { Logger.Info("Clicked warning button for speed up Bluestacks "); this.mWarningButton.ImageName = "warning"; SpeedUpBlueStacks speedUpBlueStacks = new SpeedUpBlueStacks(); if (this.mSnailMode == PerformanceState.NoVtxSupport) speedUpBlueStacks.mUpgradeComputer.Visibility = Visibility.Visible; else if (this.mSnailMode == PerformanceState.VtxDisabled) speedUpBlueStacks.mEnableVt.Visibility = Visibility.Visible; ContainerWindow containerWindow = new ContainerWindow(this.ParentWindow, (UserControl) speedUpBlueStacks, 640.0, 200.0, false, true, false, -1.0, (Brush) null); } private void mBtvButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { Logger.Info("Clicked btv button"); BTVManager.Instance.StartBlueStacksTV(); } private void TopBar_Loaded(object sender, RoutedEventArgs e) { if (FeatureManager.Instance.IsBTVEnabled && string.Equals(BlueStacks.Common.Strings.CurrentDefaultVmName, this.ParentWindow.mVmName, StringComparison.InvariantCulture)) this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mBtvButton, true); this.RefreshNotificationCentreButton(); if (!this.ParentWindow.mGuestBootCompleted) { this.ParentWindow.mCommonHandler.SetSidebarImageProperties(false, this.mSidebarButton, (TextBlock) null); this.ParentWindow.GuestBootCompleted += new MainWindow.GuestBootCompletedEventHandler(this.ParentWindow_GuestBootCompletedEvent); } this.ParentWindow.mCommonHandler.ScreenRecordingStateChangedEvent += new CommonHandlers.ScreenRecordingStateChanged(this.TopBar_ScreenRecordingStateChangedEvent); this.mVideoRecordStatusControl.RecordingStoppedEvent += new System.Action(this.TopBar_RecordingStoppedEvent); if (!(this.ParentWindow.mVmName == "Android") || !this.mTitleIcon.ToolTip.ToString().Equals(BlueStacks.Common.Strings.ProductTopBarDisplayName, StringComparison.OrdinalIgnoreCase)) return; CustomPictureBox mTitleIcon = this.mTitleIcon; ToolTip toolTip = new ToolTip(); toolTip.Content = (object) (BlueStacks.Common.Strings.ProductDisplayName ?? ""); mTitleIcon.ToolTip = (object) toolTip; } private void TopBar_RecordingStoppedEvent() { this.ParentWindow.Dispatcher.Invoke((Delegate) (() => this.mVideoRecordStatusControl.Visibility = Visibility.Collapsed)); } private void TopBar_ScreenRecordingStateChangedEvent(bool isRecording) { this.ParentWindow.Dispatcher.Invoke((Delegate) (() => { if (isRecording) { if (this.mVideoRecordStatusControl.Visibility == Visibility.Visible || !CommonHandlers.sIsRecordingVideo) return; this.mVideoRecordStatusControl.Init(this.ParentWindow); this.mVideoRecordStatusControl.Visibility = Visibility.Visible; } else { this.mVideoRecordStatusControl.ResetTimer(); this.mVideoRecordStatusControl.Visibility = Visibility.Collapsed; } })); } public void mNotificationCentreButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { Logger.Info("Clicked notification_centre button"); this.mNotificationDrawerControl.Width = 320.0; SerializableDictionary<string, GenericNotificationItem> notificationItems = GenericNotificationManager.GetNotificationItems((Predicate<GenericNotificationItem>) (x => { if (x.IsDeleted) return false; return string.Equals(x.VmName, this.ParentWindow.mVmName, StringComparison.InvariantCulture) || !x.IsAndroidNotification; })); this.mNotificationDrawerControl.Populate(notificationItems); ClientStats.SendMiscellaneousStatsAsync("NotificationBellIconClicked", RegistryManager.Instance.UserGuid, RegistryManager.Instance.ClientVersion, (string) null, (string) null, (string) null, (string) null, (string) null, (string) null, "Android"); GenericNotificationManager.MarkNotification((IEnumerable<string>) notificationItems.Keys, (System.Action<GenericNotificationItem>) (x => { if (!x.IsReceivedStatSent || x.IsDeleted || (x.IsShown || x.IsAndroidNotification)) return; x.IsShown = true; ClientStats.SendMiscellaneousStatsAsync("notification_shown", RegistryManager.Instance.UserGuid, RegistryManager.Instance.ClientVersion, x.Id, x.Title, x.ExtraPayload.ContainsKey("campaign_id") ? x.ExtraPayload["campaign_id"] : "", (string) null, (string) null, (string) null, "Android"); })); this.mNotificationDrawerControl.UpdateNotificationCount(); if (sender != null) { this.mNotificationCentreButton.ImageName = "notification"; this.mNotificationCountBadge.Visibility = Visibility.Collapsed; } else NotificationDrawer.DrawerAnimationTimer.Start(); this.mNotificationCentrePopup.IsOpen = true; this.mNotificationDrawerControl.mNotificationScroll.ScrollToTop(); this.mNotificationCentreButton.ImageName = "notification_hover"; } internal bool CheckForRam() { int num = 0; try { num = (int) (ulong.Parse(new ComputerInfo().TotalPhysicalMemory.ToString((IFormatProvider) CultureInfo.InvariantCulture), (IFormatProvider) CultureInfo.InvariantCulture) / this.MB_MULTIPLIER); } catch (Exception ex) { Logger.Error(ex.ToString()); } return num < 4096; } internal void RefreshNotificationCentreButton() { if (this.ParentWindow.EngineInstanceRegistry.IsGoogleSigninDone && FeatureManager.Instance.IsShowNotificationCentre && RegistryManager.Instance.InstallationType != InstallationTypes.GamingEdition) { this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mNotificationGrid, true); this.mNotificationCentreButton.ImageName = GenericNotificationManager.GetNotificationItems((Predicate<GenericNotificationItem>) (x => !x.IsRead && !x.IsDeleted && x.Priority == NotificationPriority.Important)).Count <= 0 ? "notification" : "notification_crucial"; this.mNotificationDrawerControl.UpdateNotificationCount(); } else this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mNotificationGrid, false); } internal void mNotificationCentreDropDownBorder_LayoutUpdated(object sender, EventArgs e) { RectangleGeometry rectangleGeometry = new RectangleGeometry(); Rect rect = new Rect() { Height = this.mNotificationCentreDropDownBorder.ActualHeight, Width = this.mNotificationCentreDropDownBorder.ActualWidth }; BlueStacksUIBinding.BindCornerRadiusToDouble((DependencyObject) rectangleGeometry, RectangleGeometry.RadiusXProperty, "PreferenceDropDownRadius"); BlueStacksUIBinding.BindCornerRadiusToDouble((DependencyObject) rectangleGeometry, RectangleGeometry.RadiusYProperty, "PreferenceDropDownRadius"); rectangleGeometry.Rect = rect; this.mNotificationCentreDropDownBorder.Clip = (Geometry) rectangleGeometry; } internal void ShowRecordingIcons() { this.mMacroRecordControl.Init(this.ParentWindow); this.mMacroRecordControl.Visibility = Visibility.Visible; this.mMacroRecordControl.StartTimer(); if (this.ParentWindow.mIsFullScreen) return; this.ParentWindow.mTopBar.mMacroRecorderToolTipPopup.IsOpen = true; this.ParentWindow.mTopBar.mMacroRecorderToolTipPopup.StaysOpen = true; this.mMacroRecordingPopupTimer = new DispatcherTimer() { Interval = new TimeSpan(0, 0, 0, 5, 0) }; this.mMacroRecordingPopupTimer.Tick += new EventHandler(this.MacroRecordingPopupTimer_Tick); this.mMacroRecordingPopupTimer.Start(); } private void MacroRecordingPopupTimer_Tick(object sender, EventArgs e) { this.ParentWindow.mTopBar.mMacroRecorderToolTipPopup.IsOpen = false; (sender as DispatcherTimer).Stop(); } internal void HideRecordingIcons() { this.mConfigButton.Visibility = Visibility.Visible; if (this.ParentWindow.EngineInstanceRegistry.IsGoogleSigninDone) { this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mNotificationGrid, true); this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mUserAccountBtn, true); } this.mMacroRecordControl.Visibility = Visibility.Collapsed; this.mMacroRecorderToolTipPopup.IsOpen = false; } internal void ShowMacroPlaybackOnTopBar(MacroRecording record) { if (Oem.IsOEMDmm) return; this.mMacroPlayControl.Init(this.ParentWindow, record); this.mMacroPlayControl.Visibility = Visibility.Visible; if (this.ParentWindow.mIsFullScreen) return; this.ParentWindow.mTopBar.mMacroRunningToolTipPopup.IsOpen = true; this.ParentWindow.mTopBar.mMacroRunningToolTipPopup.StaysOpen = true; this.mMacroRunningPopupTimer = new DispatcherTimer() { Interval = new TimeSpan(0, 0, 0, 5, 0) }; this.mMacroRunningPopupTimer.Tick += new EventHandler(this.MacroRunningPopupTimer_Tick); this.mMacroRunningPopupTimer.Start(); } private void MacroRunningPopupTimer_Tick(object sender, EventArgs e) { this.ParentWindow.mTopBar.mMacroRunningToolTipPopup.IsOpen = false; (sender as DispatcherTimer).Stop(); } internal void HideMacroPlaybackFromTopBar() { if (Oem.IsOEMDmm) return; this.mConfigButton.Visibility = Visibility.Visible; if (this.ParentWindow.EngineInstanceRegistry.IsGoogleSigninDone) { this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mNotificationGrid, true); this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mUserAccountBtn, true); } this.mMacroPlayControl.Visibility = Visibility.Collapsed; } internal void UpdateMacroRecordingProgress() { if (!this.ParentWindow.mIsMacroPlaying && !this.ParentWindow.mIsMacroRecorderActive) return; this.mConfigButton.Visibility = Visibility.Visible; if (!this.ParentWindow.EngineInstanceRegistry.IsGoogleSigninDone) return; this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mNotificationGrid, true); this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mUserAccountBtn, true); } internal void ShowSyncIcon() { this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mOperationsSyncGrid, true); } internal void HideSyncIcon() { this.TopBarOptionsPanelElementVisibility((FrameworkElement) this.mOperationsSyncGrid, false); } private void MSidebarButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { this.ParentWindow?.mCommonHandler?.FlipSidebarVisibility(sender as CustomPictureBox, (TextBlock) null); } private void TopBar_SizeChanged(object sender, SizeChangedEventArgs e) { if (DesignerProperties.GetIsInDesignMode((DependencyObject) this)) return; this.TopBarButtonsHandling(); } private void TopBarButtonsHandling() { double num = this.ActualWidth - 180.0 - (double) (this.mAppTabButtons.mDictTabs.Count * 48); double actualWidth = this.mOptionsDockPanel.ActualWidth; if (actualWidth > num) { foreach (KeyValuePair<FrameworkElement, double> keyValuePair in (IEnumerable<KeyValuePair<FrameworkElement, double>>) this.mOptionsPriorityPanel.Values) { if (keyValuePair.Key.Visibility == Visibility.Visible) { keyValuePair.Key.Visibility = Visibility.Collapsed; actualWidth -= keyValuePair.Value; } if (actualWidth < num) break; } } else { for (int index = this.mOptionsPriorityPanel.Count - 1; index >= 0; --index) { KeyValuePair<FrameworkElement, double> keyValuePair = this.mOptionsPriorityPanel.ElementAt<KeyValuePair<int, KeyValuePair<FrameworkElement, double>>>(index).Value; if (keyValuePair.Key.Visibility == Visibility.Collapsed) { if (actualWidth + keyValuePair.Value >= num) break; keyValuePair.Key.Visibility = Visibility.Visible; actualWidth += keyValuePair.Value; } } } } private bool ContainsKey(FrameworkElement element) { foreach (KeyValuePair<FrameworkElement, double> keyValuePair in (IEnumerable<KeyValuePair<FrameworkElement, double>>) this.mOptionsPriorityPanel.Values) { if (keyValuePair.Key == element) return true; } return false; } private void RemoveKey(FrameworkElement element) { foreach (KeyValuePair<int, KeyValuePair<FrameworkElement, double>> keyValuePair in this.mOptionsPriorityPanel) { if (keyValuePair.Value.Key == element) { this.mOptionsPriorityPanel.Remove(keyValuePair.Key); break; } } } internal void TopBarOptionsPanelElementVisibility(FrameworkElement element, bool isVisible) { if (isVisible) { double num = this.ActualWidth - 180.0 - (double) (this.mAppTabButtons.mDictTabs.Count * 48); if (this.mOptionsDockPanel.ActualWidth + element.Width < num) element.Visibility = Visibility.Visible; else element.Visibility = Visibility.Collapsed; if (this.ContainsKey(element)) return; this.mOptionsPriorityPanel.Add(int.Parse(element.Tag.ToString(), (IFormatProvider) CultureInfo.InvariantCulture), new KeyValuePair<FrameworkElement, double>(element, element.Width)); } else { element.Visibility = Visibility.Collapsed; if (!this.ContainsKey(element)) return; this.RemoveKey(element); } } void ITopBar.ShowSyncPanel(bool isSource) { this.mOperationsSyncGrid.Visibility = Visibility.Visible; if (!isSource) return; this.mPlayPauseSyncButton.ImageName = "pause_title_bar"; this.mPlayPauseSyncButton.Visibility = Visibility.Visible; this.mStopSyncButton.Visibility = Visibility.Visible; } void ITopBar.HideSyncPanel() { this.mOperationsSyncGrid.Visibility = Visibility.Collapsed; this.mPlayPauseSyncButton.Visibility = Visibility.Collapsed; this.mStopSyncButton.Visibility = Visibility.Collapsed; this.mSyncInstancesToolTipPopup.IsOpen = false; } private void PlayPauseSyncButton_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) { if ((sender as CustomPictureBox).ImageName.Equals("pause_title_bar", StringComparison.InvariantCultureIgnoreCase)) { (sender as CustomPictureBox).ImageName = "play_title_bar"; this.ParentWindow.mSynchronizerWindow.PauseAllSyncOperations(); } else { (sender as CustomPictureBox).ImageName = "pause_title_bar"; this.ParentWindow.mSynchronizerWindow.PlayAllSyncOperations(); } } private void StopSyncButton_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) { ((ITopBar) this).HideSyncPanel(); this.ParentWindow.mSynchronizerWindow.StopAllSyncOperations(); if (!RegistryManager.Instance.IsShowToastNotification) return; this.ParentWindow.ShowGeneralToast(LocaleStrings.GetLocalizedString("STRING_SYNC_STOPPED", "")); } private void OperationsSyncGrid_MouseEnter(object sender, MouseEventArgs e) { if (!this.ParentWindow.mIsSynchronisationActive) return; this.mSyncInstancesToolTipPopup.IsOpen = true; } private void OperationsSyncGrid_MouseLeave(object sender, MouseEventArgs e) { if (!this.ParentWindow.mIsSynchronisationActive || this.mOperationsSyncGrid.IsMouseOver || this.mSyncInstancesToolTipPopup.IsMouseOver) return; this.mSyncInstancesToolTipPopup.IsOpen = false; } private void SyncInstancesToolTip_MouseLeave(object sender, MouseEventArgs e) { if (this.mOperationsSyncGrid.IsMouseOver || this.mSyncInstancesToolTipPopup.IsMouseOver) return; this.mSyncInstancesToolTipPopup.IsOpen = false; } internal void ClosePopups() { if (this.mMacroRecorderToolTipPopup.IsOpen) this.mMacroRecorderToolTipPopup.IsOpen = false; if (this.mMacroRunningToolTipPopup.IsOpen) this.mMacroRunningToolTipPopup.IsOpen = false; if (this.mNotificationCentrePopup.IsOpen) this.mNotificationCentrePopup.IsOpen = false; if (this.mSettingsMenuPopup.IsOpen) this.mSettingsMenuPopup.IsOpen = false; if (!this.mSyncInstancesToolTipPopup.IsOpen) return; this.mSyncInstancesToolTipPopup.IsOpen = false; } private void HelpButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { string helpCenterUrl = BlueStacksUIUtils.GetHelpCenterUrl(); if (RegistryManager.Instance.InstallationType == InstallationTypes.GamingEdition) BlueStacksUIUtils.OpenUrl(helpCenterUrl); else this.ParentWindow.mTopBar.mAppTabButtons.AddWebTab(helpCenterUrl, "STRING_FEEDBACK", "help_center", true, "FEEDBACK_TEXT", false); } private void mNotificationCentrePopup_Closed(object sender, EventArgs e) { GenericNotificationManager.MarkNotification((IEnumerable<string>) new List<string>((IEnumerable<string>) GenericNotificationManager.GetNotificationItems((Predicate<GenericNotificationItem>) (x => !x.IsDeleted && !x.IsRead && string.Equals(x.VmName, this.ParentWindow.mVmName, StringComparison.InvariantCulture))).Keys), (System.Action<GenericNotificationItem>) (x => x.IsRead = true)); this.mNotificationDrawerControl.UpdateNotificationCount(); this.mNotificationCentreButton.ImageName = "notification"; this.mNotificationCentreButton.IsEnabled = true; } private void mNotificationCentrePopup_Opened(object sender, EventArgs e) { this.mNotificationCentreButton.IsEnabled = false; } [DebuggerNonUserCode] [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (this._contentLoaded) return; this._contentLoaded = true; Application.LoadComponent((object) this, new Uri("/Bluestacks;component/topbar.xaml", UriKind.Relative)); } [DebuggerNonUserCode] [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] internal Delegate _CreateDelegate(Type delegateType, string handler) { return Delegate.CreateDelegate(delegateType, (object) this, handler); } [DebuggerNonUserCode] [GeneratedCode("PresentationBuildTasks", "4.0.0.0")] [EditorBrowsable(EditorBrowsableState.Never)] void IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: ((FrameworkElement) target).Loaded += new RoutedEventHandler(this.TopBar_Loaded); ((FrameworkElement) target).SizeChanged += new SizeChangedEventHandler(this.TopBar_SizeChanged); break; case 2: this.mMainGrid = (Grid) target; break; case 3: this.WindowHeaderGrid = (Grid) target; break; case 4: this.mTitleIcon = (CustomPictureBox) target; break; case 5: this.mTitleTextGrid = (Grid) target; break; case 6: this.mTitleText = (TextBlock) target; break; case 7: this.mVersionText = (TextBlock) target; break; case 8: this.mOptionsDockPanel = (DockPanel) target; break; case 9: this.mSidebarButton = (CustomPictureBox) target; this.mSidebarButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.MSidebarButton_MouseLeftButtonUp); break; case 10: this.mCloseButton = (CustomPictureBox) target; this.mCloseButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.CloseButton_MouseLeftButtonUp); break; case 11: this.mMaximizeButton = (CustomPictureBox) target; this.mMaximizeButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.MaxmizeButton_MouseLeftButtonUp); break; case 12: this.mMinimizeButton = (CustomPictureBox) target; this.mMinimizeButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.MinimizeButton_MouseLeftButtonUp); break; case 13: this.mConfigButtonGrid = (Grid) target; break; case 14: this.mConfigButton = (CustomPictureBox) target; this.mConfigButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.ConfigButton_MouseLeftButtonUp); break; case 15: this.mSettingsBtnNotification = (Ellipse) target; break; case 16: this.mSettingsMenuPopup = (CustomPopUp) target; break; case 17: this.mPreferenceDropDownBorder = (Border) target; break; case 18: this.mGrid = (Grid) target; break; case 19: this.mMaskBorder = (Border) target; break; case 20: this.mPreferenceDropDownControl = (PreferenceDropDownControl) target; break; case 21: this.mHelpButton = (CustomPictureBox) target; this.mHelpButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.HelpButton_MouseLeftButtonUp); break; case 22: this.mUserAccountBtn = (CustomPictureBox) target; this.mUserAccountBtn.MouseLeftButtonUp += new MouseButtonEventHandler(this.UserAccountButton_MouseLeftButtonUp); break; case 23: this.mNotificationGrid = (Grid) target; break; case 24: this.mNotificationCentreButton = (CustomPictureBox) target; this.mNotificationCentreButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.mNotificationCentreButton_MouseLeftButtonUp); break; case 25: this.mNotificationCountBadge = (Canvas) target; break; case 26: this.mNotificationCentrePopup = (CustomPopUp) target; break; case 27: this.mNotificationCaret = (Path) target; break; case 28: this.mNotificationCentreDropDownBorder = (Border) target; this.mNotificationCentreDropDownBorder.LayoutUpdated += new EventHandler(this.mNotificationCentreDropDownBorder_LayoutUpdated); break; case 29: this.mMaskBorder1 = (Border) target; break; case 30: this.mNotificationDrawerControl = (NotificationDrawer) target; break; case 31: this.mBtvButton = (CustomPictureBox) target; this.mBtvButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.mBtvButton_MouseLeftButtonUp); break; case 32: this.mWarningButton = (CustomPictureBox) target; this.mWarningButton.MouseLeftButtonUp += new MouseButtonEventHandler(this.mWarningButton_MouseLeftButtonUp); break; case 33: this.mOperationsSyncGrid = (Grid) target; this.mOperationsSyncGrid.MouseEnter += new MouseEventHandler(this.OperationsSyncGrid_MouseEnter); this.mOperationsSyncGrid.MouseLeave += new MouseEventHandler(this.OperationsSyncGrid_MouseLeave); break; case 34: this.mSyncMaskBorder = (Border) target; break; case 35: this.mPlayPauseSyncButton = (CustomPictureBox) target; this.mPlayPauseSyncButton.PreviewMouseLeftButtonUp += new MouseButtonEventHandler(this.PlayPauseSyncButton_PreviewMouseLeftButtonUp); break; case 36: this.mStopSyncButton = (CustomPictureBox) target; this.mStopSyncButton.PreviewMouseLeftButtonUp += new MouseButtonEventHandler(this.StopSyncButton_PreviewMouseLeftButtonUp); break; case 37: this.mSyncInstancesToolTipPopup = (CustomPopUp) target; break; case 38: this.mDummyGrid = (Grid) target; break; case 39: this.mMaskBorder2 = (Border) target; break; case 40: this.mUpwardArrow = (Path) target; break; case 41: this.mLocalConfigIndicator = (CustomPictureBox) target; break; case 42: this.mAppTabButtons = (AppTabButtons) target; break; case 43: this.mVideoRecordingStatusGrid = (Grid) target; break; case 44: this.mVideoRecordStatusControl = (VideoRecordingStatus) target; break; case 45: this.mMacroGrid = (Grid) target; break; case 46: this.mMacroRecordControl = (MacroTopBarRecordControl) target; break; case 47: this.mMacroPlayControl = (MacroTopBarPlayControl) target; break; case 48: this.mMacroRecorderToolTipPopup = (CustomPopUp) target; break; case 49: this.dummyGrid = (Grid) target; break; case 50: this.mMaskBorder3 = (Border) target; break; case 51: this.mMacroRecordingTooltip = (TextBlock) target; break; case 52: this.mUpArrow = (Path) target; break; case 53: this.mMacroRunningToolTipPopup = (CustomPopUp) target; break; case 54: this.grid = (Grid) target; break; case 55: this.mMaskBorder4 = (Border) target; break; case 56: this.mMacroRunningTooltip = (TextBlock) target; break; default: this._contentLoaded = true; break; } } } }
42.009615
391
0.702335
[ "MIT" ]
YehudaEi/Bluestacks-source-code
src/Bluestacks/BlueStacks/BlueStacksUI/TopBar.cs
43,692
C#
using System.Collections.Generic; using System.Linq; using Android.App; using Android.Content; using Android.Content.PM; using Android.OS; using Android.Widget; using WorldOfEnglishWord.BisnessLogic; namespace WorldOfEnglishWord.Controllers.Test { [Activity(Label = "SolutionTestActivity", ScreenOrientation = ScreenOrientation.Portrait)] public class SolutionTestActivity : Activity { private TextView textViewCountQuestions; private TextView textViewQuestion; private EditText editTextAnswers; private Button buttonNextQuestion; private WordsLogic wordsLogic; private List<string> wordsForTest; private int countQuestions; private int numberOfThisQuestion; private int index; private List<string> userBadResponse = new List<string>(); private List<string> dictionaryResponse = new List<string>(); protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); wordsLogic = WordsLogic.GetInstance(); SetContentView(Resource.Layout.solution_test_view); wordsForTest = Intent.GetStringArrayListExtra("WordsForTest").ToList(); countQuestions = wordsForTest.Count; numberOfThisQuestion = 1; index = 0; textViewCountQuestions = FindViewById<TextView>(Resource.Id.tv_count_answers); textViewQuestion = FindViewById<TextView>(Resource.Id.tv_question); editTextAnswers = FindViewById<EditText>(Resource.Id.et_answer); buttonNextQuestion = FindViewById<Button>(Resource.Id.btn_next_question); if (countQuestions == 1) { buttonNextQuestion.Text = "Завершить тест"; } textViewCountQuestions.Text = $"{numberOfThisQuestion}/{countQuestions}"; textViewQuestion.Text = wordsForTest[0]; buttonNextQuestion.Click += (sender, e) => GoToNextQuestion(); } public override void OnBackPressed() { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Завершение теста"); alert.SetMessage("Вы уверены, что хотите завершить тест?"); alert.SetPositiveButton("Да", (senderAlert, args) => { CompleteTest(); Intent intent = new Intent(this, typeof(ResultTestActivity)); intent.PutExtra("CountQuestions", countQuestions); intent.PutStringArrayListExtra("WordsForTest", wordsForTest); intent.PutStringArrayListExtra("UserResponse", userBadResponse); intent.PutStringArrayListExtra("DictionaryResponse", dictionaryResponse); StartActivity(intent); Finish(); }); alert.SetNegativeButton("Нет", (senderAlert, args) => { }); Dialog dialogEndTest = alert.Create(); dialogEndTest.Show(); } private void GoToNextQuestion() { buttonNextQuestion.Enabled = false; (string, bool) checkResponse = wordsLogic.CheckingResponseToTheTest(wordsForTest[index], editTextAnswers.Text.ToLower()); if (checkResponse.Item2) { wordsForTest.Remove(wordsForTest[index]); } else { userBadResponse.Add(editTextAnswers.Text); dictionaryResponse.Add(checkResponse.Item1); index++; } if (numberOfThisQuestion == countQuestions) { Intent intent = new Intent(this, typeof(ResultTestActivity)); intent.PutExtra("CountQuestions", countQuestions); intent.PutStringArrayListExtra("WordsForTest", wordsForTest); intent.PutStringArrayListExtra("UserResponse", userBadResponse); intent.PutStringArrayListExtra("DictionaryResponse", dictionaryResponse); StartActivity(intent); Finish(); return; } numberOfThisQuestion += 1; textViewCountQuestions.Text = $"{numberOfThisQuestion}/{countQuestions}"; textViewQuestion.Text = wordsForTest[index]; editTextAnswers.Text = ""; if (numberOfThisQuestion == countQuestions) { buttonNextQuestion.Text = "Завершить тест"; } buttonNextQuestion.Enabled = true; } private void CompleteTest() { while (index != wordsForTest.Count) { if (editTextAnswers.Text != "") { (string, bool) checkResponse = wordsLogic.CheckingResponseToTheTest(wordsForTest[index], editTextAnswers.Text.ToLower()); if (checkResponse.Item2) { wordsForTest.Remove(wordsForTest[index]); } else { userBadResponse.Add(editTextAnswers.Text); dictionaryResponse.Add(checkResponse.Item1); index++; } editTextAnswers.Text = ""; } else { userBadResponse.Add(""); (string, bool) checkResponsePotentialError = wordsLogic.CheckingResponseToTheTest(wordsForTest[index], ""); dictionaryResponse.Add(checkResponsePotentialError.Item1); index++; } } } } }
36.348101
141
0.579314
[ "MIT" ]
Bezuglyash/WorldOfEnglishWords
WorldOfEnglishWord/Controllers/Test/SolutionTestActivity.cs
5,822
C#
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Zero.Models; namespace Zero.Data { public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } } }
25.533333
99
0.73107
[ "MIT" ]
VisualAcademy/RedPlus.RazorPages
Zero/Data/ApplicationDbContext.cs
385
C#
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using System; using Wangkanai.Detection.Models; namespace Wangkanai.Detection.Services { /// <summary> /// Provides the APIs for query <see cref="Crawler"/>. /// </summary> public interface ICrawlerService { /// <summary> /// Determine that the request client is crawler. /// </summary> public bool IsCrawler { get; } /// <summary> /// Gets the <see cref="Crawler"/> name of the request clients. /// </summary> public Crawler Name { get; } /// <summary> /// Gets the <see cref="Version"/> of the request client. /// </summary> public Version Version { get; } } }
28.333333
78
0.583529
[ "Apache-2.0" ]
ApolonTorq/Detection
src/Services/Interfaces/ICrawlerService.cs
850
C#
/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.SageMaker; using Amazon.SageMaker.Model; namespace Amazon.PowerShell.Cmdlets.SM { /// <summary> /// A list of devices.<br/><br/>This cmdlet automatically pages all available results to the pipeline - parameters related to iteration are only needed if you want to manually control the paginated output. To disable autopagination, use -NoAutoIteration. /// </summary> [Cmdlet("Get", "SMDeviceList")] [OutputType("Amazon.SageMaker.Model.DeviceSummary")] [AWSCmdlet("Calls the Amazon SageMaker Service ListDevices API operation.", Operation = new[] {"ListDevices"}, SelectReturnType = typeof(Amazon.SageMaker.Model.ListDevicesResponse))] [AWSCmdletOutput("Amazon.SageMaker.Model.DeviceSummary or Amazon.SageMaker.Model.ListDevicesResponse", "This cmdlet returns a collection of Amazon.SageMaker.Model.DeviceSummary objects.", "The service call response (type Amazon.SageMaker.Model.ListDevicesResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class GetSMDeviceListCmdlet : AmazonSageMakerClientCmdlet, IExecutor { #region Parameter DeviceFleetName /// <summary> /// <para> /// <para>Filter for fleets containing this name in their device fleet name.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String DeviceFleetName { get; set; } #endregion #region Parameter LatestHeartbeatAfter /// <summary> /// <para> /// <para>Select fleets where the job was updated after X</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.DateTime? LatestHeartbeatAfter { get; set; } #endregion #region Parameter ModelName /// <summary> /// <para> /// <para>A filter that searches devices that contains this name in any of their models.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String ModelName { get; set; } #endregion #region Parameter MaxResult /// <summary> /// <para> /// <para>Maximum number of results to select.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("MaxResults")] public System.Int32? MaxResult { get; set; } #endregion #region Parameter NextToken /// <summary> /// <para> /// <para>The response from the last list when returning a list large enough to need tokening.</para> /// </para> /// <para> /// <br/><b>Note:</b> This parameter is only used if you are manually controlling output pagination of the service API call. /// <br/>In order to manually control output pagination, use '-NextToken $null' for the first call and '-NextToken $AWSHistory.LastServiceResponse.NextToken' for subsequent calls. /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String NextToken { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'DeviceSummaries'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.SageMaker.Model.ListDevicesResponse). /// Specifying the name of a property of type Amazon.SageMaker.Model.ListDevicesResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "DeviceSummaries"; #endregion #region Parameter NoAutoIteration /// <summary> /// By default the cmdlet will auto-iterate and retrieve all results to the pipeline by performing multiple /// service calls. If set, the cmdlet will retrieve only the next 'page' of results using the value of NextToken /// as the start point. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter NoAutoIteration { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.SageMaker.Model.ListDevicesResponse, GetSMDeviceListCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); } context.DeviceFleetName = this.DeviceFleetName; context.LatestHeartbeatAfter = this.LatestHeartbeatAfter; context.MaxResult = this.MaxResult; context.ModelName = this.ModelName; context.NextToken = this.NextToken; // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; var useParameterSelect = this.Select.StartsWith("^"); // create request and set iteration invariants var request = new Amazon.SageMaker.Model.ListDevicesRequest(); if (cmdletContext.DeviceFleetName != null) { request.DeviceFleetName = cmdletContext.DeviceFleetName; } if (cmdletContext.LatestHeartbeatAfter != null) { request.LatestHeartbeatAfter = cmdletContext.LatestHeartbeatAfter.Value; } if (cmdletContext.MaxResult != null) { request.MaxResults = cmdletContext.MaxResult.Value; } if (cmdletContext.ModelName != null) { request.ModelName = cmdletContext.ModelName; } // Initialize loop variant and commence piping var _nextToken = cmdletContext.NextToken; var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken)); var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); do { request.NextToken = _nextToken; CmdletOutput output; try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; if (!useParameterSelect) { pipelineOutput = cmdletContext.Select(response, this); } output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; _nextToken = response.NextToken; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } ProcessOutput(output); } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken)); if (useParameterSelect) { WriteObject(cmdletContext.Select(null, this)); } return null; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.SageMaker.Model.ListDevicesResponse CallAWSServiceOperation(IAmazonSageMaker client, Amazon.SageMaker.Model.ListDevicesRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon SageMaker Service", "ListDevices"); try { #if DESKTOP return client.ListDevices(request); #elif CORECLR return client.ListDevicesAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String DeviceFleetName { get; set; } public System.DateTime? LatestHeartbeatAfter { get; set; } public System.Int32? MaxResult { get; set; } public System.String ModelName { get; set; } public System.String NextToken { get; set; } public System.Func<Amazon.SageMaker.Model.ListDevicesResponse, GetSMDeviceListCmdlet, object> Select { get; set; } = (response, cmdlet) => response.DeviceSummaries; } } }
42.86194
258
0.58884
[ "Apache-2.0" ]
QPC-database/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/SageMaker/Basic/Get-SMDeviceList-Cmdlet.cs
11,487
C#
using System; namespace Craftgate.Response.Dto; public class ReportingPaymentTransaction : PaymentTransaction { public DateTime CreatedDate { get; set; } public DateTime TransactionStatusDate { get; set; } public decimal RefundablePrice { get; set; } public MemberResponse? SubMerchantMember { get; set; } public string? RefundStatus { get; set; } public PayoutStatus? PayoutStatus { get; set; } public decimal BankCommissionRate { get; set; } public decimal BankCommissionRateAmount { get; set; } }
35.533333
61
0.733583
[ "MIT" ]
selcukyavuz/craftgate-dotnet-client
Craftgate/Response/Dto/ReportingPaymentTransaction.cs
533
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Triangle-ExamAdd")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Triangle-ExamAdd")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("98fd89ed-b34b-4f96-8391-8bd0e2c44041")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.837838
84
0.747857
[ "MIT" ]
Radostta/Programming-Basics-And-Fundamentals-SoftUni
Draw-With-Loops/Triangle-ExamAdd/Properties/AssemblyInfo.cs
1,403
C#
// Inspired by // http://blogs.msdn.com/ericlippert/archive/2007/03/28/lambda-expressions-vs-anonymous-methods-part-five.aspx using System; class TestClass { delegate void DT (T t); delegate void DF (F f); struct T { } struct F { } static void P (DT dt) { Console.WriteLine ("True"); dt (new T ()); } static void P (DF df) { System.Console.WriteLine ("False"); df (new F ()); } static T And (T a1, T a2) { return new T (); } static F And (T a1, F a2) { return new F (); } static F And (F a1, T a2) { return new F (); } static F And (F a1, F a2) { return new F (); } static T Or (T a1, T a2) { return new T (); } static T Or (T a1, F a2) { return new T (); } static T Or (F a1, T a2) { return new T (); } static F Or (F a1, F a2) { return new F (); } static F Not (T a) { return new F (); } static T Not (F a) { return new T (); } static void StopTrue (T t) { } public static int Main () { // Test that we encode (!v3) & ((!v1) & ((v1 | v2) & (v2 | v3))) P (v1 => P (v2 => P (v3 => StopTrue ( And (Not (v3), And (Not (v1), And (Or (v1, v2), Or (v2, v3)) ) ) )))); return 0; } }
20.963636
110
0.545533
[ "Apache-2.0" ]
121468615/mono
mcs/tests/gtest-lambda-06.cs
1,153
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.Extensions.Options; using SendGrid; using SendGrid.Helpers.Mail; namespace AudioBoos.Server.Services.Email; public class EmailSender : IEmailSender { public EmailOptions _settings { get; } //set only via Secret Manager public EmailSender(IOptions<EmailOptions> optionsAccessor) { _settings = optionsAccessor.Value; } public Task SendEmailAsync(string email, string subject, string message) { return Execute(_settings.ServiceKey, subject, message, email); } public Task Execute(string apiKey, string subject, string message, string email) { var client = new SendGridClient(apiKey); var msg = new SendGridMessage { From = new EmailAddress(_settings.FromEmail, _settings.FromName), Subject = subject, PlainTextContent = message, HtmlContent = message }; msg.AddTo(new EmailAddress(email)); msg.SetClickTracking(true, true); return client.SendEmailAsync(msg); } }
33.393939
86
0.696007
[ "MIT" ]
audioboos/audioboos-backend
audioboos-server/Services/Email/EmailSender.cs
1,104
C#
using RestSharp; using RestSharp.Authenticators; using System; using System.Net; namespace SugarCRMRestClient { public class SugarAuthenticator : IAuthenticator { private SugarOAuthRequest _authenticationrequest; private string _baseUrl; private SugarOAuthToken _oauthToken; public SugarAuthenticator(SugarOAuthRequest authenticationrequest, string baseUrl) { _authenticationrequest = authenticationrequest; _baseUrl = baseUrl; FetchOAuthToken(); } public void Authenticate(IRestClient client, IRestRequest request) { request.AddHeader("oauth-token", _oauthToken.Access_Token); } public void FetchOAuthToken() { var authClient = new RestClient(_baseUrl); var authrequest = new RestRequest("oauth2/token", Method.POST); foreach (var item in _authenticationrequest.GetAuthParams()) { authrequest.AddParameter(item.Key, item.Value); } var returnval = authClient.Execute<SugarOAuthToken>(authrequest); if (returnval.StatusCode == HttpStatusCode.OK) { _oauthToken = returnval.Data; } else throw new Exception(returnval.StatusCode.ToString() + " " + returnval.Content); } public void UpdateToken() { var authClient = new RestClient(_baseUrl); var authrequest = new RestRequest("oauth2/token", Method.POST); _authenticationrequest.grant_type = "refresh_token"; _authenticationrequest.refresh_token = _oauthToken.Refresh_Token; foreach (var item in _authenticationrequest.GetRefreshAuthParams()) { authrequest.AddParameter(item.Key, item.Value); } var returnval = authClient.Execute<SugarOAuthToken>(authrequest); if (returnval.StatusCode == HttpStatusCode.OK) { _oauthToken = returnval.Data; } else throw new Exception(returnval.StatusCode.ToString() + " " + returnval.Content); } public bool IsAccessTokenExpired { get { return _oauthToken.HasAccessTokenExpired(); } } public bool IsRefreshTokenExpired { get { return _oauthToken.HasRefreshTokenExpired(); } } } }
35.416667
96
0.587843
[ "MIT" ]
mshenoy83/SugarCRMRestClient
src/SugarAuthenticator.cs
2,552
C#
using System; using System.Globalization; using Miningcore.Extensions; using Newtonsoft.Json; namespace Miningcore.Serialization { public class HexToByteArrayJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { return typeof(byte[]) == objectType; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue($"0x{value:x}"); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var str = (string) reader.Value; if (str.StartsWith("0x")) str = str.Substring(2); if (string.IsNullOrEmpty(str)) return null; return str.HexToByteArray(); } } }
26.787879
124
0.617647
[ "MIT" ]
BTHPOS/miningcore
src/Miningcore/Serialization/HexToByteArrayJsonConverter.cs
884
C#
using Avalonia.Controls; using Avalonia.Controls.Templates; using Avalonia.Markup.Xaml.Templates; using Avalonia.Metadata; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChangeContentBasedOnEnumSample.ViewModels { public class DataTemplateSelector : IDataTemplate { [Content] public Dictionary<string, IDataTemplate> AvailableTemplates { get; } = new (); public IControl Build(object param) { return AvailableTemplates[param.ToString() ?? throw new ArgumentNullException(nameof(param))].Build(param); } public bool Match(object data) { var key = data.ToString(); return !string.IsNullOrEmpty(key) && AvailableTemplates.ContainsKey(key); } } }
28.032258
120
0.665132
[ "MIT" ]
timunie/Tims.Avalonia.Samples
src/ChangeContentBasedOnEnumSample/ViewModels/DataTemplateSelector.cs
871
C#
using System.Threading; using System.Threading.Tasks; using CovidInformer.Entities; namespace CovidInformer.Services { public interface IDataProvider { Task<CovidData> GetDataAsync(CancellationToken cancellationToken = default); } }
21.25
84
0.764706
[ "MIT" ]
VlaTo/CovidInformer
src/CovidInformer/CovidInformer/Services/IDataProvider.cs
257
C#
using AutoMapper; namespace CodeWarrior.App.Mappers { public class AutoMapperConfiguration { public static void Configure() { Mapper.Initialize(x => x.AddProfile<BindingModelToDatabaseModel>()); Mapper.Initialize(x => x.AddProfile<DatabaseModelToViewModel>()); } } }
25.230769
80
0.643293
[ "MIT" ]
BrainStation-23/BitBook
Application/CodeWarrior.App/Mappers/AutoMapperConfiguration.cs
330
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Serilog; using Serilog.Events; namespace AppHospital.Api { public class Program { public static int Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Console() .CreateLogger(); try { Log.Information("Starting web host"); CreateWebHostBuilder(args).Build().Run(); return 0; } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); return 1; } finally { Log.CloseAndFlush(); } } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseSerilog(); } }
26.38
78
0.554208
[ "MIT" ]
AppHospital/client-api
src/AppHospital.Api/Program.cs
1,321
C#
using System; using System.IO; using EnvDTE; using Microsoft.VisualStudio.Shell; using Process = System.Diagnostics.Process; namespace RapidFire { public static class OpenOutputFolderHelper { /// <summary> /// Opens the given <see cref="Project"/> project's output folder in File Explorer. /// </summary> /// <param name="project">The given project.</param> public static void OpenProjectOutputFolder(Project project) { ThreadHelper.ThrowIfNotOnUIThread(); var projectDir = Path.GetDirectoryName(project.FullName); if (projectDir == null) { throw new InvalidOperationException("Unable to find project directory"); } var relativeOutputPath = project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString(); var projectOutputPath = Path.Combine(projectDir, relativeOutputPath); var assemblyName = project.Properties.Item("AssemblyName").Value.ToString(); var outputType = (int)project.Properties.Item("OutputType").Value; var projectFileOutputPath = Path.Combine(projectOutputPath, $"{assemblyName}{(outputType == 2 ? ".dll" : "exe")}"); if (File.Exists(projectFileOutputPath)) { Process.Start("explorer.exe", $"/select, \"{projectFileOutputPath}\""); } else { Process.Start(projectOutputPath); } } } }
35.181818
133
0.615633
[ "Apache-2.0" ]
andrewphamvk/RapidFire
RapidFire/Helpers/OpenOutputFolderHelper.cs
1,550
C#
// SPDX-License-Identifier: MIT // Copyright © 2021 Oscar Björhn, Petter Löfgren and contributors namespace Daf.Core.Ssis.Wrapper.Wrappers.Tasks { public class ExpressionTaskWrapper : TaskWrapper { public ExpressionTaskWrapper(ContainerWrapper containerWrapper) : base(containerWrapper, "Microsoft.ExpressionTask") { } public string Expression { get { return TaskHost.Properties["Expression"].GetValue(TaskHost); } set { TaskHost.Properties["Expression"].SetValue(TaskHost, value); } } } }
30
122
0.760784
[ "MIT" ]
data-automation-framework/daf-core-ssis
Daf.Core.Ssis.Wrapper/Wrappers/Tasks/ExpressionTaskWrapper.cs
515
C#
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System.Text; using Elastic.Xunit.XunitPlumbing; using Elasticsearch.Net; using FluentAssertions; using Nest; using Tests.Core.Client; namespace Tests.CodeStandards.Serialization { public class GeoLocationTests { [U] public void CanDeserializeAndSerializeToWellKnownText() { var wkt = "{\"location\":\"POINT (-90 90)\"}"; var client = TestClient.DisabledStreaming; Doc deserialized; using (var stream = RecyclableMemoryStreamFactory.Default.Create(Encoding.UTF8.GetBytes(wkt))) deserialized = client.RequestResponseSerializer.Deserialize<Doc>(stream); deserialized.Location.Should().Be(new GeoLocation(90, -90)); client.RequestResponseSerializer.SerializeToString(deserialized).Should().Be(wkt); } private class Doc { public GeoLocation Location { get; set; } } } }
28.416667
97
0.755621
[ "Apache-2.0" ]
magaum/elasticsearch-net
tests/Tests/CodeStandards/Serialization/GeoLocationTests.cs
1,023
C#
// namespace IntraSoft.Data.Dtos.Document // { // using IntraSoft.Services.Mapping; // using IntraSoft.Data.Models; // using System.IO; // public class FileReadForMenuDto: IMapFrom<DocumentFile> // { // public int Id { get; set; } // public string FilePath { get; set; } // public string FileName => Path.GetFileName(this.FilePath); // } // }
30.153846
69
0.609694
[ "MIT" ]
vladosfi/IntraSoft
src/Data/Dtos/Files/FileReadForMenuDto.cs
394
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace ElsaDashboard.Samples.AspNetCore.SubPath.Pages { public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } public void OnGet() { } } }
22.083333
56
0.683019
[ "MIT" ]
1002527441/elsa-core
src/samples/dashboard/aspnetcore/ElsaDashboard.Samples.AspNetCore.SubPath/Pages/Index.cshtml.cs
532
C#
using MainPageMobile.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace MainPageMobile.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class LoginPage : ContentPage { public LoginPage() { var vm = new LoginViewModel(); this.BindingContext = vm; vm.DisplayInvalidLoginPrompt += () => DisplayAlert("Error", "Invalid Login, try again", "OK"); InitializeComponent(); Email.Completed += (object sender, EventArgs e) => { Password.Focus(); }; Password.Completed += (object sender, EventArgs e) => { vm.SubmitCommand.Execute(null); }; } } }
26.147059
106
0.593926
[ "BSD-3-Clause" ]
Metodii/Diplomna
MainPageMobile/MainPageMobile/MainPageMobile/Views/LoginPage.xaml.cs
891
C#
using System; using System.Collections.Generic; using System.Web.Script.Serialization; using BrightcoveMapiWrapper.Model.Items; using BrightcoveMapiWrapper.Serialization; using BrightcoveMapiWrapper.Util; namespace BrightcoveMapiWrapper.Model.Containers { /// <summary> /// Represents a collection of BrightcoveItems /// </summary> /// <typeparam name="T"></typeparam> public class BrightcoveItemCollection<T> : List<T>, IJavaScriptConvertable where T : BrightcoveItem, IJavaScriptConvertable { /// <summary> /// The current page of results. (Each page is limited to a max of 100 items) /// </summary> public int PageNumber { get; set; } /// <summary> /// The size of each page of results. If not specified, the default is 100 /// </summary> public int PageSize { get; set; } /// <summary> /// The total number of items available /// </summary> public int TotalCount { get; set; } #region IJavaScriptConvertable implementation /// <summary> /// Deserializes the specified dictionary. /// </summary> /// <param name="dictionary">The <see cref="IDictionary{String,Object}" />.</param> /// <param name="serializer">The <see cref="JavaScriptSerializer" />.</param> public void Deserialize(IDictionary<string, object> dictionary, JavaScriptSerializer serializer) { foreach (string key in dictionary.Keys) { switch (key) { case "error": ApiUtil.ThrowIfError(dictionary, key, serializer); break; case "items": Clear(); AddRange(serializer.ConvertToType<T[]>(dictionary[key])); break; case "page_number": PageNumber = (int) dictionary[key]; break; case "page_size": PageSize = (int) dictionary[key]; break; case "total_count": TotalCount = (int) dictionary[key]; break; } } } /// <summary> /// Serializes the specified serializer. /// </summary> /// <param name="serializer">The serializer.</param> /// <returns> /// A serialized <see cref="IDictionary{String,Object}" />. /// </returns> /// <exception cref="System.NotImplementedException"></exception> public IDictionary<string, object> Serialize(JavaScriptSerializer serializer) { throw new NotImplementedException(); } #endregion } }
25.052083
125
0.638669
[ "MIT" ]
BrightcoveOS/.NET-MAPI-Wrapper
source/BrightcoveOS .NET-MAPI-Wrapper/Model/Containers/BrightcoveItemCollection.cs
2,407
C#
using Microsoft.Azure.Cosmos.Table.Queryable; namespace Microsoft.Azure.Cosmos.Table.Extensions { internal sealed class TableExtensionExpressionParser : ExpressionParser { internal override void VisitQueryOptionExpression(FilterQueryOptionExpression fqoe) { base.FilterString = TableExtensionExpressionWriter.ExpressionToString(fqoe.Predicate); } } }
28
89
0.82967
[ "MIT" ]
Luiz-Monad/azure-cosmos-table
src/Microsoft.Azure.Cosmos.Table.Extensions/TableExtensionExpressionParser.cs
364
C#
using System; using System.Collections; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Windows; namespace MinecraftToolsBoxSDK { public class TreeDataGridElement : ContentElement { private const string NullItemError = "The item added to the collection cannot be null."; public static readonly RoutedEvent ExpandingEvent; public static readonly RoutedEvent ExpandedEvent; public static readonly RoutedEvent CollapsingEvent; public static readonly RoutedEvent CollapsedEvent; public static readonly DependencyProperty HasChildrenProperty; public static readonly DependencyProperty IsExpandedProperty; public static readonly DependencyProperty LevelProperty; public TreeDataGridElement Parent { get; private set; } public TreeDataGridModel Model { get; private set; } public ObservableCollection<TreeDataGridElement> Children { get; private set; } static TreeDataGridElement() { // Register dependency properties HasChildrenProperty = RegisterHasChildrenProperty(); IsExpandedProperty = RegisterIsExpandedProperty(); LevelProperty = RegisterLevelProperty(); // Register routed events ExpandingEvent = RegisterExpandingEvent(); ExpandedEvent = RegisterExpandedEvent(); CollapsingEvent = RegisterCollapsingEvent(); CollapsedEvent = RegisterCollapsedEvent(); } public TreeDataGridElement() { // Initialize the element Children = new ObservableCollection<TreeDataGridElement>(); // Attach events Children.CollectionChanged += OnChildrenChanged; } internal void SetModel(TreeDataGridModel model, TreeDataGridElement parent = null) { // Set the element information Model = model; Parent = parent; Level = ((parent != null) ? parent.Level + 1 : 0); // Iterate through all child elements foreach (TreeDataGridElement child in Children) { // Set the model for the child child.SetModel(model, this); } } protected virtual void OnExpanding() { } protected virtual void OnExpanded() { } protected virtual void OnCollapsing() { } protected virtual void OnCollapsed() { } private void OnChildrenChanged(object sender, NotifyCollectionChangedEventArgs args) { // Process the event switch (args.Action) { case NotifyCollectionChangedAction.Add: // Process added child OnChildAdded(args.NewItems[0]); break; case NotifyCollectionChangedAction.Replace: // Process replaced child OnChildReplaced((TreeDataGridElement)args.OldItems[0], args.NewItems[0], args.NewStartingIndex); break; case NotifyCollectionChangedAction.Remove: // Process removed child OnChildRemoved((TreeDataGridElement)args.OldItems[0]); break; case NotifyCollectionChangedAction.Reset: // Process cleared children OnChildrenCleared(args.OldItems); break; } } private void OnChildAdded(object item) { // Verify the new child TreeDataGridElement child = VerifyItem(item); // Set the model for the child child.SetModel(Model, this); // Notify the model that a child was added to the item Model?.OnChildAdded(child); SetValue(HasChildrenProperty, true); } private void OnChildReplaced(TreeDataGridElement oldChild, object item, int index) { // Verify the new child TreeDataGridElement child = VerifyItem(item); // Clear the model for the old child oldChild.SetModel(null); // Notify the model that a child was replaced Model?.OnChildReplaced(oldChild, child, index); } private void OnChildRemoved(TreeDataGridElement child) { // Clear the model for the child child.SetModel(null); // Notify the model that a child was removed from the item Model?.OnChildRemoved(child); } private void OnChildrenCleared(IList children) { // Iterate through all of the children foreach (TreeDataGridElement child in children) { // Clear the model for the child child.SetModel(null); } // Notify the model that all of the children were removed from the item Model?.OnChildrenRemoved(this, children); } internal static TreeDataGridElement VerifyItem(object item) { // Is the item valid? if (item == null) { // The item is not valid throw new ArgumentNullException(nameof(item), NullItemError); } // Return the element return (TreeDataGridElement)item; } private static void OnIsExpandedChanged(DependencyObject element, DependencyPropertyChangedEventArgs args) { // Get the tree item TreeDataGridElement item = (TreeDataGridElement)element; // Is the item being expanded? if ((bool)args.NewValue) { // Raise expanding event item.RaiseEvent(new RoutedEventArgs(ExpandingEvent, item)); // Execute derived expanding handler item.OnExpanding(); // Expand the item in the model item.Model?.Expand(item); // Raise expanded event item.RaiseEvent(new RoutedEventArgs(ExpandedEvent, item)); // Execute derived expanded handler item.OnExpanded(); } else { // Raise collapsing event item.RaiseEvent(new RoutedEventArgs(CollapsingEvent, item)); // Execute derived collapsing handler item.OnCollapsing(); // Collapse the item in the model item.Model?.Collapse(item); // Raise collapsed event item.RaiseEvent(new RoutedEventArgs(CollapsedEvent, item)); // Execute derived collapsed handler item.OnCollapsed(); } } private static DependencyProperty RegisterHasChildrenProperty() { // Create the property metadata FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata() { DefaultValue = false }; // Register the property return DependencyProperty.Register(nameof(HasChildren), typeof(bool), typeof(TreeDataGridElement), metadata); } private static DependencyProperty RegisterIsExpandedProperty() { // Create the property metadata FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata() { DefaultValue = false, PropertyChangedCallback = OnIsExpandedChanged }; // Register the property return DependencyProperty.Register(nameof(IsExpanded), typeof(bool), typeof(TreeDataGridElement), metadata); } private static DependencyProperty RegisterLevelProperty() { // Create the property metadata FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata() { DefaultValue = 0 }; // Register the property return DependencyProperty.Register(nameof(Level), typeof(int), typeof(TreeDataGridElement), metadata); } private static RoutedEvent RegisterExpandingEvent() { // Register the event return EventManager.RegisterRoutedEvent(nameof(Expanding), RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(TreeDataGridElement)); } private static RoutedEvent RegisterExpandedEvent() { // Register the event return EventManager.RegisterRoutedEvent(nameof(Expanded), RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(TreeDataGridElement)); } private static RoutedEvent RegisterCollapsingEvent() { // Register the event return EventManager.RegisterRoutedEvent(nameof(Collapsing), RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(TreeDataGridElement)); } private static RoutedEvent RegisterCollapsedEvent() { // Register the event return EventManager.RegisterRoutedEvent(nameof(Collapsed), RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(TreeDataGridElement)); } public bool HasChildren { get { return (bool)GetValue(HasChildrenProperty); } } public bool IsExpanded { get { return (bool)GetValue(IsExpandedProperty); } set { SetValue(IsExpandedProperty, value); } } public int Level { get { return (int)GetValue(LevelProperty); } private set { SetValue(LevelProperty, value); } } public event RoutedEventHandler Expanding { add { AddHandler(ExpandingEvent, value); } remove { RemoveHandler(ExpandingEvent, value); } } public event RoutedEventHandler Expanded { add { AddHandler(ExpandedEvent, value); } remove { RemoveHandler(ExpandedEvent, value); } } public event RoutedEventHandler Collapsing { add { AddHandler(CollapsingEvent, value); } remove { RemoveHandler(CollapsingEvent, value); } } public event RoutedEventHandler Collapsed { add { AddHandler(CollapsedEvent, value); } remove { RemoveHandler(CollapsedEvent, value); } } } }
34.343137
153
0.592254
[ "MIT" ]
rcnteam/MinecraftToolsBox
MinecraftToolsBoxSDK/Controls/TreeDataGrid/TreeDataGridElement.cs
10,511
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; namespace TextPet.Events { public class BeginReadWriteEventArgs : EventArgs { public ReadOnlyCollection<string> Files { get; } public int Amount { get; } public bool IsWrite { get; } public BeginReadWriteEventArgs(string file, bool isWrite) : this(new List<string>() { file }, isWrite, 1) { } public BeginReadWriteEventArgs(string file, bool isWrite, int amount) : this(new List<string>() { file }, isWrite, amount) { } public BeginReadWriteEventArgs(IList<string> files, bool isWrite) : this(files, isWrite, files?.Count ?? 0) { } public BeginReadWriteEventArgs(IList<string> files, bool isWrite, int amount) { this.Files = new ReadOnlyCollection<string>(files); this.IsWrite = isWrite; this.Amount = amount; } } }
30.413793
81
0.72449
[ "MIT" ]
Prof9/TextPet
TextPet/Events/BeginReadWriteEventArgs.cs
884
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.DataShare.Models { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Linq; /// <summary> /// An Azure storage blob folder data set. /// </summary> [Newtonsoft.Json.JsonObject("BlobFolder")] [Rest.Serialization.JsonTransformation] public partial class BlobFolderDataSet : DataSet { /// <summary> /// Initializes a new instance of the BlobFolderDataSet class. /// </summary> public BlobFolderDataSet() { CustomInit(); } /// <summary> /// Initializes a new instance of the BlobFolderDataSet class. /// </summary> /// <param name="containerName">Container that has the file /// path.</param> /// <param name="prefix">Prefix for blob folder</param> /// <param name="resourceGroup">Resource group of storage /// account</param> /// <param name="storageAccountName">Storage account name of the source /// data set</param> /// <param name="subscriptionId">Subscription id of storage /// account</param> /// <param name="id">The resource id of the azure resource</param> /// <param name="name">Name of the azure resource</param> /// <param name="systemData">System Data of the Azure resource.</param> /// <param name="type">Type of the azure resource</param> /// <param name="dataSetId">Unique id for identifying a data set /// resource</param> public BlobFolderDataSet(string containerName, string prefix, string resourceGroup, string storageAccountName, string subscriptionId, string id = default(string), string name = default(string), SystemData systemData = default(SystemData), string type = default(string), string dataSetId = default(string)) : base(id, name, systemData, type) { ContainerName = containerName; DataSetId = dataSetId; Prefix = prefix; ResourceGroup = resourceGroup; StorageAccountName = storageAccountName; SubscriptionId = subscriptionId; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets container that has the file path. /// </summary> [JsonProperty(PropertyName = "properties.containerName")] public string ContainerName { get; set; } /// <summary> /// Gets unique id for identifying a data set resource /// </summary> [JsonProperty(PropertyName = "properties.dataSetId")] public string DataSetId { get; private set; } /// <summary> /// Gets or sets prefix for blob folder /// </summary> [JsonProperty(PropertyName = "properties.prefix")] public string Prefix { get; set; } /// <summary> /// Gets or sets resource group of storage account /// </summary> [JsonProperty(PropertyName = "properties.resourceGroup")] public string ResourceGroup { get; set; } /// <summary> /// Gets or sets storage account name of the source data set /// </summary> [JsonProperty(PropertyName = "properties.storageAccountName")] public string StorageAccountName { get; set; } /// <summary> /// Gets or sets subscription id of storage account /// </summary> [JsonProperty(PropertyName = "properties.subscriptionId")] public string SubscriptionId { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (ContainerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ContainerName"); } if (Prefix == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Prefix"); } if (ResourceGroup == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ResourceGroup"); } if (StorageAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "StorageAccountName"); } if (SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "SubscriptionId"); } } } }
38.066667
313
0.600895
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/datashare/Microsoft.Azure.Management.DataShare/src/Generated/Models/BlobFolderDataSet.cs
5,139
C#
// 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.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace IdentitySample.Models { public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); // Customize the ASP.NET Identity model and override the defaults if needed. // For example, you can rename the ASP.NET Identity table names and more. // Add your customizations after calling base.OnModelCreating(builder); } } }
35.692308
88
0.730603
[ "MIT" ]
48355746/AspNetCore
src/Identity/samples/IdentitySample.Mvc/Models/ApplicationDbContext.cs
928
C#
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // Copyright (C) LibreHardwareMonitor and Contributors. // Partial Copyright (C) Michael Möller <mmoeller@openhardwaremonitor.org> and Contributors. // All Rights Reserved. using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; using LibreHardwareMonitor.Hardware; namespace LibreHardwareMonitor.UI { public partial class ParameterForm : Form { private class ParameterRow : INotifyPropertyChanged { public readonly IParameter Parameter; private float _value = float.NaN; private bool _default = true; public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public ParameterRow(IParameter parameter) { Parameter = parameter; Value = parameter.Value; Default = parameter.IsDefault; } public string Name { get { return Parameter.Name; } } public string Description { get { return Parameter.Description; } } public float Value { get { return _value; } set { _default = false; _value = value; NotifyPropertyChanged(nameof(Default)); NotifyPropertyChanged(nameof(Value)); } } public bool Default { get { return _default; } set { _default = value; if (_default) _value = Parameter.DefaultValue; NotifyPropertyChanged(nameof(Default)); NotifyPropertyChanged(nameof(Value)); } } } private BindingList<ParameterRow> _parameterRows; public string Caption { get { return captionLabel.Text; } set { captionLabel.Text = value; } } public ParameterForm() { InitializeComponent(); CancelButton = cancelButton; } public void SetParameters(IReadOnlyList<IParameter> value) { _parameterRows = new BindingList<ParameterRow>(); foreach (IParameter parameter in value) { _parameterRows.Add(new ParameterRow(parameter)); } bindingSource.DataSource = _parameterRows; } private void DataGridView_RowEnter(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0 && e.RowIndex < _parameterRows.Count) descriptionLabel.Text = _parameterRows[e.RowIndex].Description; else descriptionLabel.Text = string.Empty; } private void DataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (e.ColumnIndex == 2 && !float.TryParse(e.FormattedValue.ToString(), out float _)) { dataGridView.Rows[e.RowIndex].Cells[0].ErrorText = "Invalid value"; e.Cancel = true; } } private void DataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) { dataGridView.Rows[e.RowIndex].Cells[0].ErrorText = string.Empty; } private void OkButton_Click(object sender, EventArgs e) { foreach (ParameterRow row in _parameterRows) { if (row.Default) row.Parameter.IsDefault = true; else row.Parameter.Value = row.Value; } } private void DataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e) { if (dataGridView.CurrentCell is DataGridViewCheckBoxCell || dataGridView.CurrentCell is DataGridViewComboBoxCell) dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit); } } }
31.87234
125
0.560748
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
joye-ramone/LibreHardwareMonitor
LibreHardwareMonitor/UI/ParameterForm.cs
4,497
C#
using System.Numerics; namespace _09_PerlinShiftedOffIntegerValues { public class Metal : Material { public Vector3 Albedo; public float fuzz; public Metal(Vector3 a, float f) { this.Albedo = a; this.fuzz = f < 1 ? f : 1; } public bool Scatter(Ray r_in, Hit_Record rec, out Vector3 attenuation, out Ray scattered) { Vector3 unit_vector = Vector3.Normalize(r_in.Direction); Vector3 reflected = Helpers.Reflect(unit_vector, rec.Normal); scattered = new Ray(rec.P, reflected + fuzz * Helpers.Random_in_unit_sphere()); attenuation = this.Albedo; return (Vector3.Dot(scattered.Direction, rec.Normal) > 0); } } }
28.592593
97
0.598446
[ "MIT" ]
Jorgemagic/RaytracingTheNextWeek
09-PerlinShiftedOffIntegerValues/Materials/Metal.cs
774
C#
using BTCPayServer.Abstractions.Models; namespace BTCPayServer.Plugins; public class BTCPayServerPlugin : BaseBTCPayServerPlugin { public override string Identifier { get; } = nameof(BTCPayServer); public override string Name { get; } = "BTCPay Server"; public override string Description { get; } = "BTCPay Server core system"; }
28.833333
78
0.751445
[ "MIT" ]
wforney/btcpayserver
BTCPayServer/Plugins/BTCPayServerPlugin.cs
346
C#
using FSO.SimAntics.NetPlay.Model; using System; using System.Collections.Generic; using System.Linq; using System.IO; namespace FSO.SimAntics.Engine.Diagnostics { public class VMSyncTrace { public List<VMSyncTraceTick> History = new List<VMSyncTraceTick>(); VMSyncTraceTick _current = null; const int MAX_HISTORY = 30 * 60; public VMSyncTraceTick GetTick(uint tickID) { return History.FirstOrDefault(x => x.TickID == tickID); } public void NewTick(uint id) { _current = new VMSyncTraceTick() { TickID = id }; History.Add(_current); if (History.Count > MAX_HISTORY) History.RemoveAt(0); } public void Trace(string str) { _current?.Trace.Add(str); } public void CompareFirstError(VMSyncTraceTick compare) { var me = GetTick(compare.TickID); if (me == null) return; var last = "<start tick>"; for (int i = 0; i < compare.Trace.Count && i < me.Trace.Count; i++) { if (compare.Trace[i] != me.Trace[i]) { Console.WriteLine("!!! DESYNC DETECTED !!!"); Console.WriteLine("Last:"); Console.WriteLine(last); Console.WriteLine("Our trace:"); Console.WriteLine(me.Trace[i]); Console.WriteLine("Server trace:"); Console.WriteLine(compare.Trace[i]); return; } last = me.Trace[i]; } } } public class VMSyncTraceTick : VMSerializable { public uint TickID = 0; public List<string> Trace = new List<string>(); public void Deserialize(BinaryReader reader) { Trace.Clear(); TickID = reader.ReadUInt32(); var count = reader.ReadInt32(); for (int i = 0; i < count; i++) { Trace.Add(reader.ReadString()); } } public void SerializeInto(BinaryWriter writer) { writer.Write(TickID); writer.Write(Trace.Count); foreach (var item in Trace) writer.Write(item); } } }
29.506173
79
0.500837
[ "MPL-2.0" ]
HarryFreeMyLand/newso
Src/tso.simantics/Engine/Diagnostics/VMSyncTrace.cs
2,390
C#
using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading.Tasks; using WalletWasabi.Helpers; using WalletWasabi.Logging; namespace System.IO; public static class IoHelpers { /// <summary> /// Attempts to delete <paramref name="directory"/> with retry feature to allow File Explorer or any other /// application that holds the directory handle of the <paramref name="directory"/> to release it. /// </summary> /// <see href="https://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true/14933880#44324346"/> public static async Task<bool> TryDeleteDirectoryAsync(string directory, int maxRetries = 10, int millisecondsDelay = 100) { Guard.NotNull(nameof(directory), directory); if (maxRetries < 1) { throw new ArgumentOutOfRangeException(nameof(maxRetries)); } if (millisecondsDelay < 1) { throw new ArgumentOutOfRangeException(nameof(millisecondsDelay)); } for (int i = 0; i < maxRetries; ++i) { try { if (Directory.Exists(directory)) { Directory.Delete(directory, recursive: true); } return true; } catch (DirectoryNotFoundException e) { Logger.LogDebug($"Directory was not found: {e}"); // Directory does not exist. So the operation is trivially done. return true; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { await Task.Delay(millisecondsDelay).ConfigureAwait(false); } } return false; } public static void EnsureContainingDirectoryExists(string fileNameOrPath) { string fullPath = Path.GetFullPath(fileNameOrPath); // No matter if relative or absolute path is given to this. string? dir = Path.GetDirectoryName(fullPath); EnsureDirectoryExists(dir); } /// <summary> /// It's like Directory.CreateDirectory, but does not fail when root is given. /// </summary> public static void EnsureDirectoryExists(string? dir) { if (!string.IsNullOrWhiteSpace(dir)) // If root is given, then do not worry. { Directory.CreateDirectory(dir); // It does not fail if it exists. } } public static void EnsureFileExists(string filePath) { if (!File.Exists(filePath)) { EnsureContainingDirectoryExists(filePath); File.Create(filePath)?.Dispose(); } } public static void OpenFolderInFileExplorer(string dirPath) { if (Directory.Exists(dirPath)) { using var process = Process.Start(new ProcessStartInfo { FileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "explorer.exe" : (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "open" : "xdg-open"), Arguments = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"\"{dirPath}\"" : dirPath, CreateNoWindow = true }); } } public static async Task OpenBrowserAsync(string url) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { // If no associated application/json MimeType is found xdg-open opens retrun error // but it tries to open it anyway using the console editor (nano, vim, other..) await EnvironmentHelpers.ShellExecAsync($"xdg-open {url}", waitForExit: false).ConfigureAwait(false); } else { using var process = Process.Start(new ProcessStartInfo { FileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? url : "open", Arguments = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? $"-e {url}" : "", CreateNoWindow = true, UseShellExecute = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) }); } } public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target) { foreach (DirectoryInfo dir in source.GetDirectories()) { CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name)); } foreach (FileInfo file in source.GetFiles()) { file.CopyTo(Path.Combine(target.FullName, file.Name)); } } public static void CreateOrOverwriteFile(string path) { using var _ = File.Create(path); } }
28.3
134
0.718576
[ "MIT" ]
CAnorbo/WalletWasabi
WalletWasabi/Helpers/IoHelpers.cs
3,962
C#
using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using AutoMapper; using BlazorBoilerplate.Shared.DataInterfaces; using BlazorBoilerplate.Shared.DataModels; using BlazorBoilerplate.Shared.Dto.Sample; namespace BlazorBoilerplate.Storage.Stores { public class MessageStore : IMessageStore { private readonly IApplicationDbContext _applicationDbContext; private readonly IMapper _autoMapper; public MessageStore(IApplicationDbContext applicationDbContext, IMapper autoMapper) { _applicationDbContext = applicationDbContext; _autoMapper = autoMapper; } public async Task<Message> AddMessage(MessageDto messageDto) { var message = _autoMapper.Map<MessageDto, Message>(messageDto); await _applicationDbContext.Messages.AddAsync(message); await _applicationDbContext.SaveChangesAsync(CancellationToken.None); return message; } public async Task DeleteById(int id) { // TODO: Figure out why I was getting an exception when deleting the highest ID. (Apart from that, works) _applicationDbContext.Messages.Remove(new Message() { Id = id }); await _applicationDbContext.SaveChangesAsync(CancellationToken.None); } public List<MessageDto> GetMessages() { return _autoMapper.ProjectTo<MessageDto>(_applicationDbContext.Messages).OrderBy(i => i.When).Take(10).ToList(); } } }
35.886364
124
0.693477
[ "MIT" ]
AhLay/blazorboilerplate
src/BlazorBoilerplate.Storage/Stores/MessageStore.cs
1,581
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Lego.Ev3.Tester.Wpf.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.8.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.777778
151
0.581937
[ "Apache-2.0" ]
PeterOrneholm/LegoEv3Core
samples/LegoEv3Core.Samples.Wpf/Properties/Settings.Designer.cs
1,076
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("01_Fill the matrix")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("01_Fill the matrix")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("25890087-14e1-4805-9c1e-0be55700e4f0")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.054054
85
0.725952
[ "MIT" ]
jsdelivrbot/Telerik-Academy-Homeworks
Module 1 - Essentials/02_C# Part 2/02_Multidimensional Arrays/01_Fill the matrix/Properties/AssemblyInfo.cs
1,448
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; namespace Azure.Management.Compute.Models { public partial class OSDiskImageEncryption : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Optional.IsDefined(DiskEncryptionSetId)) { writer.WritePropertyName("diskEncryptionSetId"); writer.WriteStringValue(DiskEncryptionSetId); } writer.WriteEndObject(); } internal static OSDiskImageEncryption DeserializeOSDiskImageEncryption(JsonElement element) { Optional<string> diskEncryptionSetId = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("diskEncryptionSetId")) { diskEncryptionSetId = property.Value.GetString(); continue; } } return new OSDiskImageEncryption(diskEncryptionSetId.Value); } } }
29.95122
99
0.613192
[ "MIT" ]
AbelHu/azure-sdk-for-net
sdk/testcommon/Azure.Management.Compute.2019_12/src/Generated/Models/OSDiskImageEncryption.Serialization.cs
1,228
C#
/* * 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 alexaforbusiness-2017-11-09.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.AlexaForBusiness.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.AlexaForBusiness.Model.Internal.MarshallTransformations { /// <summary> /// DeleteSkillAuthorization Request Marshaller /// </summary> public class DeleteSkillAuthorizationRequestMarshaller : IMarshaller<IRequest, DeleteSkillAuthorizationRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DeleteSkillAuthorizationRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DeleteSkillAuthorizationRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.AlexaForBusiness"); string target = "AlexaForBusiness.DeleteSkillAuthorization"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-11-09"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetRoomArn()) { context.Writer.WritePropertyName("RoomArn"); context.Writer.Write(publicRequest.RoomArn); } if(publicRequest.IsSetSkillId()) { context.Writer.WritePropertyName("SkillId"); context.Writer.Write(publicRequest.SkillId); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static DeleteSkillAuthorizationRequestMarshaller _instance = new DeleteSkillAuthorizationRequestMarshaller(); internal static DeleteSkillAuthorizationRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteSkillAuthorizationRequestMarshaller Instance { get { return _instance; } } } }
36.252252
163
0.631958
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/AlexaForBusiness/Generated/Model/Internal/MarshallTransformations/DeleteSkillAuthorizationRequestMarshaller.cs
4,024
C#
using System; using System.Collections.Generic; using System.Text; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace Uno.UI.Samples.Content.UITests.ContentControlTestsControl { public class SelectorInheritanceTemplateSelector : DataTemplateSelector { public DataTemplate TrueTemplate { get; set; } public DataTemplate FalseTemplate { get; set; } public DataTemplate NullTemplate { get; set; } protected override DataTemplate SelectTemplateCore(object item, DependencyObject container) { return SelectTemplateCore(item); } protected override DataTemplate SelectTemplateCore(object item) { var value = item?.ToString(); if(value != null) { return bool.Parse(value) ? TrueTemplate : FalseTemplate; } return NullTemplate; } } }
22.138889
93
0.747804
[ "Apache-2.0" ]
06needhamt/uno
src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/ContentControlTestsControl/SelectorInheritanceTemplateSelector.cs
799
C#
using System; namespace Metaheuristics { public class DiscreteGA2OptBest4SPP : DiscreteGA { public SPPInstance Instance { get; protected set; } protected int generatedSolutions; public DiscreteGA2OptBest4SPP(SPPInstance instance, int popSize, double mutationProbability, int[] lowerBounds, int[] upperBounds) : base(popSize, mutationProbability, lowerBounds, upperBounds) { Instance = instance; LocalSearchEnabled = true; generatedSolutions = 0; } protected override void LocalSearch(int[] individual) { SPPUtils.LocalSearch2OptBest(Instance, individual); } protected override double Fitness(int[] individual) { return SPPUtils.Fitness(Instance, individual); } protected override int[] InitialSolution () { int[] solution; if (generatedSolutions < 2) { solution = SPPUtils.GRCSolution(Instance, 1.0); } else { solution = SPPUtils.RandomSolution(Instance); } generatedSolutions++; return solution; } } }
22.255319
94
0.684512
[ "MIT" ]
yasserglez/metaheuristics
Common/SPP/DiscreteGA2OptBest4SPP.cs
1,046
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using System.Text.Json; using Azure.Core; using Azure.ResourceManager.Compute; namespace Azure.ResourceManager.Compute.Models { public partial class VirtualMachineScaleSetVMExtensionsListResult { internal static VirtualMachineScaleSetVMExtensionsListResult DeserializeVirtualMachineScaleSetVMExtensionsListResult(JsonElement element) { Optional<IReadOnlyList<VirtualMachineScaleSetVMExtensionData>> value = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("value")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List<VirtualMachineScaleSetVMExtensionData> array = new List<VirtualMachineScaleSetVMExtensionData>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(VirtualMachineScaleSetVMExtensionData.DeserializeVirtualMachineScaleSetVMExtensionData(item)); } value = array; continue; } } return new VirtualMachineScaleSetVMExtensionsListResult(Optional.ToList(value)); } } }
37.285714
145
0.621967
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/compute/Azure.ResourceManager.Compute/src/Generated/Models/VirtualMachineScaleSetVMExtensionsListResult.Serialization.cs
1,566
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace App.Areas.EmployeeManagement.Models { [Table("Employee")] public class Employee { [Key] public int EmployeeId { set; get; } [Required(ErrorMessage = "Must have employee name")] [Display(Name = "Employee name")] [StringLength(50)] public string EmployeeName { set; get; } [Display(Name = "Day of birth")] [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime DOB { set; get; } [Required(ErrorMessage = "Must have sex")] [Display(Name = "Sex")] [StringLength(10)] public string Sex { set; get; } [Required(ErrorMessage = "Must have place of birth")] [Display(Name = "Place of birth")] [StringLength(50)] public string PlaceOfBirth { set; get; } public string Address{get;set;} public List<Employee_Skill> Employee_Skills { get; set; } public int DepartmentId { set; get; } [ForeignKey("DepartmentId")] public Department Department{set;get;} public int LevelId { set; get; } [ForeignKey("LevelId")] public Level Level{set;get;} [Display(Name = "Avatar")] public byte[] ImageByte {get;set;} } }
26.589286
90
0.605776
[ "MIT" ]
LucasTran-tq/Business-Management-AspNet
Areas/EmployeeManagement/Models/Employee/Employee.cs
1,489
C#
#region Project Description [About this] // ================================================================================= // The whole Project is Licensed under the MIT License // ================================================================================= // ================================================================================= // Wiesend's Dynamic Link Library is a collection of reusable code that // I've written, or found throughout my programming career. // // I tried my very best to mention all of the original copyright holders. // I hope that all code which I've copied from others is mentioned and all // their copyrights are given. The copied code (or code snippets) could // already be modified by me or others. // ================================================================================= #endregion of Project Description #region Original Source Code [Links to all original source code] // ================================================================================= // Original Source Code [Links to all original source code] // ================================================================================= // https://github.com/JaCraig/Craig-s-Utility-Library // ================================================================================= // I didn't wrote this source totally on my own, this class could be nearly a // clone of the project of James Craig, I did highly get inspired by him, so // this piece of code isn't totally mine, shame on me, I'm not the best! // ================================================================================= #endregion of where is the original source code #region Licenses [MIT Licenses] #region MIT License [James Craig] // ================================================================================= // Copyright(c) 2014 <a href="http://www.gutgames.com">James Craig</a> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // ================================================================================= #endregion of MIT License [James Craig] #region MIT License [Dominik Wiesend] // ================================================================================= // Copyright(c) 2016 Dominik Wiesend. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // ================================================================================= #endregion of MIT License [Dominik Wiesend] #endregion of Licenses [MIT Licenses] using System; using System.ComponentModel; namespace Wiesend.Profiler { /// <summary> /// Holds timing/profiling related extensions /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public static class TimerExtensions { /// <summary> /// Times an action and places /// </summary> /// <param name="ActionToTime">Action to time</param> /// <param name="FunctionName">Name to associate with the action</param> public static void Time(this Action ActionToTime, string FunctionName = "") { if (ActionToTime == null) return; using (new Profiler(FunctionName)) ActionToTime(); } /// <summary> /// Times an action and places /// </summary> /// <typeparam name="T">Action input type</typeparam> /// <param name="ActionToTime">Action to time</param> /// <param name="FunctionName">Name to associate with the action</param> /// <param name="Object1">Object 1</param> public static void Time<T>(this Action<T> ActionToTime, T Object1, string FunctionName = "") { if (ActionToTime == null) return; using (new Profiler(FunctionName)) ActionToTime(Object1); } /// <summary> /// Times an action and places /// </summary> /// <typeparam name="T1">Action input type 1</typeparam> /// <typeparam name="T2">Action input type 2</typeparam> /// <param name="ActionToTime">Action to time</param> /// <param name="FunctionName">Name to associate with the action</param> /// <param name="Object1">Object 1</param> /// <param name="Object2">Object 2</param> public static void Time<T1, T2>(this Action<T1, T2> ActionToTime, T1 Object1, T2 Object2, string FunctionName = "") { if (ActionToTime == null) return; using (new Profiler(FunctionName)) ActionToTime(Object1, Object2); } /// <summary> /// Times an action and places /// </summary> /// <typeparam name="T1">Action input type 1</typeparam> /// <typeparam name="T2">Action input type 2</typeparam> /// <typeparam name="T3">Action input type 3</typeparam> /// <param name="ActionToTime">Action to time</param> /// <param name="FunctionName">Name to associate with the action</param> /// <param name="Object1">Object 1</param> /// <param name="Object2">Object 2</param> /// <param name="Object3">Object 3</param> public static void Time<T1, T2, T3>(this Action<T1, T2, T3> ActionToTime, T1 Object1, T2 Object2, T3 Object3, string FunctionName = "") { if (ActionToTime == null) return; using (new Profiler(FunctionName)) ActionToTime(Object1, Object2, Object3); } /// <summary> /// Times an action and places /// </summary> /// <param name="FuncToTime">Action to time</param> /// <param name="FunctionName">Name to associate with the action</param> /// <typeparam name="R">Type of the value to return</typeparam> /// <returns>The value returned by the Func</returns> public static R Time<R>(this Func<R> FuncToTime, string FunctionName = "") { if (FuncToTime == null) return default(R); using (new Profiler(FunctionName)) return FuncToTime(); } /// <summary> /// Times an action and places /// </summary> /// <param name="FuncToTime">Action to time</param> /// <param name="FunctionName">Name to associate with the action</param> /// <param name="Object1">Object 1</param> /// <typeparam name="T1">Object type 1</typeparam> /// <typeparam name="R">Type of the value to return</typeparam> /// <returns>The value returned by the Func</returns> public static R Time<T1, R>(this Func<T1, R> FuncToTime, T1 Object1, string FunctionName = "") { if (FuncToTime == null) return default(R); using (new Profiler(FunctionName)) return FuncToTime(Object1); } /// <summary> /// Times an action and places /// </summary> /// <param name="FuncToTime">Action to time</param> /// <param name="FunctionName">Name to associate with the action</param> /// <param name="Object1">Object 1</param> /// <param name="Object2">Object 2</param> /// <typeparam name="T1">Object type 1</typeparam> /// <typeparam name="T2">Object type 2</typeparam> /// <typeparam name="R">Type of the value to return</typeparam> /// <returns>The value returned by the Func</returns> public static R Time<T1, T2, R>(this Func<T1, T2, R> FuncToTime, T1 Object1, T2 Object2, string FunctionName = "") { if (FuncToTime == null) return default(R); using (new Profiler(FunctionName)) return FuncToTime(Object1, Object2); } /// <summary> /// Times an action and places /// </summary> /// <param name="FuncToTime">Action to time</param> /// <param name="FunctionName">Name to associate with the action</param> /// <param name="Object1">Object 1</param> /// <param name="Object2">Object 2</param> /// <param name="Object3">Object 3</param> /// <typeparam name="T1">Object type 1</typeparam> /// <typeparam name="T2">Object type 2</typeparam> /// <typeparam name="T3">Object type 3</typeparam> /// <typeparam name="R">Type of the value to return</typeparam> /// <returns>The value returned by the Func</returns> public static R Time<T1, T2, T3, R>(this Func<T1, T2, T3, R> FuncToTime, T1 Object1, T2 Object2, T3 Object3, string FunctionName = "") { if (FuncToTime == null) return default(R); using (new Profiler(FunctionName)) return FuncToTime(Object1, Object2, Object3); } } }
49.536036
143
0.567427
[ "MIT" ]
DominikWiesend/wiesend
projects/Wiesend.Profiler/Profiler/ExtensionMethods/TimerExtensions.cs
10,999
C#
using System.Linq; using System.Management.Automation; using System.Net; using dotnetlink; namespace dotnetlinkps.IPConfiguration { [Cmdlet(VerbsCommon.Remove, "IPConfiguration")] public class RemoveIpConfiguration : PSCmdlet { private NetlinkSocket _socket; [Parameter] public IPAddress Address { get; set; } [Parameter] public byte Netmask { get; set; } [Parameter] public string Interface { get; set; } protected override void BeginProcessing() { _socket = SingletonRepository.getNetlinkSocket(); var nicIndex = _socket.GetNetworkInterfaces().First(i => i.InterfaceName.ToLower() == Interface.ToLower()).Index; _socket.RemoveIpAddress(new IpAddress(Address, Netmask, nicIndex)); } protected override void ProcessRecord() { base.ProcessRecord(); } protected override void EndProcessing() { base.EndProcessing(); } protected override void StopProcessing() { base.StopProcessing(); } } }
27.75
125
0.627027
[ "MIT" ]
judgie97/dotnetlink
src/dotnetlinkps/IPConfiguration/RemoveIpConfiguration.cs
1,110
C#
using UnrealBuildTool; using System.IO; using System; public class JavascriptWebSocket : ModuleRules { public JavascriptWebSocket(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "V8", "Sockets", "OnlineSubSystemUtils", "Networking" }); bool bPlatformSupportsLibWebsockets = Target.Platform == UnrealTargetPlatform.Win32 || Target.Platform == UnrealTargetPlatform.Win64 || Target.Platform == UnrealTargetPlatform.Android || Target.Platform == UnrealTargetPlatform.Mac || Target.IsInPlatformGroup(UnrealPlatformGroup.Unix); if (bPlatformSupportsLibWebsockets) { PublicDefinitions.Add("WITH_JSWEBSOCKET=1"); HackWebSocketIncludeDir(Path.Combine(Directory.GetCurrentDirectory(), "ThirdParty", "libWebSockets", "libWebSockets"), Target); } else { PublicDefinitions.Add("WITH_JSWEBSOCKET=0"); } } private void HackWebSocketIncludeDir(String WebsocketPath, ReadOnlyTargetRules Target) { string PlatformSubdir = Target.Platform.ToString(); bool bHasZlib = false; if (Target.Platform == UnrealTargetPlatform.Win64 || Target.Platform == UnrealTargetPlatform.Win32) { PlatformSubdir = Path.Combine(PlatformSubdir, "VS" + Target.WindowsPlatform.GetVisualStudioCompilerVersionName()); bHasZlib = true; } else if (Target.Platform == UnrealTargetPlatform.Linux) { PlatformSubdir = Path.Combine(PlatformSubdir, Target.Architecture); } PrivateDependencyModuleNames.Add("libWebSockets"); if (bHasZlib) { PrivateDependencyModuleNames.Add("zlib"); } PrivateIncludePaths.Add(Path.Combine(WebsocketPath, "include")); PrivateIncludePaths.Add(Path.Combine(WebsocketPath, "include", PlatformSubdir)); } }
32.969697
139
0.633272
[ "BSD-3-Clause" ]
2youyou2/Unreal.js-core
Source/JavascriptWebSocket/JavascriptWebSocket.Build.cs
2,176
C#
// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from https://github.com/llvm/llvm-project/tree/llvmorg-14.0.0/clang/include/clang-c // Original source is Copyright (c) the LLVM Project and Contributors. Licensed under the Apache License v2.0 with LLVM Exceptions. See NOTICE.txt in the project root for license information. namespace ClangSharp.Interop { public enum CXCommentKind { CXComment_Null = 0, CXComment_Text = 1, CXComment_InlineCommand = 2, CXComment_HTMLStartTag = 3, CXComment_HTMLEndTag = 4, CXComment_Paragraph = 5, CXComment_BlockCommand = 6, CXComment_ParamCommand = 7, CXComment_TParamCommand = 8, CXComment_VerbatimBlockCommand = 9, CXComment_VerbatimBlockLine = 10, CXComment_VerbatimLine = 11, CXComment_FullComment = 12, } }
39.88
191
0.705115
[ "MIT" ]
Microsoft/ClangSharp
sources/ClangSharp.Interop/CXCommentKind.cs
997
C#
/* * 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 config-2014-11-12.normal.json service model. */ using System; using System.Collections.Generic; using Amazon.ConfigService.Model; using Amazon.ConfigService.Model.Internal.MarshallTransformations; using Amazon.ConfigService.Internal; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.ConfigService { /// <summary> /// Implementation for accessing ConfigService /// /// AWS Config /// <para> /// AWS Config provides a way to keep track of the configurations of all the AWS resources /// associated with your AWS account. You can use AWS Config to get the current and historical /// configurations of each AWS resource and also to get information about the relationship /// between the resources. An AWS resource can be an Amazon Compute Cloud (Amazon EC2) /// instance, an Elastic Block Store (EBS) volume, an elastic network Interface (ENI), /// or a security group. For a complete list of resources currently supported by AWS Config, /// see <a href="http://docs.aws.amazon.com/config/latest/developerguide/resource-config-reference.html#supported-resources">Supported /// AWS Resources</a>. /// </para> /// /// <para> /// You can access and manage AWS Config through the AWS Management Console, the AWS Command /// Line Interface (AWS CLI), the AWS Config API, or the AWS SDKs for AWS Config. This /// reference guide contains documentation for the AWS Config API and the AWS CLI commands /// that you can use to manage AWS Config. The AWS Config API uses the Signature Version /// 4 protocol for signing requests. For more information about how to sign a request /// with this protocol, see <a href="http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature /// Version 4 Signing Process</a>. For detailed information about AWS Config features /// and their associated actions or commands, as well as how to work with AWS Management /// Console, see <a href="http://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html">What /// Is AWS Config</a> in the <i>AWS Config Developer Guide</i>. /// </para> /// </summary> public partial class AmazonConfigServiceClient : AmazonServiceClient, IAmazonConfigService { private static IServiceMetadata serviceMetadata = new AmazonConfigServiceMetadata(); #region Constructors /// <summary> /// Constructs AmazonConfigServiceClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> public AmazonConfigServiceClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonConfigServiceConfig()) { } /// <summary> /// Constructs AmazonConfigServiceClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="region">The region to connect.</param> public AmazonConfigServiceClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonConfigServiceConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonConfigServiceClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="config">The AmazonConfigServiceClient Configuration Object</param> public AmazonConfigServiceClient(AmazonConfigServiceConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } /// <summary> /// Constructs AmazonConfigServiceClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonConfigServiceClient(AWSCredentials credentials) : this(credentials, new AmazonConfigServiceConfig()) { } /// <summary> /// Constructs AmazonConfigServiceClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonConfigServiceClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonConfigServiceConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonConfigServiceClient with AWS Credentials and an /// AmazonConfigServiceClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonConfigServiceClient Configuration Object</param> public AmazonConfigServiceClient(AWSCredentials credentials, AmazonConfigServiceConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonConfigServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonConfigServiceClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonConfigServiceConfig()) { } /// <summary> /// Constructs AmazonConfigServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonConfigServiceClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonConfigServiceConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonConfigServiceClient with AWS Access Key ID, AWS Secret Key and an /// AmazonConfigServiceClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonConfigServiceClient Configuration Object</param> public AmazonConfigServiceClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonConfigServiceConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonConfigServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonConfigServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonConfigServiceConfig()) { } /// <summary> /// Constructs AmazonConfigServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonConfigServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonConfigServiceConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonConfigServiceClient with AWS Access Key ID, AWS Secret Key and an /// AmazonConfigServiceClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonConfigServiceClient Configuration Object</param> public AmazonConfigServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonConfigServiceConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } /// <summary> /// Capture metadata for the service. /// </summary> protected override IServiceMetadata ServiceMetadata { get { return serviceMetadata; } } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region BatchGetResourceConfig /// <summary> /// Returns the current configuration for one or more requested resources. The operation /// also returns a list of resources that are not processed in the current request. If /// there are no unprocessed resources, the operation returns an empty unprocessedResourceKeys /// list. /// /// <note> <ul> <li> /// <para> /// The API does not return results for deleted resources. /// </para> /// </li> <li> /// <para> /// The API does not return any tags for the requested resources. This information is /// filtered out of the supplementaryConfiguration section of the API response. /// </para> /// </li> </ul> </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchGetResourceConfig service method.</param> /// /// <returns>The response from the BatchGetResourceConfig service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoAvailableConfigurationRecorderException"> /// There are no configuration recorders available to provide the role needed to describe /// your resources. Create a configuration recorder. /// </exception> /// <exception cref="Amazon.ConfigService.Model.ValidationException"> /// The requested action is not valid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/BatchGetResourceConfig">REST API Reference for BatchGetResourceConfig Operation</seealso> public virtual BatchGetResourceConfigResponse BatchGetResourceConfig(BatchGetResourceConfigRequest request) { var marshaller = BatchGetResourceConfigRequestMarshaller.Instance; var unmarshaller = BatchGetResourceConfigResponseUnmarshaller.Instance; return Invoke<BatchGetResourceConfigRequest,BatchGetResourceConfigResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the BatchGetResourceConfig operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the BatchGetResourceConfig operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndBatchGetResourceConfig /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/BatchGetResourceConfig">REST API Reference for BatchGetResourceConfig Operation</seealso> public virtual IAsyncResult BeginBatchGetResourceConfig(BatchGetResourceConfigRequest request, AsyncCallback callback, object state) { var marshaller = BatchGetResourceConfigRequestMarshaller.Instance; var unmarshaller = BatchGetResourceConfigResponseUnmarshaller.Instance; return BeginInvoke<BatchGetResourceConfigRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the BatchGetResourceConfig operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginBatchGetResourceConfig.</param> /// /// <returns>Returns a BatchGetResourceConfigResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/BatchGetResourceConfig">REST API Reference for BatchGetResourceConfig Operation</seealso> public virtual BatchGetResourceConfigResponse EndBatchGetResourceConfig(IAsyncResult asyncResult) { return EndInvoke<BatchGetResourceConfigResponse>(asyncResult); } #endregion #region DeleteAggregationAuthorization /// <summary> /// Deletes the authorization granted to the specified configuration aggregator account /// in a specified region. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteAggregationAuthorization service method.</param> /// /// <returns>The response from the DeleteAggregationAuthorization service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteAggregationAuthorization">REST API Reference for DeleteAggregationAuthorization Operation</seealso> public virtual DeleteAggregationAuthorizationResponse DeleteAggregationAuthorization(DeleteAggregationAuthorizationRequest request) { var marshaller = DeleteAggregationAuthorizationRequestMarshaller.Instance; var unmarshaller = DeleteAggregationAuthorizationResponseUnmarshaller.Instance; return Invoke<DeleteAggregationAuthorizationRequest,DeleteAggregationAuthorizationResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteAggregationAuthorization operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteAggregationAuthorization operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteAggregationAuthorization /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteAggregationAuthorization">REST API Reference for DeleteAggregationAuthorization Operation</seealso> public virtual IAsyncResult BeginDeleteAggregationAuthorization(DeleteAggregationAuthorizationRequest request, AsyncCallback callback, object state) { var marshaller = DeleteAggregationAuthorizationRequestMarshaller.Instance; var unmarshaller = DeleteAggregationAuthorizationResponseUnmarshaller.Instance; return BeginInvoke<DeleteAggregationAuthorizationRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteAggregationAuthorization operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteAggregationAuthorization.</param> /// /// <returns>Returns a DeleteAggregationAuthorizationResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteAggregationAuthorization">REST API Reference for DeleteAggregationAuthorization Operation</seealso> public virtual DeleteAggregationAuthorizationResponse EndDeleteAggregationAuthorization(IAsyncResult asyncResult) { return EndInvoke<DeleteAggregationAuthorizationResponse>(asyncResult); } #endregion #region DeleteConfigRule /// <summary> /// Deletes the specified AWS Config rule and all of its evaluation results. /// /// /// <para> /// AWS Config sets the state of a rule to <code>DELETING</code> until the deletion is /// complete. You cannot update a rule while it is in this state. If you make a <code>PutConfigRule</code> /// or <code>DeleteConfigRule</code> request for the rule, you will receive a <code>ResourceInUseException</code>. /// </para> /// /// <para> /// You can check the state of a rule by using the <code>DescribeConfigRules</code> request. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteConfigRule service method.</param> /// /// <returns>The response from the DeleteConfigRule service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigRuleException"> /// One or more AWS Config rules in the request are invalid. Verify that the rule names /// are correct and try again. /// </exception> /// <exception cref="Amazon.ConfigService.Model.ResourceInUseException"> /// The rule is currently being deleted or the rule is deleting your evaluation results. /// Try your request again later. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteConfigRule">REST API Reference for DeleteConfigRule Operation</seealso> public virtual DeleteConfigRuleResponse DeleteConfigRule(DeleteConfigRuleRequest request) { var marshaller = DeleteConfigRuleRequestMarshaller.Instance; var unmarshaller = DeleteConfigRuleResponseUnmarshaller.Instance; return Invoke<DeleteConfigRuleRequest,DeleteConfigRuleResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteConfigRule operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteConfigRule operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteConfigRule /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteConfigRule">REST API Reference for DeleteConfigRule Operation</seealso> public virtual IAsyncResult BeginDeleteConfigRule(DeleteConfigRuleRequest request, AsyncCallback callback, object state) { var marshaller = DeleteConfigRuleRequestMarshaller.Instance; var unmarshaller = DeleteConfigRuleResponseUnmarshaller.Instance; return BeginInvoke<DeleteConfigRuleRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteConfigRule operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteConfigRule.</param> /// /// <returns>Returns a DeleteConfigRuleResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteConfigRule">REST API Reference for DeleteConfigRule Operation</seealso> public virtual DeleteConfigRuleResponse EndDeleteConfigRule(IAsyncResult asyncResult) { return EndInvoke<DeleteConfigRuleResponse>(asyncResult); } #endregion #region DeleteConfigurationAggregator /// <summary> /// Deletes the specified configuration aggregator and the aggregated data associated /// with the aggregator. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteConfigurationAggregator service method.</param> /// /// <returns>The response from the DeleteConfigurationAggregator service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationAggregatorException"> /// You have specified a configuration aggregator that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteConfigurationAggregator">REST API Reference for DeleteConfigurationAggregator Operation</seealso> public virtual DeleteConfigurationAggregatorResponse DeleteConfigurationAggregator(DeleteConfigurationAggregatorRequest request) { var marshaller = DeleteConfigurationAggregatorRequestMarshaller.Instance; var unmarshaller = DeleteConfigurationAggregatorResponseUnmarshaller.Instance; return Invoke<DeleteConfigurationAggregatorRequest,DeleteConfigurationAggregatorResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteConfigurationAggregator operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteConfigurationAggregator operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteConfigurationAggregator /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteConfigurationAggregator">REST API Reference for DeleteConfigurationAggregator Operation</seealso> public virtual IAsyncResult BeginDeleteConfigurationAggregator(DeleteConfigurationAggregatorRequest request, AsyncCallback callback, object state) { var marshaller = DeleteConfigurationAggregatorRequestMarshaller.Instance; var unmarshaller = DeleteConfigurationAggregatorResponseUnmarshaller.Instance; return BeginInvoke<DeleteConfigurationAggregatorRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteConfigurationAggregator operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteConfigurationAggregator.</param> /// /// <returns>Returns a DeleteConfigurationAggregatorResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteConfigurationAggregator">REST API Reference for DeleteConfigurationAggregator Operation</seealso> public virtual DeleteConfigurationAggregatorResponse EndDeleteConfigurationAggregator(IAsyncResult asyncResult) { return EndInvoke<DeleteConfigurationAggregatorResponse>(asyncResult); } #endregion #region DeleteConfigurationRecorder /// <summary> /// Deletes the configuration recorder. /// /// /// <para> /// After the configuration recorder is deleted, AWS Config will not record resource configuration /// changes until you create a new configuration recorder. /// </para> /// /// <para> /// This action does not delete the configuration information that was previously recorded. /// You will be able to access the previously recorded information by using the <code>GetResourceConfigHistory</code> /// action, but you will not be able to access this information in the AWS Config console /// until you create a new configuration recorder. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteConfigurationRecorder service method.</param> /// /// <returns>The response from the DeleteConfigurationRecorder service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationRecorderException"> /// You have specified a configuration recorder that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteConfigurationRecorder">REST API Reference for DeleteConfigurationRecorder Operation</seealso> public virtual DeleteConfigurationRecorderResponse DeleteConfigurationRecorder(DeleteConfigurationRecorderRequest request) { var marshaller = DeleteConfigurationRecorderRequestMarshaller.Instance; var unmarshaller = DeleteConfigurationRecorderResponseUnmarshaller.Instance; return Invoke<DeleteConfigurationRecorderRequest,DeleteConfigurationRecorderResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteConfigurationRecorder operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteConfigurationRecorder operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteConfigurationRecorder /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteConfigurationRecorder">REST API Reference for DeleteConfigurationRecorder Operation</seealso> public virtual IAsyncResult BeginDeleteConfigurationRecorder(DeleteConfigurationRecorderRequest request, AsyncCallback callback, object state) { var marshaller = DeleteConfigurationRecorderRequestMarshaller.Instance; var unmarshaller = DeleteConfigurationRecorderResponseUnmarshaller.Instance; return BeginInvoke<DeleteConfigurationRecorderRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteConfigurationRecorder operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteConfigurationRecorder.</param> /// /// <returns>Returns a DeleteConfigurationRecorderResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteConfigurationRecorder">REST API Reference for DeleteConfigurationRecorder Operation</seealso> public virtual DeleteConfigurationRecorderResponse EndDeleteConfigurationRecorder(IAsyncResult asyncResult) { return EndInvoke<DeleteConfigurationRecorderResponse>(asyncResult); } #endregion #region DeleteDeliveryChannel /// <summary> /// Deletes the delivery channel. /// /// /// <para> /// Before you can delete the delivery channel, you must stop the configuration recorder /// by using the <a>StopConfigurationRecorder</a> action. /// </para> /// </summary> /// <param name="deliveryChannelName">The name of the delivery channel to delete.</param> /// /// <returns>The response from the DeleteDeliveryChannel service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.LastDeliveryChannelDeleteFailedException"> /// You cannot delete the delivery channel you specified because the configuration recorder /// is running. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchDeliveryChannelException"> /// You have specified a delivery channel that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteDeliveryChannel">REST API Reference for DeleteDeliveryChannel Operation</seealso> public virtual DeleteDeliveryChannelResponse DeleteDeliveryChannel(string deliveryChannelName) { var request = new DeleteDeliveryChannelRequest(); request.DeliveryChannelName = deliveryChannelName; return DeleteDeliveryChannel(request); } /// <summary> /// Deletes the delivery channel. /// /// /// <para> /// Before you can delete the delivery channel, you must stop the configuration recorder /// by using the <a>StopConfigurationRecorder</a> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteDeliveryChannel service method.</param> /// /// <returns>The response from the DeleteDeliveryChannel service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.LastDeliveryChannelDeleteFailedException"> /// You cannot delete the delivery channel you specified because the configuration recorder /// is running. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchDeliveryChannelException"> /// You have specified a delivery channel that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteDeliveryChannel">REST API Reference for DeleteDeliveryChannel Operation</seealso> public virtual DeleteDeliveryChannelResponse DeleteDeliveryChannel(DeleteDeliveryChannelRequest request) { var marshaller = DeleteDeliveryChannelRequestMarshaller.Instance; var unmarshaller = DeleteDeliveryChannelResponseUnmarshaller.Instance; return Invoke<DeleteDeliveryChannelRequest,DeleteDeliveryChannelResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteDeliveryChannel operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteDeliveryChannel operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteDeliveryChannel /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteDeliveryChannel">REST API Reference for DeleteDeliveryChannel Operation</seealso> public virtual IAsyncResult BeginDeleteDeliveryChannel(DeleteDeliveryChannelRequest request, AsyncCallback callback, object state) { var marshaller = DeleteDeliveryChannelRequestMarshaller.Instance; var unmarshaller = DeleteDeliveryChannelResponseUnmarshaller.Instance; return BeginInvoke<DeleteDeliveryChannelRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteDeliveryChannel operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteDeliveryChannel.</param> /// /// <returns>Returns a DeleteDeliveryChannelResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteDeliveryChannel">REST API Reference for DeleteDeliveryChannel Operation</seealso> public virtual DeleteDeliveryChannelResponse EndDeleteDeliveryChannel(IAsyncResult asyncResult) { return EndInvoke<DeleteDeliveryChannelResponse>(asyncResult); } #endregion #region DeleteEvaluationResults /// <summary> /// Deletes the evaluation results for the specified AWS Config rule. You can specify /// one AWS Config rule per request. After you delete the evaluation results, you can /// call the <a>StartConfigRulesEvaluation</a> API to start evaluating your AWS resources /// against the rule. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteEvaluationResults service method.</param> /// /// <returns>The response from the DeleteEvaluationResults service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigRuleException"> /// One or more AWS Config rules in the request are invalid. Verify that the rule names /// are correct and try again. /// </exception> /// <exception cref="Amazon.ConfigService.Model.ResourceInUseException"> /// The rule is currently being deleted or the rule is deleting your evaluation results. /// Try your request again later. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteEvaluationResults">REST API Reference for DeleteEvaluationResults Operation</seealso> public virtual DeleteEvaluationResultsResponse DeleteEvaluationResults(DeleteEvaluationResultsRequest request) { var marshaller = DeleteEvaluationResultsRequestMarshaller.Instance; var unmarshaller = DeleteEvaluationResultsResponseUnmarshaller.Instance; return Invoke<DeleteEvaluationResultsRequest,DeleteEvaluationResultsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteEvaluationResults operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteEvaluationResults operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteEvaluationResults /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteEvaluationResults">REST API Reference for DeleteEvaluationResults Operation</seealso> public virtual IAsyncResult BeginDeleteEvaluationResults(DeleteEvaluationResultsRequest request, AsyncCallback callback, object state) { var marshaller = DeleteEvaluationResultsRequestMarshaller.Instance; var unmarshaller = DeleteEvaluationResultsResponseUnmarshaller.Instance; return BeginInvoke<DeleteEvaluationResultsRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteEvaluationResults operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteEvaluationResults.</param> /// /// <returns>Returns a DeleteEvaluationResultsResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteEvaluationResults">REST API Reference for DeleteEvaluationResults Operation</seealso> public virtual DeleteEvaluationResultsResponse EndDeleteEvaluationResults(IAsyncResult asyncResult) { return EndInvoke<DeleteEvaluationResultsResponse>(asyncResult); } #endregion #region DeletePendingAggregationRequest /// <summary> /// Deletes pending authorization requests for a specified aggregator account in a specified /// region. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeletePendingAggregationRequest service method.</param> /// /// <returns>The response from the DeletePendingAggregationRequest service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeletePendingAggregationRequest">REST API Reference for DeletePendingAggregationRequest Operation</seealso> public virtual DeletePendingAggregationRequestResponse DeletePendingAggregationRequest(DeletePendingAggregationRequestRequest request) { var marshaller = DeletePendingAggregationRequestRequestMarshaller.Instance; var unmarshaller = DeletePendingAggregationRequestResponseUnmarshaller.Instance; return Invoke<DeletePendingAggregationRequestRequest,DeletePendingAggregationRequestResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeletePendingAggregationRequest operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeletePendingAggregationRequest operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeletePendingAggregationRequest /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeletePendingAggregationRequest">REST API Reference for DeletePendingAggregationRequest Operation</seealso> public virtual IAsyncResult BeginDeletePendingAggregationRequest(DeletePendingAggregationRequestRequest request, AsyncCallback callback, object state) { var marshaller = DeletePendingAggregationRequestRequestMarshaller.Instance; var unmarshaller = DeletePendingAggregationRequestResponseUnmarshaller.Instance; return BeginInvoke<DeletePendingAggregationRequestRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeletePendingAggregationRequest operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeletePendingAggregationRequest.</param> /// /// <returns>Returns a DeletePendingAggregationRequestResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeletePendingAggregationRequest">REST API Reference for DeletePendingAggregationRequest Operation</seealso> public virtual DeletePendingAggregationRequestResponse EndDeletePendingAggregationRequest(IAsyncResult asyncResult) { return EndInvoke<DeletePendingAggregationRequestResponse>(asyncResult); } #endregion #region DeleteRetentionConfiguration /// <summary> /// Deletes the retention configuration. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteRetentionConfiguration service method.</param> /// /// <returns>The response from the DeleteRetentionConfiguration service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchRetentionConfigurationException"> /// You have specified a retention configuration that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteRetentionConfiguration">REST API Reference for DeleteRetentionConfiguration Operation</seealso> public virtual DeleteRetentionConfigurationResponse DeleteRetentionConfiguration(DeleteRetentionConfigurationRequest request) { var marshaller = DeleteRetentionConfigurationRequestMarshaller.Instance; var unmarshaller = DeleteRetentionConfigurationResponseUnmarshaller.Instance; return Invoke<DeleteRetentionConfigurationRequest,DeleteRetentionConfigurationResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteRetentionConfiguration operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteRetentionConfiguration operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteRetentionConfiguration /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteRetentionConfiguration">REST API Reference for DeleteRetentionConfiguration Operation</seealso> public virtual IAsyncResult BeginDeleteRetentionConfiguration(DeleteRetentionConfigurationRequest request, AsyncCallback callback, object state) { var marshaller = DeleteRetentionConfigurationRequestMarshaller.Instance; var unmarshaller = DeleteRetentionConfigurationResponseUnmarshaller.Instance; return BeginInvoke<DeleteRetentionConfigurationRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteRetentionConfiguration operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteRetentionConfiguration.</param> /// /// <returns>Returns a DeleteRetentionConfigurationResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeleteRetentionConfiguration">REST API Reference for DeleteRetentionConfiguration Operation</seealso> public virtual DeleteRetentionConfigurationResponse EndDeleteRetentionConfiguration(IAsyncResult asyncResult) { return EndInvoke<DeleteRetentionConfigurationResponse>(asyncResult); } #endregion #region DeliverConfigSnapshot /// <summary> /// Schedules delivery of a configuration snapshot to the Amazon S3 bucket in the specified /// delivery channel. After the delivery has started, AWS Config sends the following notifications /// using an Amazon SNS topic that you have specified. /// /// <ul> <li> /// <para> /// Notification of the start of the delivery. /// </para> /// </li> <li> /// <para> /// Notification of the completion of the delivery, if the delivery was successfully completed. /// </para> /// </li> <li> /// <para> /// Notification of delivery failure, if the delivery failed. /// </para> /// </li> </ul> /// </summary> /// <param name="deliveryChannelName">The name of the delivery channel through which the snapshot is delivered.</param> /// /// <returns>The response from the DeliverConfigSnapshot service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoAvailableConfigurationRecorderException"> /// There are no configuration recorders available to provide the role needed to describe /// your resources. Create a configuration recorder. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoRunningConfigurationRecorderException"> /// There is no configuration recorder running. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchDeliveryChannelException"> /// You have specified a delivery channel that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeliverConfigSnapshot">REST API Reference for DeliverConfigSnapshot Operation</seealso> public virtual DeliverConfigSnapshotResponse DeliverConfigSnapshot(string deliveryChannelName) { var request = new DeliverConfigSnapshotRequest(); request.DeliveryChannelName = deliveryChannelName; return DeliverConfigSnapshot(request); } /// <summary> /// Schedules delivery of a configuration snapshot to the Amazon S3 bucket in the specified /// delivery channel. After the delivery has started, AWS Config sends the following notifications /// using an Amazon SNS topic that you have specified. /// /// <ul> <li> /// <para> /// Notification of the start of the delivery. /// </para> /// </li> <li> /// <para> /// Notification of the completion of the delivery, if the delivery was successfully completed. /// </para> /// </li> <li> /// <para> /// Notification of delivery failure, if the delivery failed. /// </para> /// </li> </ul> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeliverConfigSnapshot service method.</param> /// /// <returns>The response from the DeliverConfigSnapshot service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoAvailableConfigurationRecorderException"> /// There are no configuration recorders available to provide the role needed to describe /// your resources. Create a configuration recorder. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoRunningConfigurationRecorderException"> /// There is no configuration recorder running. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchDeliveryChannelException"> /// You have specified a delivery channel that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeliverConfigSnapshot">REST API Reference for DeliverConfigSnapshot Operation</seealso> public virtual DeliverConfigSnapshotResponse DeliverConfigSnapshot(DeliverConfigSnapshotRequest request) { var marshaller = DeliverConfigSnapshotRequestMarshaller.Instance; var unmarshaller = DeliverConfigSnapshotResponseUnmarshaller.Instance; return Invoke<DeliverConfigSnapshotRequest,DeliverConfigSnapshotResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeliverConfigSnapshot operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeliverConfigSnapshot operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeliverConfigSnapshot /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeliverConfigSnapshot">REST API Reference for DeliverConfigSnapshot Operation</seealso> public virtual IAsyncResult BeginDeliverConfigSnapshot(DeliverConfigSnapshotRequest request, AsyncCallback callback, object state) { var marshaller = DeliverConfigSnapshotRequestMarshaller.Instance; var unmarshaller = DeliverConfigSnapshotResponseUnmarshaller.Instance; return BeginInvoke<DeliverConfigSnapshotRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeliverConfigSnapshot operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeliverConfigSnapshot.</param> /// /// <returns>Returns a DeliverConfigSnapshotResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeliverConfigSnapshot">REST API Reference for DeliverConfigSnapshot Operation</seealso> public virtual DeliverConfigSnapshotResponse EndDeliverConfigSnapshot(IAsyncResult asyncResult) { return EndInvoke<DeliverConfigSnapshotResponse>(asyncResult); } #endregion #region DescribeAggregateComplianceByConfigRules /// <summary> /// Returns a list of compliant and noncompliant rules with the number of resources for /// compliant and noncompliant rules. /// /// <note> /// <para> /// The results can return an empty result page, but if you have a nextToken, the results /// are displayed on the next page. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeAggregateComplianceByConfigRules service method.</param> /// /// <returns>The response from the DescribeAggregateComplianceByConfigRules service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidLimitException"> /// The specified limit is outside the allowable range. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidNextTokenException"> /// The specified next token is invalid. Specify the <code>nextToken</code> string that /// was returned in the previous response to get the next page of results. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationAggregatorException"> /// You have specified a configuration aggregator that does not exist. /// </exception> /// <exception cref="Amazon.ConfigService.Model.ValidationException"> /// The requested action is not valid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeAggregateComplianceByConfigRules">REST API Reference for DescribeAggregateComplianceByConfigRules Operation</seealso> public virtual DescribeAggregateComplianceByConfigRulesResponse DescribeAggregateComplianceByConfigRules(DescribeAggregateComplianceByConfigRulesRequest request) { var marshaller = DescribeAggregateComplianceByConfigRulesRequestMarshaller.Instance; var unmarshaller = DescribeAggregateComplianceByConfigRulesResponseUnmarshaller.Instance; return Invoke<DescribeAggregateComplianceByConfigRulesRequest,DescribeAggregateComplianceByConfigRulesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeAggregateComplianceByConfigRules operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeAggregateComplianceByConfigRules operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeAggregateComplianceByConfigRules /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeAggregateComplianceByConfigRules">REST API Reference for DescribeAggregateComplianceByConfigRules Operation</seealso> public virtual IAsyncResult BeginDescribeAggregateComplianceByConfigRules(DescribeAggregateComplianceByConfigRulesRequest request, AsyncCallback callback, object state) { var marshaller = DescribeAggregateComplianceByConfigRulesRequestMarshaller.Instance; var unmarshaller = DescribeAggregateComplianceByConfigRulesResponseUnmarshaller.Instance; return BeginInvoke<DescribeAggregateComplianceByConfigRulesRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeAggregateComplianceByConfigRules operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeAggregateComplianceByConfigRules.</param> /// /// <returns>Returns a DescribeAggregateComplianceByConfigRulesResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeAggregateComplianceByConfigRules">REST API Reference for DescribeAggregateComplianceByConfigRules Operation</seealso> public virtual DescribeAggregateComplianceByConfigRulesResponse EndDescribeAggregateComplianceByConfigRules(IAsyncResult asyncResult) { return EndInvoke<DescribeAggregateComplianceByConfigRulesResponse>(asyncResult); } #endregion #region DescribeAggregationAuthorizations /// <summary> /// Returns a list of authorizations granted to various aggregator accounts and regions. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeAggregationAuthorizations service method.</param> /// /// <returns>The response from the DescribeAggregationAuthorizations service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidLimitException"> /// The specified limit is outside the allowable range. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidNextTokenException"> /// The specified next token is invalid. Specify the <code>nextToken</code> string that /// was returned in the previous response to get the next page of results. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeAggregationAuthorizations">REST API Reference for DescribeAggregationAuthorizations Operation</seealso> public virtual DescribeAggregationAuthorizationsResponse DescribeAggregationAuthorizations(DescribeAggregationAuthorizationsRequest request) { var marshaller = DescribeAggregationAuthorizationsRequestMarshaller.Instance; var unmarshaller = DescribeAggregationAuthorizationsResponseUnmarshaller.Instance; return Invoke<DescribeAggregationAuthorizationsRequest,DescribeAggregationAuthorizationsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeAggregationAuthorizations operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeAggregationAuthorizations operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeAggregationAuthorizations /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeAggregationAuthorizations">REST API Reference for DescribeAggregationAuthorizations Operation</seealso> public virtual IAsyncResult BeginDescribeAggregationAuthorizations(DescribeAggregationAuthorizationsRequest request, AsyncCallback callback, object state) { var marshaller = DescribeAggregationAuthorizationsRequestMarshaller.Instance; var unmarshaller = DescribeAggregationAuthorizationsResponseUnmarshaller.Instance; return BeginInvoke<DescribeAggregationAuthorizationsRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeAggregationAuthorizations operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeAggregationAuthorizations.</param> /// /// <returns>Returns a DescribeAggregationAuthorizationsResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeAggregationAuthorizations">REST API Reference for DescribeAggregationAuthorizations Operation</seealso> public virtual DescribeAggregationAuthorizationsResponse EndDescribeAggregationAuthorizations(IAsyncResult asyncResult) { return EndInvoke<DescribeAggregationAuthorizationsResponse>(asyncResult); } #endregion #region DescribeComplianceByConfigRule /// <summary> /// Indicates whether the specified AWS Config rules are compliant. If a rule is noncompliant, /// this action returns the number of AWS resources that do not comply with the rule. /// /// /// <para> /// A rule is compliant if all of the evaluated resources comply with it. It is noncompliant /// if any of these resources do not comply. /// </para> /// /// <para> /// If AWS Config has no current evaluation results for the rule, it returns <code>INSUFFICIENT_DATA</code>. /// This result might indicate one of the following conditions: /// </para> /// <ul> <li> /// <para> /// AWS Config has never invoked an evaluation for the rule. To check whether it has, /// use the <code>DescribeConfigRuleEvaluationStatus</code> action to get the <code>LastSuccessfulInvocationTime</code> /// and <code>LastFailedInvocationTime</code>. /// </para> /// </li> <li> /// <para> /// The rule's AWS Lambda function is failing to send evaluation results to AWS Config. /// Verify that the role you assigned to your configuration recorder includes the <code>config:PutEvaluations</code> /// permission. If the rule is a custom rule, verify that the AWS Lambda execution role /// includes the <code>config:PutEvaluations</code> permission. /// </para> /// </li> <li> /// <para> /// The rule's AWS Lambda function has returned <code>NOT_APPLICABLE</code> for all evaluation /// results. This can occur if the resources were deleted or removed from the rule's scope. /// </para> /// </li> </ul> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeComplianceByConfigRule service method.</param> /// /// <returns>The response from the DescribeComplianceByConfigRule service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidNextTokenException"> /// The specified next token is invalid. Specify the <code>nextToken</code> string that /// was returned in the previous response to get the next page of results. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigRuleException"> /// One or more AWS Config rules in the request are invalid. Verify that the rule names /// are correct and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeComplianceByConfigRule">REST API Reference for DescribeComplianceByConfigRule Operation</seealso> public virtual DescribeComplianceByConfigRuleResponse DescribeComplianceByConfigRule(DescribeComplianceByConfigRuleRequest request) { var marshaller = DescribeComplianceByConfigRuleRequestMarshaller.Instance; var unmarshaller = DescribeComplianceByConfigRuleResponseUnmarshaller.Instance; return Invoke<DescribeComplianceByConfigRuleRequest,DescribeComplianceByConfigRuleResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeComplianceByConfigRule operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeComplianceByConfigRule operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeComplianceByConfigRule /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeComplianceByConfigRule">REST API Reference for DescribeComplianceByConfigRule Operation</seealso> public virtual IAsyncResult BeginDescribeComplianceByConfigRule(DescribeComplianceByConfigRuleRequest request, AsyncCallback callback, object state) { var marshaller = DescribeComplianceByConfigRuleRequestMarshaller.Instance; var unmarshaller = DescribeComplianceByConfigRuleResponseUnmarshaller.Instance; return BeginInvoke<DescribeComplianceByConfigRuleRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeComplianceByConfigRule operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeComplianceByConfigRule.</param> /// /// <returns>Returns a DescribeComplianceByConfigRuleResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeComplianceByConfigRule">REST API Reference for DescribeComplianceByConfigRule Operation</seealso> public virtual DescribeComplianceByConfigRuleResponse EndDescribeComplianceByConfigRule(IAsyncResult asyncResult) { return EndInvoke<DescribeComplianceByConfigRuleResponse>(asyncResult); } #endregion #region DescribeComplianceByResource /// <summary> /// Indicates whether the specified AWS resources are compliant. If a resource is noncompliant, /// this action returns the number of AWS Config rules that the resource does not comply /// with. /// /// /// <para> /// A resource is compliant if it complies with all the AWS Config rules that evaluate /// it. It is noncompliant if it does not comply with one or more of these rules. /// </para> /// /// <para> /// If AWS Config has no current evaluation results for the resource, it returns <code>INSUFFICIENT_DATA</code>. /// This result might indicate one of the following conditions about the rules that evaluate /// the resource: /// </para> /// <ul> <li> /// <para> /// AWS Config has never invoked an evaluation for the rule. To check whether it has, /// use the <code>DescribeConfigRuleEvaluationStatus</code> action to get the <code>LastSuccessfulInvocationTime</code> /// and <code>LastFailedInvocationTime</code>. /// </para> /// </li> <li> /// <para> /// The rule's AWS Lambda function is failing to send evaluation results to AWS Config. /// Verify that the role that you assigned to your configuration recorder includes the /// <code>config:PutEvaluations</code> permission. If the rule is a custom rule, verify /// that the AWS Lambda execution role includes the <code>config:PutEvaluations</code> /// permission. /// </para> /// </li> <li> /// <para> /// The rule's AWS Lambda function has returned <code>NOT_APPLICABLE</code> for all evaluation /// results. This can occur if the resources were deleted or removed from the rule's scope. /// </para> /// </li> </ul> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeComplianceByResource service method.</param> /// /// <returns>The response from the DescribeComplianceByResource service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidNextTokenException"> /// The specified next token is invalid. Specify the <code>nextToken</code> string that /// was returned in the previous response to get the next page of results. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeComplianceByResource">REST API Reference for DescribeComplianceByResource Operation</seealso> public virtual DescribeComplianceByResourceResponse DescribeComplianceByResource(DescribeComplianceByResourceRequest request) { var marshaller = DescribeComplianceByResourceRequestMarshaller.Instance; var unmarshaller = DescribeComplianceByResourceResponseUnmarshaller.Instance; return Invoke<DescribeComplianceByResourceRequest,DescribeComplianceByResourceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeComplianceByResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeComplianceByResource operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeComplianceByResource /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeComplianceByResource">REST API Reference for DescribeComplianceByResource Operation</seealso> public virtual IAsyncResult BeginDescribeComplianceByResource(DescribeComplianceByResourceRequest request, AsyncCallback callback, object state) { var marshaller = DescribeComplianceByResourceRequestMarshaller.Instance; var unmarshaller = DescribeComplianceByResourceResponseUnmarshaller.Instance; return BeginInvoke<DescribeComplianceByResourceRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeComplianceByResource operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeComplianceByResource.</param> /// /// <returns>Returns a DescribeComplianceByResourceResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeComplianceByResource">REST API Reference for DescribeComplianceByResource Operation</seealso> public virtual DescribeComplianceByResourceResponse EndDescribeComplianceByResource(IAsyncResult asyncResult) { return EndInvoke<DescribeComplianceByResourceResponse>(asyncResult); } #endregion #region DescribeConfigRuleEvaluationStatus /// <summary> /// Returns status information for each of your AWS managed Config rules. The status includes /// information such as the last time AWS Config invoked the rule, the last time AWS Config /// failed to invoke the rule, and the related error for the last failure. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeConfigRuleEvaluationStatus service method.</param> /// /// <returns>The response from the DescribeConfigRuleEvaluationStatus service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidNextTokenException"> /// The specified next token is invalid. Specify the <code>nextToken</code> string that /// was returned in the previous response to get the next page of results. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigRuleException"> /// One or more AWS Config rules in the request are invalid. Verify that the rule names /// are correct and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigRuleEvaluationStatus">REST API Reference for DescribeConfigRuleEvaluationStatus Operation</seealso> public virtual DescribeConfigRuleEvaluationStatusResponse DescribeConfigRuleEvaluationStatus(DescribeConfigRuleEvaluationStatusRequest request) { var marshaller = DescribeConfigRuleEvaluationStatusRequestMarshaller.Instance; var unmarshaller = DescribeConfigRuleEvaluationStatusResponseUnmarshaller.Instance; return Invoke<DescribeConfigRuleEvaluationStatusRequest,DescribeConfigRuleEvaluationStatusResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeConfigRuleEvaluationStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeConfigRuleEvaluationStatus operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeConfigRuleEvaluationStatus /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigRuleEvaluationStatus">REST API Reference for DescribeConfigRuleEvaluationStatus Operation</seealso> public virtual IAsyncResult BeginDescribeConfigRuleEvaluationStatus(DescribeConfigRuleEvaluationStatusRequest request, AsyncCallback callback, object state) { var marshaller = DescribeConfigRuleEvaluationStatusRequestMarshaller.Instance; var unmarshaller = DescribeConfigRuleEvaluationStatusResponseUnmarshaller.Instance; return BeginInvoke<DescribeConfigRuleEvaluationStatusRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeConfigRuleEvaluationStatus operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeConfigRuleEvaluationStatus.</param> /// /// <returns>Returns a DescribeConfigRuleEvaluationStatusResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigRuleEvaluationStatus">REST API Reference for DescribeConfigRuleEvaluationStatus Operation</seealso> public virtual DescribeConfigRuleEvaluationStatusResponse EndDescribeConfigRuleEvaluationStatus(IAsyncResult asyncResult) { return EndInvoke<DescribeConfigRuleEvaluationStatusResponse>(asyncResult); } #endregion #region DescribeConfigRules /// <summary> /// Returns details about your AWS Config rules. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeConfigRules service method.</param> /// /// <returns>The response from the DescribeConfigRules service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidNextTokenException"> /// The specified next token is invalid. Specify the <code>nextToken</code> string that /// was returned in the previous response to get the next page of results. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigRuleException"> /// One or more AWS Config rules in the request are invalid. Verify that the rule names /// are correct and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigRules">REST API Reference for DescribeConfigRules Operation</seealso> public virtual DescribeConfigRulesResponse DescribeConfigRules(DescribeConfigRulesRequest request) { var marshaller = DescribeConfigRulesRequestMarshaller.Instance; var unmarshaller = DescribeConfigRulesResponseUnmarshaller.Instance; return Invoke<DescribeConfigRulesRequest,DescribeConfigRulesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeConfigRules operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeConfigRules operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeConfigRules /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigRules">REST API Reference for DescribeConfigRules Operation</seealso> public virtual IAsyncResult BeginDescribeConfigRules(DescribeConfigRulesRequest request, AsyncCallback callback, object state) { var marshaller = DescribeConfigRulesRequestMarshaller.Instance; var unmarshaller = DescribeConfigRulesResponseUnmarshaller.Instance; return BeginInvoke<DescribeConfigRulesRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeConfigRules operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeConfigRules.</param> /// /// <returns>Returns a DescribeConfigRulesResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigRules">REST API Reference for DescribeConfigRules Operation</seealso> public virtual DescribeConfigRulesResponse EndDescribeConfigRules(IAsyncResult asyncResult) { return EndInvoke<DescribeConfigRulesResponse>(asyncResult); } #endregion #region DescribeConfigurationAggregators /// <summary> /// Returns the details of one or more configuration aggregators. If the configuration /// aggregator is not specified, this action returns the details for all the configuration /// aggregators associated with the account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeConfigurationAggregators service method.</param> /// /// <returns>The response from the DescribeConfigurationAggregators service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidLimitException"> /// The specified limit is outside the allowable range. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidNextTokenException"> /// The specified next token is invalid. Specify the <code>nextToken</code> string that /// was returned in the previous response to get the next page of results. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationAggregatorException"> /// You have specified a configuration aggregator that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigurationAggregators">REST API Reference for DescribeConfigurationAggregators Operation</seealso> public virtual DescribeConfigurationAggregatorsResponse DescribeConfigurationAggregators(DescribeConfigurationAggregatorsRequest request) { var marshaller = DescribeConfigurationAggregatorsRequestMarshaller.Instance; var unmarshaller = DescribeConfigurationAggregatorsResponseUnmarshaller.Instance; return Invoke<DescribeConfigurationAggregatorsRequest,DescribeConfigurationAggregatorsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeConfigurationAggregators operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeConfigurationAggregators operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeConfigurationAggregators /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigurationAggregators">REST API Reference for DescribeConfigurationAggregators Operation</seealso> public virtual IAsyncResult BeginDescribeConfigurationAggregators(DescribeConfigurationAggregatorsRequest request, AsyncCallback callback, object state) { var marshaller = DescribeConfigurationAggregatorsRequestMarshaller.Instance; var unmarshaller = DescribeConfigurationAggregatorsResponseUnmarshaller.Instance; return BeginInvoke<DescribeConfigurationAggregatorsRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeConfigurationAggregators operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeConfigurationAggregators.</param> /// /// <returns>Returns a DescribeConfigurationAggregatorsResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigurationAggregators">REST API Reference for DescribeConfigurationAggregators Operation</seealso> public virtual DescribeConfigurationAggregatorsResponse EndDescribeConfigurationAggregators(IAsyncResult asyncResult) { return EndInvoke<DescribeConfigurationAggregatorsResponse>(asyncResult); } #endregion #region DescribeConfigurationAggregatorSourcesStatus /// <summary> /// Returns status information for sources within an aggregator. The status includes information /// about the last time AWS Config aggregated data from source accounts or AWS Config /// failed to aggregate data from source accounts with the related error code or message. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeConfigurationAggregatorSourcesStatus service method.</param> /// /// <returns>The response from the DescribeConfigurationAggregatorSourcesStatus service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidLimitException"> /// The specified limit is outside the allowable range. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidNextTokenException"> /// The specified next token is invalid. Specify the <code>nextToken</code> string that /// was returned in the previous response to get the next page of results. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationAggregatorException"> /// You have specified a configuration aggregator that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigurationAggregatorSourcesStatus">REST API Reference for DescribeConfigurationAggregatorSourcesStatus Operation</seealso> public virtual DescribeConfigurationAggregatorSourcesStatusResponse DescribeConfigurationAggregatorSourcesStatus(DescribeConfigurationAggregatorSourcesStatusRequest request) { var marshaller = DescribeConfigurationAggregatorSourcesStatusRequestMarshaller.Instance; var unmarshaller = DescribeConfigurationAggregatorSourcesStatusResponseUnmarshaller.Instance; return Invoke<DescribeConfigurationAggregatorSourcesStatusRequest,DescribeConfigurationAggregatorSourcesStatusResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeConfigurationAggregatorSourcesStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeConfigurationAggregatorSourcesStatus operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeConfigurationAggregatorSourcesStatus /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigurationAggregatorSourcesStatus">REST API Reference for DescribeConfigurationAggregatorSourcesStatus Operation</seealso> public virtual IAsyncResult BeginDescribeConfigurationAggregatorSourcesStatus(DescribeConfigurationAggregatorSourcesStatusRequest request, AsyncCallback callback, object state) { var marshaller = DescribeConfigurationAggregatorSourcesStatusRequestMarshaller.Instance; var unmarshaller = DescribeConfigurationAggregatorSourcesStatusResponseUnmarshaller.Instance; return BeginInvoke<DescribeConfigurationAggregatorSourcesStatusRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeConfigurationAggregatorSourcesStatus operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeConfigurationAggregatorSourcesStatus.</param> /// /// <returns>Returns a DescribeConfigurationAggregatorSourcesStatusResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigurationAggregatorSourcesStatus">REST API Reference for DescribeConfigurationAggregatorSourcesStatus Operation</seealso> public virtual DescribeConfigurationAggregatorSourcesStatusResponse EndDescribeConfigurationAggregatorSourcesStatus(IAsyncResult asyncResult) { return EndInvoke<DescribeConfigurationAggregatorSourcesStatusResponse>(asyncResult); } #endregion #region DescribeConfigurationRecorders /// <summary> /// Returns the details for the specified configuration recorders. If the configuration /// recorder is not specified, this action returns the details for all configuration recorders /// associated with the account. /// /// <note> /// <para> /// Currently, you can specify only one configuration recorder per region in your account. /// </para> /// </note> /// </summary> /// /// <returns>The response from the DescribeConfigurationRecorders service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationRecorderException"> /// You have specified a configuration recorder that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigurationRecorders">REST API Reference for DescribeConfigurationRecorders Operation</seealso> public virtual DescribeConfigurationRecordersResponse DescribeConfigurationRecorders() { return DescribeConfigurationRecorders(new DescribeConfigurationRecordersRequest()); } /// <summary> /// Returns the details for the specified configuration recorders. If the configuration /// recorder is not specified, this action returns the details for all configuration recorders /// associated with the account. /// /// <note> /// <para> /// Currently, you can specify only one configuration recorder per region in your account. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeConfigurationRecorders service method.</param> /// /// <returns>The response from the DescribeConfigurationRecorders service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationRecorderException"> /// You have specified a configuration recorder that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigurationRecorders">REST API Reference for DescribeConfigurationRecorders Operation</seealso> public virtual DescribeConfigurationRecordersResponse DescribeConfigurationRecorders(DescribeConfigurationRecordersRequest request) { var marshaller = DescribeConfigurationRecordersRequestMarshaller.Instance; var unmarshaller = DescribeConfigurationRecordersResponseUnmarshaller.Instance; return Invoke<DescribeConfigurationRecordersRequest,DescribeConfigurationRecordersResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeConfigurationRecorders operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeConfigurationRecorders operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeConfigurationRecorders /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigurationRecorders">REST API Reference for DescribeConfigurationRecorders Operation</seealso> public virtual IAsyncResult BeginDescribeConfigurationRecorders(DescribeConfigurationRecordersRequest request, AsyncCallback callback, object state) { var marshaller = DescribeConfigurationRecordersRequestMarshaller.Instance; var unmarshaller = DescribeConfigurationRecordersResponseUnmarshaller.Instance; return BeginInvoke<DescribeConfigurationRecordersRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeConfigurationRecorders operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeConfigurationRecorders.</param> /// /// <returns>Returns a DescribeConfigurationRecordersResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigurationRecorders">REST API Reference for DescribeConfigurationRecorders Operation</seealso> public virtual DescribeConfigurationRecordersResponse EndDescribeConfigurationRecorders(IAsyncResult asyncResult) { return EndInvoke<DescribeConfigurationRecordersResponse>(asyncResult); } #endregion #region DescribeConfigurationRecorderStatus /// <summary> /// Returns the current status of the specified configuration recorder. If a configuration /// recorder is not specified, this action returns the status of all configuration recorders /// associated with the account. /// /// <note> /// <para> /// Currently, you can specify only one configuration recorder per region in your account. /// </para> /// </note> /// </summary> /// /// <returns>The response from the DescribeConfigurationRecorderStatus service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationRecorderException"> /// You have specified a configuration recorder that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigurationRecorderStatus">REST API Reference for DescribeConfigurationRecorderStatus Operation</seealso> public virtual DescribeConfigurationRecorderStatusResponse DescribeConfigurationRecorderStatus() { return DescribeConfigurationRecorderStatus(new DescribeConfigurationRecorderStatusRequest()); } /// <summary> /// Returns the current status of the specified configuration recorder. If a configuration /// recorder is not specified, this action returns the status of all configuration recorders /// associated with the account. /// /// <note> /// <para> /// Currently, you can specify only one configuration recorder per region in your account. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeConfigurationRecorderStatus service method.</param> /// /// <returns>The response from the DescribeConfigurationRecorderStatus service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationRecorderException"> /// You have specified a configuration recorder that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigurationRecorderStatus">REST API Reference for DescribeConfigurationRecorderStatus Operation</seealso> public virtual DescribeConfigurationRecorderStatusResponse DescribeConfigurationRecorderStatus(DescribeConfigurationRecorderStatusRequest request) { var marshaller = DescribeConfigurationRecorderStatusRequestMarshaller.Instance; var unmarshaller = DescribeConfigurationRecorderStatusResponseUnmarshaller.Instance; return Invoke<DescribeConfigurationRecorderStatusRequest,DescribeConfigurationRecorderStatusResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeConfigurationRecorderStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeConfigurationRecorderStatus operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeConfigurationRecorderStatus /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigurationRecorderStatus">REST API Reference for DescribeConfigurationRecorderStatus Operation</seealso> public virtual IAsyncResult BeginDescribeConfigurationRecorderStatus(DescribeConfigurationRecorderStatusRequest request, AsyncCallback callback, object state) { var marshaller = DescribeConfigurationRecorderStatusRequestMarshaller.Instance; var unmarshaller = DescribeConfigurationRecorderStatusResponseUnmarshaller.Instance; return BeginInvoke<DescribeConfigurationRecorderStatusRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeConfigurationRecorderStatus operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeConfigurationRecorderStatus.</param> /// /// <returns>Returns a DescribeConfigurationRecorderStatusResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigurationRecorderStatus">REST API Reference for DescribeConfigurationRecorderStatus Operation</seealso> public virtual DescribeConfigurationRecorderStatusResponse EndDescribeConfigurationRecorderStatus(IAsyncResult asyncResult) { return EndInvoke<DescribeConfigurationRecorderStatusResponse>(asyncResult); } #endregion #region DescribeDeliveryChannels /// <summary> /// Returns details about the specified delivery channel. If a delivery channel is not /// specified, this action returns the details of all delivery channels associated with /// the account. /// /// <note> /// <para> /// Currently, you can specify only one delivery channel per region in your account. /// </para> /// </note> /// </summary> /// /// <returns>The response from the DescribeDeliveryChannels service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchDeliveryChannelException"> /// You have specified a delivery channel that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeDeliveryChannels">REST API Reference for DescribeDeliveryChannels Operation</seealso> public virtual DescribeDeliveryChannelsResponse DescribeDeliveryChannels() { return DescribeDeliveryChannels(new DescribeDeliveryChannelsRequest()); } /// <summary> /// Returns details about the specified delivery channel. If a delivery channel is not /// specified, this action returns the details of all delivery channels associated with /// the account. /// /// <note> /// <para> /// Currently, you can specify only one delivery channel per region in your account. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeDeliveryChannels service method.</param> /// /// <returns>The response from the DescribeDeliveryChannels service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchDeliveryChannelException"> /// You have specified a delivery channel that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeDeliveryChannels">REST API Reference for DescribeDeliveryChannels Operation</seealso> public virtual DescribeDeliveryChannelsResponse DescribeDeliveryChannels(DescribeDeliveryChannelsRequest request) { var marshaller = DescribeDeliveryChannelsRequestMarshaller.Instance; var unmarshaller = DescribeDeliveryChannelsResponseUnmarshaller.Instance; return Invoke<DescribeDeliveryChannelsRequest,DescribeDeliveryChannelsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeDeliveryChannels operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeDeliveryChannels operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeDeliveryChannels /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeDeliveryChannels">REST API Reference for DescribeDeliveryChannels Operation</seealso> public virtual IAsyncResult BeginDescribeDeliveryChannels(DescribeDeliveryChannelsRequest request, AsyncCallback callback, object state) { var marshaller = DescribeDeliveryChannelsRequestMarshaller.Instance; var unmarshaller = DescribeDeliveryChannelsResponseUnmarshaller.Instance; return BeginInvoke<DescribeDeliveryChannelsRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeDeliveryChannels operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeDeliveryChannels.</param> /// /// <returns>Returns a DescribeDeliveryChannelsResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeDeliveryChannels">REST API Reference for DescribeDeliveryChannels Operation</seealso> public virtual DescribeDeliveryChannelsResponse EndDescribeDeliveryChannels(IAsyncResult asyncResult) { return EndInvoke<DescribeDeliveryChannelsResponse>(asyncResult); } #endregion #region DescribeDeliveryChannelStatus /// <summary> /// Returns the current status of the specified delivery channel. If a delivery channel /// is not specified, this action returns the current status of all delivery channels /// associated with the account. /// /// <note> /// <para> /// Currently, you can specify only one delivery channel per region in your account. /// </para> /// </note> /// </summary> /// /// <returns>The response from the DescribeDeliveryChannelStatus service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchDeliveryChannelException"> /// You have specified a delivery channel that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeDeliveryChannelStatus">REST API Reference for DescribeDeliveryChannelStatus Operation</seealso> public virtual DescribeDeliveryChannelStatusResponse DescribeDeliveryChannelStatus() { return DescribeDeliveryChannelStatus(new DescribeDeliveryChannelStatusRequest()); } /// <summary> /// Returns the current status of the specified delivery channel. If a delivery channel /// is not specified, this action returns the current status of all delivery channels /// associated with the account. /// /// <note> /// <para> /// Currently, you can specify only one delivery channel per region in your account. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeDeliveryChannelStatus service method.</param> /// /// <returns>The response from the DescribeDeliveryChannelStatus service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchDeliveryChannelException"> /// You have specified a delivery channel that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeDeliveryChannelStatus">REST API Reference for DescribeDeliveryChannelStatus Operation</seealso> public virtual DescribeDeliveryChannelStatusResponse DescribeDeliveryChannelStatus(DescribeDeliveryChannelStatusRequest request) { var marshaller = DescribeDeliveryChannelStatusRequestMarshaller.Instance; var unmarshaller = DescribeDeliveryChannelStatusResponseUnmarshaller.Instance; return Invoke<DescribeDeliveryChannelStatusRequest,DescribeDeliveryChannelStatusResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeDeliveryChannelStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeDeliveryChannelStatus operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeDeliveryChannelStatus /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeDeliveryChannelStatus">REST API Reference for DescribeDeliveryChannelStatus Operation</seealso> public virtual IAsyncResult BeginDescribeDeliveryChannelStatus(DescribeDeliveryChannelStatusRequest request, AsyncCallback callback, object state) { var marshaller = DescribeDeliveryChannelStatusRequestMarshaller.Instance; var unmarshaller = DescribeDeliveryChannelStatusResponseUnmarshaller.Instance; return BeginInvoke<DescribeDeliveryChannelStatusRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeDeliveryChannelStatus operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeDeliveryChannelStatus.</param> /// /// <returns>Returns a DescribeDeliveryChannelStatusResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeDeliveryChannelStatus">REST API Reference for DescribeDeliveryChannelStatus Operation</seealso> public virtual DescribeDeliveryChannelStatusResponse EndDescribeDeliveryChannelStatus(IAsyncResult asyncResult) { return EndInvoke<DescribeDeliveryChannelStatusResponse>(asyncResult); } #endregion #region DescribePendingAggregationRequests /// <summary> /// Returns a list of all pending aggregation requests. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribePendingAggregationRequests service method.</param> /// /// <returns>The response from the DescribePendingAggregationRequests service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidLimitException"> /// The specified limit is outside the allowable range. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidNextTokenException"> /// The specified next token is invalid. Specify the <code>nextToken</code> string that /// was returned in the previous response to get the next page of results. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribePendingAggregationRequests">REST API Reference for DescribePendingAggregationRequests Operation</seealso> public virtual DescribePendingAggregationRequestsResponse DescribePendingAggregationRequests(DescribePendingAggregationRequestsRequest request) { var marshaller = DescribePendingAggregationRequestsRequestMarshaller.Instance; var unmarshaller = DescribePendingAggregationRequestsResponseUnmarshaller.Instance; return Invoke<DescribePendingAggregationRequestsRequest,DescribePendingAggregationRequestsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribePendingAggregationRequests operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribePendingAggregationRequests operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribePendingAggregationRequests /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribePendingAggregationRequests">REST API Reference for DescribePendingAggregationRequests Operation</seealso> public virtual IAsyncResult BeginDescribePendingAggregationRequests(DescribePendingAggregationRequestsRequest request, AsyncCallback callback, object state) { var marshaller = DescribePendingAggregationRequestsRequestMarshaller.Instance; var unmarshaller = DescribePendingAggregationRequestsResponseUnmarshaller.Instance; return BeginInvoke<DescribePendingAggregationRequestsRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribePendingAggregationRequests operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribePendingAggregationRequests.</param> /// /// <returns>Returns a DescribePendingAggregationRequestsResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribePendingAggregationRequests">REST API Reference for DescribePendingAggregationRequests Operation</seealso> public virtual DescribePendingAggregationRequestsResponse EndDescribePendingAggregationRequests(IAsyncResult asyncResult) { return EndInvoke<DescribePendingAggregationRequestsResponse>(asyncResult); } #endregion #region DescribeRetentionConfigurations /// <summary> /// Returns the details of one or more retention configurations. If the retention configuration /// name is not specified, this action returns the details for all the retention configurations /// for that account. /// /// <note> /// <para> /// Currently, AWS Config supports only one retention configuration per region in your /// account. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeRetentionConfigurations service method.</param> /// /// <returns>The response from the DescribeRetentionConfigurations service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidNextTokenException"> /// The specified next token is invalid. Specify the <code>nextToken</code> string that /// was returned in the previous response to get the next page of results. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchRetentionConfigurationException"> /// You have specified a retention configuration that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeRetentionConfigurations">REST API Reference for DescribeRetentionConfigurations Operation</seealso> public virtual DescribeRetentionConfigurationsResponse DescribeRetentionConfigurations(DescribeRetentionConfigurationsRequest request) { var marshaller = DescribeRetentionConfigurationsRequestMarshaller.Instance; var unmarshaller = DescribeRetentionConfigurationsResponseUnmarshaller.Instance; return Invoke<DescribeRetentionConfigurationsRequest,DescribeRetentionConfigurationsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeRetentionConfigurations operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeRetentionConfigurations operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeRetentionConfigurations /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeRetentionConfigurations">REST API Reference for DescribeRetentionConfigurations Operation</seealso> public virtual IAsyncResult BeginDescribeRetentionConfigurations(DescribeRetentionConfigurationsRequest request, AsyncCallback callback, object state) { var marshaller = DescribeRetentionConfigurationsRequestMarshaller.Instance; var unmarshaller = DescribeRetentionConfigurationsResponseUnmarshaller.Instance; return BeginInvoke<DescribeRetentionConfigurationsRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeRetentionConfigurations operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeRetentionConfigurations.</param> /// /// <returns>Returns a DescribeRetentionConfigurationsResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeRetentionConfigurations">REST API Reference for DescribeRetentionConfigurations Operation</seealso> public virtual DescribeRetentionConfigurationsResponse EndDescribeRetentionConfigurations(IAsyncResult asyncResult) { return EndInvoke<DescribeRetentionConfigurationsResponse>(asyncResult); } #endregion #region GetAggregateComplianceDetailsByConfigRule /// <summary> /// Returns the evaluation results for the specified AWS Config rule for a specific resource /// in a rule. The results indicate which AWS resources were evaluated by the rule, when /// each resource was last evaluated, and whether each resource complies with the rule. /// /// /// <note> /// <para> /// The results can return an empty result page. But if you have a nextToken, the results /// are displayed on the next page. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetAggregateComplianceDetailsByConfigRule service method.</param> /// /// <returns>The response from the GetAggregateComplianceDetailsByConfigRule service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidLimitException"> /// The specified limit is outside the allowable range. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidNextTokenException"> /// The specified next token is invalid. Specify the <code>nextToken</code> string that /// was returned in the previous response to get the next page of results. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationAggregatorException"> /// You have specified a configuration aggregator that does not exist. /// </exception> /// <exception cref="Amazon.ConfigService.Model.ValidationException"> /// The requested action is not valid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetAggregateComplianceDetailsByConfigRule">REST API Reference for GetAggregateComplianceDetailsByConfigRule Operation</seealso> public virtual GetAggregateComplianceDetailsByConfigRuleResponse GetAggregateComplianceDetailsByConfigRule(GetAggregateComplianceDetailsByConfigRuleRequest request) { var marshaller = GetAggregateComplianceDetailsByConfigRuleRequestMarshaller.Instance; var unmarshaller = GetAggregateComplianceDetailsByConfigRuleResponseUnmarshaller.Instance; return Invoke<GetAggregateComplianceDetailsByConfigRuleRequest,GetAggregateComplianceDetailsByConfigRuleResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetAggregateComplianceDetailsByConfigRule operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetAggregateComplianceDetailsByConfigRule operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetAggregateComplianceDetailsByConfigRule /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetAggregateComplianceDetailsByConfigRule">REST API Reference for GetAggregateComplianceDetailsByConfigRule Operation</seealso> public virtual IAsyncResult BeginGetAggregateComplianceDetailsByConfigRule(GetAggregateComplianceDetailsByConfigRuleRequest request, AsyncCallback callback, object state) { var marshaller = GetAggregateComplianceDetailsByConfigRuleRequestMarshaller.Instance; var unmarshaller = GetAggregateComplianceDetailsByConfigRuleResponseUnmarshaller.Instance; return BeginInvoke<GetAggregateComplianceDetailsByConfigRuleRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetAggregateComplianceDetailsByConfigRule operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetAggregateComplianceDetailsByConfigRule.</param> /// /// <returns>Returns a GetAggregateComplianceDetailsByConfigRuleResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetAggregateComplianceDetailsByConfigRule">REST API Reference for GetAggregateComplianceDetailsByConfigRule Operation</seealso> public virtual GetAggregateComplianceDetailsByConfigRuleResponse EndGetAggregateComplianceDetailsByConfigRule(IAsyncResult asyncResult) { return EndInvoke<GetAggregateComplianceDetailsByConfigRuleResponse>(asyncResult); } #endregion #region GetAggregateConfigRuleComplianceSummary /// <summary> /// Returns the number of compliant and noncompliant rules for one or more accounts and /// regions in an aggregator. /// /// <note> /// <para> /// The results can return an empty result page, but if you have a nextToken, the results /// are displayed on the next page. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetAggregateConfigRuleComplianceSummary service method.</param> /// /// <returns>The response from the GetAggregateConfigRuleComplianceSummary service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidLimitException"> /// The specified limit is outside the allowable range. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidNextTokenException"> /// The specified next token is invalid. Specify the <code>nextToken</code> string that /// was returned in the previous response to get the next page of results. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationAggregatorException"> /// You have specified a configuration aggregator that does not exist. /// </exception> /// <exception cref="Amazon.ConfigService.Model.ValidationException"> /// The requested action is not valid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetAggregateConfigRuleComplianceSummary">REST API Reference for GetAggregateConfigRuleComplianceSummary Operation</seealso> public virtual GetAggregateConfigRuleComplianceSummaryResponse GetAggregateConfigRuleComplianceSummary(GetAggregateConfigRuleComplianceSummaryRequest request) { var marshaller = GetAggregateConfigRuleComplianceSummaryRequestMarshaller.Instance; var unmarshaller = GetAggregateConfigRuleComplianceSummaryResponseUnmarshaller.Instance; return Invoke<GetAggregateConfigRuleComplianceSummaryRequest,GetAggregateConfigRuleComplianceSummaryResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetAggregateConfigRuleComplianceSummary operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetAggregateConfigRuleComplianceSummary operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetAggregateConfigRuleComplianceSummary /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetAggregateConfigRuleComplianceSummary">REST API Reference for GetAggregateConfigRuleComplianceSummary Operation</seealso> public virtual IAsyncResult BeginGetAggregateConfigRuleComplianceSummary(GetAggregateConfigRuleComplianceSummaryRequest request, AsyncCallback callback, object state) { var marshaller = GetAggregateConfigRuleComplianceSummaryRequestMarshaller.Instance; var unmarshaller = GetAggregateConfigRuleComplianceSummaryResponseUnmarshaller.Instance; return BeginInvoke<GetAggregateConfigRuleComplianceSummaryRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetAggregateConfigRuleComplianceSummary operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetAggregateConfigRuleComplianceSummary.</param> /// /// <returns>Returns a GetAggregateConfigRuleComplianceSummaryResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetAggregateConfigRuleComplianceSummary">REST API Reference for GetAggregateConfigRuleComplianceSummary Operation</seealso> public virtual GetAggregateConfigRuleComplianceSummaryResponse EndGetAggregateConfigRuleComplianceSummary(IAsyncResult asyncResult) { return EndInvoke<GetAggregateConfigRuleComplianceSummaryResponse>(asyncResult); } #endregion #region GetComplianceDetailsByConfigRule /// <summary> /// Returns the evaluation results for the specified AWS Config rule. The results indicate /// which AWS resources were evaluated by the rule, when each resource was last evaluated, /// and whether each resource complies with the rule. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetComplianceDetailsByConfigRule service method.</param> /// /// <returns>The response from the GetComplianceDetailsByConfigRule service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidNextTokenException"> /// The specified next token is invalid. Specify the <code>nextToken</code> string that /// was returned in the previous response to get the next page of results. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigRuleException"> /// One or more AWS Config rules in the request are invalid. Verify that the rule names /// are correct and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetComplianceDetailsByConfigRule">REST API Reference for GetComplianceDetailsByConfigRule Operation</seealso> public virtual GetComplianceDetailsByConfigRuleResponse GetComplianceDetailsByConfigRule(GetComplianceDetailsByConfigRuleRequest request) { var marshaller = GetComplianceDetailsByConfigRuleRequestMarshaller.Instance; var unmarshaller = GetComplianceDetailsByConfigRuleResponseUnmarshaller.Instance; return Invoke<GetComplianceDetailsByConfigRuleRequest,GetComplianceDetailsByConfigRuleResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetComplianceDetailsByConfigRule operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetComplianceDetailsByConfigRule operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetComplianceDetailsByConfigRule /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetComplianceDetailsByConfigRule">REST API Reference for GetComplianceDetailsByConfigRule Operation</seealso> public virtual IAsyncResult BeginGetComplianceDetailsByConfigRule(GetComplianceDetailsByConfigRuleRequest request, AsyncCallback callback, object state) { var marshaller = GetComplianceDetailsByConfigRuleRequestMarshaller.Instance; var unmarshaller = GetComplianceDetailsByConfigRuleResponseUnmarshaller.Instance; return BeginInvoke<GetComplianceDetailsByConfigRuleRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetComplianceDetailsByConfigRule operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetComplianceDetailsByConfigRule.</param> /// /// <returns>Returns a GetComplianceDetailsByConfigRuleResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetComplianceDetailsByConfigRule">REST API Reference for GetComplianceDetailsByConfigRule Operation</seealso> public virtual GetComplianceDetailsByConfigRuleResponse EndGetComplianceDetailsByConfigRule(IAsyncResult asyncResult) { return EndInvoke<GetComplianceDetailsByConfigRuleResponse>(asyncResult); } #endregion #region GetComplianceDetailsByResource /// <summary> /// Returns the evaluation results for the specified AWS resource. The results indicate /// which AWS Config rules were used to evaluate the resource, when each rule was last /// used, and whether the resource complies with each rule. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetComplianceDetailsByResource service method.</param> /// /// <returns>The response from the GetComplianceDetailsByResource service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetComplianceDetailsByResource">REST API Reference for GetComplianceDetailsByResource Operation</seealso> public virtual GetComplianceDetailsByResourceResponse GetComplianceDetailsByResource(GetComplianceDetailsByResourceRequest request) { var marshaller = GetComplianceDetailsByResourceRequestMarshaller.Instance; var unmarshaller = GetComplianceDetailsByResourceResponseUnmarshaller.Instance; return Invoke<GetComplianceDetailsByResourceRequest,GetComplianceDetailsByResourceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetComplianceDetailsByResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetComplianceDetailsByResource operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetComplianceDetailsByResource /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetComplianceDetailsByResource">REST API Reference for GetComplianceDetailsByResource Operation</seealso> public virtual IAsyncResult BeginGetComplianceDetailsByResource(GetComplianceDetailsByResourceRequest request, AsyncCallback callback, object state) { var marshaller = GetComplianceDetailsByResourceRequestMarshaller.Instance; var unmarshaller = GetComplianceDetailsByResourceResponseUnmarshaller.Instance; return BeginInvoke<GetComplianceDetailsByResourceRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetComplianceDetailsByResource operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetComplianceDetailsByResource.</param> /// /// <returns>Returns a GetComplianceDetailsByResourceResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetComplianceDetailsByResource">REST API Reference for GetComplianceDetailsByResource Operation</seealso> public virtual GetComplianceDetailsByResourceResponse EndGetComplianceDetailsByResource(IAsyncResult asyncResult) { return EndInvoke<GetComplianceDetailsByResourceResponse>(asyncResult); } #endregion #region GetComplianceSummaryByConfigRule /// <summary> /// Returns the number of AWS Config rules that are compliant and noncompliant, up to /// a maximum of 25 for each. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetComplianceSummaryByConfigRule service method.</param> /// /// <returns>The response from the GetComplianceSummaryByConfigRule service method, as returned by ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetComplianceSummaryByConfigRule">REST API Reference for GetComplianceSummaryByConfigRule Operation</seealso> public virtual GetComplianceSummaryByConfigRuleResponse GetComplianceSummaryByConfigRule(GetComplianceSummaryByConfigRuleRequest request) { var marshaller = GetComplianceSummaryByConfigRuleRequestMarshaller.Instance; var unmarshaller = GetComplianceSummaryByConfigRuleResponseUnmarshaller.Instance; return Invoke<GetComplianceSummaryByConfigRuleRequest,GetComplianceSummaryByConfigRuleResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetComplianceSummaryByConfigRule operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetComplianceSummaryByConfigRule operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetComplianceSummaryByConfigRule /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetComplianceSummaryByConfigRule">REST API Reference for GetComplianceSummaryByConfigRule Operation</seealso> public virtual IAsyncResult BeginGetComplianceSummaryByConfigRule(GetComplianceSummaryByConfigRuleRequest request, AsyncCallback callback, object state) { var marshaller = GetComplianceSummaryByConfigRuleRequestMarshaller.Instance; var unmarshaller = GetComplianceSummaryByConfigRuleResponseUnmarshaller.Instance; return BeginInvoke<GetComplianceSummaryByConfigRuleRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetComplianceSummaryByConfigRule operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetComplianceSummaryByConfigRule.</param> /// /// <returns>Returns a GetComplianceSummaryByConfigRuleResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetComplianceSummaryByConfigRule">REST API Reference for GetComplianceSummaryByConfigRule Operation</seealso> public virtual GetComplianceSummaryByConfigRuleResponse EndGetComplianceSummaryByConfigRule(IAsyncResult asyncResult) { return EndInvoke<GetComplianceSummaryByConfigRuleResponse>(asyncResult); } #endregion #region GetComplianceSummaryByResourceType /// <summary> /// Returns the number of resources that are compliant and the number that are noncompliant. /// You can specify one or more resource types to get these numbers for each resource /// type. The maximum number returned is 100. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetComplianceSummaryByResourceType service method.</param> /// /// <returns>The response from the GetComplianceSummaryByResourceType service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetComplianceSummaryByResourceType">REST API Reference for GetComplianceSummaryByResourceType Operation</seealso> public virtual GetComplianceSummaryByResourceTypeResponse GetComplianceSummaryByResourceType(GetComplianceSummaryByResourceTypeRequest request) { var marshaller = GetComplianceSummaryByResourceTypeRequestMarshaller.Instance; var unmarshaller = GetComplianceSummaryByResourceTypeResponseUnmarshaller.Instance; return Invoke<GetComplianceSummaryByResourceTypeRequest,GetComplianceSummaryByResourceTypeResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetComplianceSummaryByResourceType operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetComplianceSummaryByResourceType operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetComplianceSummaryByResourceType /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetComplianceSummaryByResourceType">REST API Reference for GetComplianceSummaryByResourceType Operation</seealso> public virtual IAsyncResult BeginGetComplianceSummaryByResourceType(GetComplianceSummaryByResourceTypeRequest request, AsyncCallback callback, object state) { var marshaller = GetComplianceSummaryByResourceTypeRequestMarshaller.Instance; var unmarshaller = GetComplianceSummaryByResourceTypeResponseUnmarshaller.Instance; return BeginInvoke<GetComplianceSummaryByResourceTypeRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetComplianceSummaryByResourceType operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetComplianceSummaryByResourceType.</param> /// /// <returns>Returns a GetComplianceSummaryByResourceTypeResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetComplianceSummaryByResourceType">REST API Reference for GetComplianceSummaryByResourceType Operation</seealso> public virtual GetComplianceSummaryByResourceTypeResponse EndGetComplianceSummaryByResourceType(IAsyncResult asyncResult) { return EndInvoke<GetComplianceSummaryByResourceTypeResponse>(asyncResult); } #endregion #region GetDiscoveredResourceCounts /// <summary> /// Returns the resource types, the number of each resource type, and the total number /// of resources that AWS Config is recording in this region for your AWS account. /// /// <p class="title"> <b>Example</b> /// </para> /// <ol> <li> /// <para> /// AWS Config is recording three resource types in the US East (Ohio) Region for your /// account: 25 EC2 instances, 20 IAM users, and 15 S3 buckets. /// </para> /// </li> <li> /// <para> /// You make a call to the <code>GetDiscoveredResourceCounts</code> action and specify /// that you want all resource types. /// </para> /// </li> <li> /// <para> /// AWS Config returns the following: /// </para> /// <ul> <li> /// <para> /// The resource types (EC2 instances, IAM users, and S3 buckets). /// </para> /// </li> <li> /// <para> /// The number of each resource type (25, 20, and 15). /// </para> /// </li> <li> /// <para> /// The total number of all resources (60). /// </para> /// </li> </ul> </li> </ol> /// <para> /// The response is paginated. By default, AWS Config lists 100 <a>ResourceCount</a> objects /// on each page. You can customize this number with the <code>limit</code> parameter. /// The response includes a <code>nextToken</code> string. To get the next page of results, /// run the request again and specify the string for the <code>nextToken</code> parameter. /// </para> /// <note> /// <para> /// If you make a call to the <a>GetDiscoveredResourceCounts</a> action, you might not /// immediately receive resource counts in the following situations: /// </para> /// <ul> <li> /// <para> /// You are a new AWS Config customer. /// </para> /// </li> <li> /// <para> /// You just enabled resource recording. /// </para> /// </li> </ul> /// <para> /// It might take a few minutes for AWS Config to record and count your resources. Wait /// a few minutes and then retry the <a>GetDiscoveredResourceCounts</a> action. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetDiscoveredResourceCounts service method.</param> /// /// <returns>The response from the GetDiscoveredResourceCounts service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidLimitException"> /// The specified limit is outside the allowable range. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidNextTokenException"> /// The specified next token is invalid. Specify the <code>nextToken</code> string that /// was returned in the previous response to get the next page of results. /// </exception> /// <exception cref="Amazon.ConfigService.Model.ValidationException"> /// The requested action is not valid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetDiscoveredResourceCounts">REST API Reference for GetDiscoveredResourceCounts Operation</seealso> public virtual GetDiscoveredResourceCountsResponse GetDiscoveredResourceCounts(GetDiscoveredResourceCountsRequest request) { var marshaller = GetDiscoveredResourceCountsRequestMarshaller.Instance; var unmarshaller = GetDiscoveredResourceCountsResponseUnmarshaller.Instance; return Invoke<GetDiscoveredResourceCountsRequest,GetDiscoveredResourceCountsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetDiscoveredResourceCounts operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetDiscoveredResourceCounts operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetDiscoveredResourceCounts /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetDiscoveredResourceCounts">REST API Reference for GetDiscoveredResourceCounts Operation</seealso> public virtual IAsyncResult BeginGetDiscoveredResourceCounts(GetDiscoveredResourceCountsRequest request, AsyncCallback callback, object state) { var marshaller = GetDiscoveredResourceCountsRequestMarshaller.Instance; var unmarshaller = GetDiscoveredResourceCountsResponseUnmarshaller.Instance; return BeginInvoke<GetDiscoveredResourceCountsRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetDiscoveredResourceCounts operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetDiscoveredResourceCounts.</param> /// /// <returns>Returns a GetDiscoveredResourceCountsResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetDiscoveredResourceCounts">REST API Reference for GetDiscoveredResourceCounts Operation</seealso> public virtual GetDiscoveredResourceCountsResponse EndGetDiscoveredResourceCounts(IAsyncResult asyncResult) { return EndInvoke<GetDiscoveredResourceCountsResponse>(asyncResult); } #endregion #region GetResourceConfigHistory /// <summary> /// Returns a list of configuration items for the specified resource. The list contains /// details about each state of the resource during the specified time interval. If you /// specified a retention period to retain your <code>ConfigurationItems</code> between /// a minimum of 30 days and a maximum of 7 years (2557 days), AWS Config returns the /// <code>ConfigurationItems</code> for the specified retention period. /// /// /// <para> /// The response is paginated. By default, AWS Config returns a limit of 10 configuration /// items per page. You can customize this number with the <code>limit</code> parameter. /// The response includes a <code>nextToken</code> string. To get the next page of results, /// run the request again and specify the string for the <code>nextToken</code> parameter. /// </para> /// <note> /// <para> /// Each call to the API is limited to span a duration of seven days. It is likely that /// the number of records returned is smaller than the specified <code>limit</code>. In /// such cases, you can make another call, using the <code>nextToken</code>. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetResourceConfigHistory service method.</param> /// /// <returns>The response from the GetResourceConfigHistory service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidLimitException"> /// The specified limit is outside the allowable range. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidNextTokenException"> /// The specified next token is invalid. Specify the <code>nextToken</code> string that /// was returned in the previous response to get the next page of results. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidTimeRangeException"> /// The specified time range is not valid. The earlier time is not chronologically before /// the later time. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoAvailableConfigurationRecorderException"> /// There are no configuration recorders available to provide the role needed to describe /// your resources. Create a configuration recorder. /// </exception> /// <exception cref="Amazon.ConfigService.Model.ResourceNotDiscoveredException"> /// You have specified a resource that is either unknown or has not been discovered. /// </exception> /// <exception cref="Amazon.ConfigService.Model.ValidationException"> /// The requested action is not valid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetResourceConfigHistory">REST API Reference for GetResourceConfigHistory Operation</seealso> public virtual GetResourceConfigHistoryResponse GetResourceConfigHistory(GetResourceConfigHistoryRequest request) { var marshaller = GetResourceConfigHistoryRequestMarshaller.Instance; var unmarshaller = GetResourceConfigHistoryResponseUnmarshaller.Instance; return Invoke<GetResourceConfigHistoryRequest,GetResourceConfigHistoryResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetResourceConfigHistory operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetResourceConfigHistory operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetResourceConfigHistory /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetResourceConfigHistory">REST API Reference for GetResourceConfigHistory Operation</seealso> public virtual IAsyncResult BeginGetResourceConfigHistory(GetResourceConfigHistoryRequest request, AsyncCallback callback, object state) { var marshaller = GetResourceConfigHistoryRequestMarshaller.Instance; var unmarshaller = GetResourceConfigHistoryResponseUnmarshaller.Instance; return BeginInvoke<GetResourceConfigHistoryRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetResourceConfigHistory operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetResourceConfigHistory.</param> /// /// <returns>Returns a GetResourceConfigHistoryResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/GetResourceConfigHistory">REST API Reference for GetResourceConfigHistory Operation</seealso> public virtual GetResourceConfigHistoryResponse EndGetResourceConfigHistory(IAsyncResult asyncResult) { return EndInvoke<GetResourceConfigHistoryResponse>(asyncResult); } #endregion #region ListDiscoveredResources /// <summary> /// Accepts a resource type and returns a list of resource identifiers for the resources /// of that type. A resource identifier includes the resource type, ID, and (if available) /// the custom resource name. The results consist of resources that AWS Config has discovered, /// including those that AWS Config is not currently recording. You can narrow the results /// to include only resources that have specific resource IDs or a resource name. /// /// <note> /// <para> /// You can specify either resource IDs or a resource name, but not both, in the same /// request. /// </para> /// </note> /// <para> /// The response is paginated. By default, AWS Config lists 100 resource identifiers on /// each page. You can customize this number with the <code>limit</code> parameter. The /// response includes a <code>nextToken</code> string. To get the next page of results, /// run the request again and specify the string for the <code>nextToken</code> parameter. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListDiscoveredResources service method.</param> /// /// <returns>The response from the ListDiscoveredResources service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidLimitException"> /// The specified limit is outside the allowable range. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidNextTokenException"> /// The specified next token is invalid. Specify the <code>nextToken</code> string that /// was returned in the previous response to get the next page of results. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoAvailableConfigurationRecorderException"> /// There are no configuration recorders available to provide the role needed to describe /// your resources. Create a configuration recorder. /// </exception> /// <exception cref="Amazon.ConfigService.Model.ValidationException"> /// The requested action is not valid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/ListDiscoveredResources">REST API Reference for ListDiscoveredResources Operation</seealso> public virtual ListDiscoveredResourcesResponse ListDiscoveredResources(ListDiscoveredResourcesRequest request) { var marshaller = ListDiscoveredResourcesRequestMarshaller.Instance; var unmarshaller = ListDiscoveredResourcesResponseUnmarshaller.Instance; return Invoke<ListDiscoveredResourcesRequest,ListDiscoveredResourcesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListDiscoveredResources operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListDiscoveredResources operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListDiscoveredResources /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/ListDiscoveredResources">REST API Reference for ListDiscoveredResources Operation</seealso> public virtual IAsyncResult BeginListDiscoveredResources(ListDiscoveredResourcesRequest request, AsyncCallback callback, object state) { var marshaller = ListDiscoveredResourcesRequestMarshaller.Instance; var unmarshaller = ListDiscoveredResourcesResponseUnmarshaller.Instance; return BeginInvoke<ListDiscoveredResourcesRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ListDiscoveredResources operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListDiscoveredResources.</param> /// /// <returns>Returns a ListDiscoveredResourcesResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/ListDiscoveredResources">REST API Reference for ListDiscoveredResources Operation</seealso> public virtual ListDiscoveredResourcesResponse EndListDiscoveredResources(IAsyncResult asyncResult) { return EndInvoke<ListDiscoveredResourcesResponse>(asyncResult); } #endregion #region PutAggregationAuthorization /// <summary> /// Authorizes the aggregator account and region to collect data from the source account /// and region. /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutAggregationAuthorization service method.</param> /// /// <returns>The response from the PutAggregationAuthorization service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutAggregationAuthorization">REST API Reference for PutAggregationAuthorization Operation</seealso> public virtual PutAggregationAuthorizationResponse PutAggregationAuthorization(PutAggregationAuthorizationRequest request) { var marshaller = PutAggregationAuthorizationRequestMarshaller.Instance; var unmarshaller = PutAggregationAuthorizationResponseUnmarshaller.Instance; return Invoke<PutAggregationAuthorizationRequest,PutAggregationAuthorizationResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PutAggregationAuthorization operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutAggregationAuthorization operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutAggregationAuthorization /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutAggregationAuthorization">REST API Reference for PutAggregationAuthorization Operation</seealso> public virtual IAsyncResult BeginPutAggregationAuthorization(PutAggregationAuthorizationRequest request, AsyncCallback callback, object state) { var marshaller = PutAggregationAuthorizationRequestMarshaller.Instance; var unmarshaller = PutAggregationAuthorizationResponseUnmarshaller.Instance; return BeginInvoke<PutAggregationAuthorizationRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the PutAggregationAuthorization operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutAggregationAuthorization.</param> /// /// <returns>Returns a PutAggregationAuthorizationResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutAggregationAuthorization">REST API Reference for PutAggregationAuthorization Operation</seealso> public virtual PutAggregationAuthorizationResponse EndPutAggregationAuthorization(IAsyncResult asyncResult) { return EndInvoke<PutAggregationAuthorizationResponse>(asyncResult); } #endregion #region PutConfigRule /// <summary> /// Adds or updates an AWS Config rule for evaluating whether your AWS resources comply /// with your desired configurations. /// /// /// <para> /// You can use this action for custom AWS Config rules and AWS managed Config rules. /// A custom AWS Config rule is a rule that you develop and maintain. An AWS managed Config /// rule is a customizable, predefined rule that AWS Config provides. /// </para> /// /// <para> /// If you are adding a new custom AWS Config rule, you must first create the AWS Lambda /// function that the rule invokes to evaluate your resources. When you use the <code>PutConfigRule</code> /// action to add the rule to AWS Config, you must specify the Amazon Resource Name (ARN) /// that AWS Lambda assigns to the function. Specify the ARN for the <code>SourceIdentifier</code> /// key. This key is part of the <code>Source</code> object, which is part of the <code>ConfigRule</code> /// object. /// </para> /// /// <para> /// If you are adding an AWS managed Config rule, specify the rule's identifier for the /// <code>SourceIdentifier</code> key. To reference AWS managed Config rule identifiers, /// see <a href="http://docs.aws.amazon.com/config/latest/developerguide/evaluate-config_use-managed-rules.html">About /// AWS Managed Config Rules</a>. /// </para> /// /// <para> /// For any new rule that you add, specify the <code>ConfigRuleName</code> in the <code>ConfigRule</code> /// object. Do not specify the <code>ConfigRuleArn</code> or the <code>ConfigRuleId</code>. /// These values are generated by AWS Config for new rules. /// </para> /// /// <para> /// If you are updating a rule that you added previously, you can specify the rule by /// <code>ConfigRuleName</code>, <code>ConfigRuleId</code>, or <code>ConfigRuleArn</code> /// in the <code>ConfigRule</code> data type that you use in this request. /// </para> /// /// <para> /// The maximum number of rules that AWS Config supports is 50. /// </para> /// /// <para> /// For information about requesting a rule limit increase, see <a href="http://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#limits_config">AWS /// Config Limits</a> in the <i>AWS General Reference Guide</i>. /// </para> /// /// <para> /// For more information about developing and using AWS Config rules, see <a href="http://docs.aws.amazon.com/config/latest/developerguide/evaluate-config.html">Evaluating /// AWS Resource Configurations with AWS Config</a> in the <i>AWS Config Developer Guide</i>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutConfigRule service method.</param> /// /// <returns>The response from the PutConfigRule service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InsufficientPermissionsException"> /// Indicates one of the following errors: /// /// <ul> <li> /// <para> /// The rule cannot be created because the IAM role assigned to AWS Config lacks permissions /// to perform the config:Put* action. /// </para> /// </li> <li> /// <para> /// The AWS Lambda function cannot be invoked. Check the function ARN, and check the function's /// permissions. /// </para> /// </li> </ul> /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <exception cref="Amazon.ConfigService.Model.MaxNumberOfConfigRulesExceededException"> /// Failed to add the AWS Config rule because the account already contains the maximum /// number of 50 rules. Consider deleting any deactivated rules before you add new rules. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoAvailableConfigurationRecorderException"> /// There are no configuration recorders available to provide the role needed to describe /// your resources. Create a configuration recorder. /// </exception> /// <exception cref="Amazon.ConfigService.Model.ResourceInUseException"> /// The rule is currently being deleted or the rule is deleting your evaluation results. /// Try your request again later. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutConfigRule">REST API Reference for PutConfigRule Operation</seealso> public virtual PutConfigRuleResponse PutConfigRule(PutConfigRuleRequest request) { var marshaller = PutConfigRuleRequestMarshaller.Instance; var unmarshaller = PutConfigRuleResponseUnmarshaller.Instance; return Invoke<PutConfigRuleRequest,PutConfigRuleResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PutConfigRule operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutConfigRule operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutConfigRule /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutConfigRule">REST API Reference for PutConfigRule Operation</seealso> public virtual IAsyncResult BeginPutConfigRule(PutConfigRuleRequest request, AsyncCallback callback, object state) { var marshaller = PutConfigRuleRequestMarshaller.Instance; var unmarshaller = PutConfigRuleResponseUnmarshaller.Instance; return BeginInvoke<PutConfigRuleRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the PutConfigRule operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutConfigRule.</param> /// /// <returns>Returns a PutConfigRuleResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutConfigRule">REST API Reference for PutConfigRule Operation</seealso> public virtual PutConfigRuleResponse EndPutConfigRule(IAsyncResult asyncResult) { return EndInvoke<PutConfigRuleResponse>(asyncResult); } #endregion #region PutConfigurationAggregator /// <summary> /// Creates and updates the configuration aggregator with the selected source accounts /// and regions. The source account can be individual account(s) or an organization. /// /// <note> /// <para> /// AWS Config should be enabled in source accounts and regions you want to aggregate. /// </para> /// /// <para> /// If your source type is an organization, you must be signed in to the master account /// and all features must be enabled in your organization. AWS Config calls <code>EnableAwsServiceAccess</code> /// API to enable integration between AWS Config and AWS Organizations. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutConfigurationAggregator service method.</param> /// /// <returns>The response from the PutConfigurationAggregator service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidRoleException"> /// You have provided a null or empty role ARN. /// </exception> /// <exception cref="Amazon.ConfigService.Model.LimitExceededException"> /// For <code>StartConfigRulesEvaluation</code> API, this exception is thrown if an evaluation /// is in progress or if you call the <a>StartConfigRulesEvaluation</a> API more than /// once per minute. /// /// /// <para> /// For <code>PutConfigurationAggregator</code> API, this exception is thrown if the number /// of accounts and aggregators exceeds the limit. /// </para> /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoAvailableOrganizationException"> /// Organization does is no longer available. /// </exception> /// <exception cref="Amazon.ConfigService.Model.OrganizationAccessDeniedException"> /// No permission to call the EnableAWSServiceAccess API. /// </exception> /// <exception cref="Amazon.ConfigService.Model.OrganizationAllFeaturesNotEnabledException"> /// The configuration aggregator cannot be created because organization does not have /// all features enabled. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutConfigurationAggregator">REST API Reference for PutConfigurationAggregator Operation</seealso> public virtual PutConfigurationAggregatorResponse PutConfigurationAggregator(PutConfigurationAggregatorRequest request) { var marshaller = PutConfigurationAggregatorRequestMarshaller.Instance; var unmarshaller = PutConfigurationAggregatorResponseUnmarshaller.Instance; return Invoke<PutConfigurationAggregatorRequest,PutConfigurationAggregatorResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PutConfigurationAggregator operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutConfigurationAggregator operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutConfigurationAggregator /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutConfigurationAggregator">REST API Reference for PutConfigurationAggregator Operation</seealso> public virtual IAsyncResult BeginPutConfigurationAggregator(PutConfigurationAggregatorRequest request, AsyncCallback callback, object state) { var marshaller = PutConfigurationAggregatorRequestMarshaller.Instance; var unmarshaller = PutConfigurationAggregatorResponseUnmarshaller.Instance; return BeginInvoke<PutConfigurationAggregatorRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the PutConfigurationAggregator operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutConfigurationAggregator.</param> /// /// <returns>Returns a PutConfigurationAggregatorResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutConfigurationAggregator">REST API Reference for PutConfigurationAggregator Operation</seealso> public virtual PutConfigurationAggregatorResponse EndPutConfigurationAggregator(IAsyncResult asyncResult) { return EndInvoke<PutConfigurationAggregatorResponse>(asyncResult); } #endregion #region PutConfigurationRecorder /// <summary> /// Creates a new configuration recorder to record the selected resource configurations. /// /// /// <para> /// You can use this action to change the role <code>roleARN</code> or the <code>recordingGroup</code> /// of an existing recorder. To change the role, call the action on the existing configuration /// recorder and specify a role. /// </para> /// <note> /// <para> /// Currently, you can specify only one configuration recorder per region in your account. /// </para> /// /// <para> /// If <code>ConfigurationRecorder</code> does not have the <b>recordingGroup</b> parameter /// specified, the default is to record all supported resource types. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutConfigurationRecorder service method.</param> /// /// <returns>The response from the PutConfigurationRecorder service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidConfigurationRecorderNameException"> /// You have provided a configuration recorder name that is not valid. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidRecordingGroupException"> /// AWS Config throws an exception if the recording group does not contain a valid list /// of resource types. Invalid values might also be incorrectly formatted. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidRoleException"> /// You have provided a null or empty role ARN. /// </exception> /// <exception cref="Amazon.ConfigService.Model.MaxNumberOfConfigurationRecordersExceededException"> /// You have reached the limit of the number of recorders you can create. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutConfigurationRecorder">REST API Reference for PutConfigurationRecorder Operation</seealso> public virtual PutConfigurationRecorderResponse PutConfigurationRecorder(PutConfigurationRecorderRequest request) { var marshaller = PutConfigurationRecorderRequestMarshaller.Instance; var unmarshaller = PutConfigurationRecorderResponseUnmarshaller.Instance; return Invoke<PutConfigurationRecorderRequest,PutConfigurationRecorderResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PutConfigurationRecorder operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutConfigurationRecorder operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutConfigurationRecorder /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutConfigurationRecorder">REST API Reference for PutConfigurationRecorder Operation</seealso> public virtual IAsyncResult BeginPutConfigurationRecorder(PutConfigurationRecorderRequest request, AsyncCallback callback, object state) { var marshaller = PutConfigurationRecorderRequestMarshaller.Instance; var unmarshaller = PutConfigurationRecorderResponseUnmarshaller.Instance; return BeginInvoke<PutConfigurationRecorderRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the PutConfigurationRecorder operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutConfigurationRecorder.</param> /// /// <returns>Returns a PutConfigurationRecorderResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutConfigurationRecorder">REST API Reference for PutConfigurationRecorder Operation</seealso> public virtual PutConfigurationRecorderResponse EndPutConfigurationRecorder(IAsyncResult asyncResult) { return EndInvoke<PutConfigurationRecorderResponse>(asyncResult); } #endregion #region PutDeliveryChannel /// <summary> /// Creates a delivery channel object to deliver configuration information to an Amazon /// S3 bucket and Amazon SNS topic. /// /// /// <para> /// Before you can create a delivery channel, you must create a configuration recorder. /// </para> /// /// <para> /// You can use this action to change the Amazon S3 bucket or an Amazon SNS topic of the /// existing delivery channel. To change the Amazon S3 bucket or an Amazon SNS topic, /// call this action and specify the changed values for the S3 bucket and the SNS topic. /// If you specify a different value for either the S3 bucket or the SNS topic, this action /// will keep the existing value for the parameter that is not changed. /// </para> /// <note> /// <para> /// You can have only one delivery channel per region in your account. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutDeliveryChannel service method.</param> /// /// <returns>The response from the PutDeliveryChannel service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InsufficientDeliveryPolicyException"> /// Your Amazon S3 bucket policy does not permit AWS Config to write to it. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidDeliveryChannelNameException"> /// The specified delivery channel name is not valid. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidS3KeyPrefixException"> /// The specified Amazon S3 key prefix is not valid. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidSNSTopicARNException"> /// The specified Amazon SNS topic does not exist. /// </exception> /// <exception cref="Amazon.ConfigService.Model.MaxNumberOfDeliveryChannelsExceededException"> /// You have reached the limit of the number of delivery channels you can create. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoAvailableConfigurationRecorderException"> /// There are no configuration recorders available to provide the role needed to describe /// your resources. Create a configuration recorder. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchBucketException"> /// The specified Amazon S3 bucket does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutDeliveryChannel">REST API Reference for PutDeliveryChannel Operation</seealso> public virtual PutDeliveryChannelResponse PutDeliveryChannel(PutDeliveryChannelRequest request) { var marshaller = PutDeliveryChannelRequestMarshaller.Instance; var unmarshaller = PutDeliveryChannelResponseUnmarshaller.Instance; return Invoke<PutDeliveryChannelRequest,PutDeliveryChannelResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PutDeliveryChannel operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutDeliveryChannel operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutDeliveryChannel /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutDeliveryChannel">REST API Reference for PutDeliveryChannel Operation</seealso> public virtual IAsyncResult BeginPutDeliveryChannel(PutDeliveryChannelRequest request, AsyncCallback callback, object state) { var marshaller = PutDeliveryChannelRequestMarshaller.Instance; var unmarshaller = PutDeliveryChannelResponseUnmarshaller.Instance; return BeginInvoke<PutDeliveryChannelRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the PutDeliveryChannel operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutDeliveryChannel.</param> /// /// <returns>Returns a PutDeliveryChannelResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutDeliveryChannel">REST API Reference for PutDeliveryChannel Operation</seealso> public virtual PutDeliveryChannelResponse EndPutDeliveryChannel(IAsyncResult asyncResult) { return EndInvoke<PutDeliveryChannelResponse>(asyncResult); } #endregion #region PutEvaluations /// <summary> /// Used by an AWS Lambda function to deliver evaluation results to AWS Config. This action /// is required in every AWS Lambda function that is invoked by an AWS Config rule. /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutEvaluations service method.</param> /// /// <returns>The response from the PutEvaluations service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <exception cref="Amazon.ConfigService.Model.InvalidResultTokenException"> /// The specified <code>ResultToken</code> is invalid. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigRuleException"> /// One or more AWS Config rules in the request are invalid. Verify that the rule names /// are correct and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutEvaluations">REST API Reference for PutEvaluations Operation</seealso> public virtual PutEvaluationsResponse PutEvaluations(PutEvaluationsRequest request) { var marshaller = PutEvaluationsRequestMarshaller.Instance; var unmarshaller = PutEvaluationsResponseUnmarshaller.Instance; return Invoke<PutEvaluationsRequest,PutEvaluationsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PutEvaluations operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutEvaluations operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutEvaluations /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutEvaluations">REST API Reference for PutEvaluations Operation</seealso> public virtual IAsyncResult BeginPutEvaluations(PutEvaluationsRequest request, AsyncCallback callback, object state) { var marshaller = PutEvaluationsRequestMarshaller.Instance; var unmarshaller = PutEvaluationsResponseUnmarshaller.Instance; return BeginInvoke<PutEvaluationsRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the PutEvaluations operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutEvaluations.</param> /// /// <returns>Returns a PutEvaluationsResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutEvaluations">REST API Reference for PutEvaluations Operation</seealso> public virtual PutEvaluationsResponse EndPutEvaluations(IAsyncResult asyncResult) { return EndInvoke<PutEvaluationsResponse>(asyncResult); } #endregion #region PutRetentionConfiguration /// <summary> /// Creates and updates the retention configuration with details about retention period /// (number of days) that AWS Config stores your historical information. The API creates /// the <code>RetentionConfiguration</code> object and names the object as <b>default</b>. /// When you have a <code>RetentionConfiguration</code> object named <b>default</b>, calling /// the API modifies the default object. /// /// <note> /// <para> /// Currently, AWS Config supports only one retention configuration per region in your /// account. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutRetentionConfiguration service method.</param> /// /// <returns>The response from the PutRetentionConfiguration service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <exception cref="Amazon.ConfigService.Model.MaxNumberOfRetentionConfigurationsExceededException"> /// Failed to add the retention configuration because a retention configuration with that /// name already exists. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutRetentionConfiguration">REST API Reference for PutRetentionConfiguration Operation</seealso> public virtual PutRetentionConfigurationResponse PutRetentionConfiguration(PutRetentionConfigurationRequest request) { var marshaller = PutRetentionConfigurationRequestMarshaller.Instance; var unmarshaller = PutRetentionConfigurationResponseUnmarshaller.Instance; return Invoke<PutRetentionConfigurationRequest,PutRetentionConfigurationResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PutRetentionConfiguration operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutRetentionConfiguration operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutRetentionConfiguration /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutRetentionConfiguration">REST API Reference for PutRetentionConfiguration Operation</seealso> public virtual IAsyncResult BeginPutRetentionConfiguration(PutRetentionConfigurationRequest request, AsyncCallback callback, object state) { var marshaller = PutRetentionConfigurationRequestMarshaller.Instance; var unmarshaller = PutRetentionConfigurationResponseUnmarshaller.Instance; return BeginInvoke<PutRetentionConfigurationRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the PutRetentionConfiguration operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutRetentionConfiguration.</param> /// /// <returns>Returns a PutRetentionConfigurationResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutRetentionConfiguration">REST API Reference for PutRetentionConfiguration Operation</seealso> public virtual PutRetentionConfigurationResponse EndPutRetentionConfiguration(IAsyncResult asyncResult) { return EndInvoke<PutRetentionConfigurationResponse>(asyncResult); } #endregion #region StartConfigRulesEvaluation /// <summary> /// Runs an on-demand evaluation for the specified AWS Config rules against the last known /// configuration state of the resources. Use <code>StartConfigRulesEvaluation</code> /// when you want to test that a rule you updated is working as expected. <code>StartConfigRulesEvaluation</code> /// does not re-record the latest configuration state for your resources. It re-runs an /// evaluation against the last known state of your resources. /// /// /// <para> /// You can specify up to 25 AWS Config rules per request. /// </para> /// /// <para> /// An existing <code>StartConfigRulesEvaluation</code> call for the specified rules must /// complete before you can call the API again. If you chose to have AWS Config stream /// to an Amazon SNS topic, you will receive a <code>ConfigRuleEvaluationStarted</code> /// notification when the evaluation starts. /// </para> /// <note> /// <para> /// You don't need to call the <code>StartConfigRulesEvaluation</code> API to run an evaluation /// for a new rule. When you create a rule, AWS Config evaluates your resources against /// the rule automatically. /// </para> /// </note> /// <para> /// The <code>StartConfigRulesEvaluation</code> API is useful if you want to run on-demand /// evaluations, such as the following example: /// </para> /// <ol> <li> /// <para> /// You have a custom rule that evaluates your IAM resources every 24 hours. /// </para> /// </li> <li> /// <para> /// You update your Lambda function to add additional conditions to your rule. /// </para> /// </li> <li> /// <para> /// Instead of waiting for the next periodic evaluation, you call the <code>StartConfigRulesEvaluation</code> /// API. /// </para> /// </li> <li> /// <para> /// AWS Config invokes your Lambda function and evaluates your IAM resources. /// </para> /// </li> <li> /// <para> /// Your custom rule will still run periodic evaluations every 24 hours. /// </para> /// </li> </ol> /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartConfigRulesEvaluation service method.</param> /// /// <returns>The response from the StartConfigRulesEvaluation service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.InvalidParameterValueException"> /// One or more of the specified parameters are invalid. Verify that your parameters are /// valid and try again. /// </exception> /// <exception cref="Amazon.ConfigService.Model.LimitExceededException"> /// For <code>StartConfigRulesEvaluation</code> API, this exception is thrown if an evaluation /// is in progress or if you call the <a>StartConfigRulesEvaluation</a> API more than /// once per minute. /// /// /// <para> /// For <code>PutConfigurationAggregator</code> API, this exception is thrown if the number /// of accounts and aggregators exceeds the limit. /// </para> /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigRuleException"> /// One or more AWS Config rules in the request are invalid. Verify that the rule names /// are correct and try again. /// </exception> /// <exception cref="Amazon.ConfigService.Model.ResourceInUseException"> /// The rule is currently being deleted or the rule is deleting your evaluation results. /// Try your request again later. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/StartConfigRulesEvaluation">REST API Reference for StartConfigRulesEvaluation Operation</seealso> public virtual StartConfigRulesEvaluationResponse StartConfigRulesEvaluation(StartConfigRulesEvaluationRequest request) { var marshaller = StartConfigRulesEvaluationRequestMarshaller.Instance; var unmarshaller = StartConfigRulesEvaluationResponseUnmarshaller.Instance; return Invoke<StartConfigRulesEvaluationRequest,StartConfigRulesEvaluationResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the StartConfigRulesEvaluation operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartConfigRulesEvaluation operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStartConfigRulesEvaluation /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/StartConfigRulesEvaluation">REST API Reference for StartConfigRulesEvaluation Operation</seealso> public virtual IAsyncResult BeginStartConfigRulesEvaluation(StartConfigRulesEvaluationRequest request, AsyncCallback callback, object state) { var marshaller = StartConfigRulesEvaluationRequestMarshaller.Instance; var unmarshaller = StartConfigRulesEvaluationResponseUnmarshaller.Instance; return BeginInvoke<StartConfigRulesEvaluationRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the StartConfigRulesEvaluation operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginStartConfigRulesEvaluation.</param> /// /// <returns>Returns a StartConfigRulesEvaluationResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/StartConfigRulesEvaluation">REST API Reference for StartConfigRulesEvaluation Operation</seealso> public virtual StartConfigRulesEvaluationResponse EndStartConfigRulesEvaluation(IAsyncResult asyncResult) { return EndInvoke<StartConfigRulesEvaluationResponse>(asyncResult); } #endregion #region StartConfigurationRecorder /// <summary> /// Starts recording configurations of the AWS resources you have selected to record in /// your AWS account. /// /// /// <para> /// You must have created at least one delivery channel to successfully start the configuration /// recorder. /// </para> /// </summary> /// <param name="configurationRecorderName">The name of the recorder object that records each configuration change made to the resources.</param> /// /// <returns>The response from the StartConfigurationRecorder service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoAvailableDeliveryChannelException"> /// There is no delivery channel available to record configurations. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationRecorderException"> /// You have specified a configuration recorder that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/StartConfigurationRecorder">REST API Reference for StartConfigurationRecorder Operation</seealso> public virtual StartConfigurationRecorderResponse StartConfigurationRecorder(string configurationRecorderName) { var request = new StartConfigurationRecorderRequest(); request.ConfigurationRecorderName = configurationRecorderName; return StartConfigurationRecorder(request); } /// <summary> /// Starts recording configurations of the AWS resources you have selected to record in /// your AWS account. /// /// /// <para> /// You must have created at least one delivery channel to successfully start the configuration /// recorder. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartConfigurationRecorder service method.</param> /// /// <returns>The response from the StartConfigurationRecorder service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoAvailableDeliveryChannelException"> /// There is no delivery channel available to record configurations. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationRecorderException"> /// You have specified a configuration recorder that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/StartConfigurationRecorder">REST API Reference for StartConfigurationRecorder Operation</seealso> public virtual StartConfigurationRecorderResponse StartConfigurationRecorder(StartConfigurationRecorderRequest request) { var marshaller = StartConfigurationRecorderRequestMarshaller.Instance; var unmarshaller = StartConfigurationRecorderResponseUnmarshaller.Instance; return Invoke<StartConfigurationRecorderRequest,StartConfigurationRecorderResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the StartConfigurationRecorder operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartConfigurationRecorder operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStartConfigurationRecorder /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/StartConfigurationRecorder">REST API Reference for StartConfigurationRecorder Operation</seealso> public virtual IAsyncResult BeginStartConfigurationRecorder(StartConfigurationRecorderRequest request, AsyncCallback callback, object state) { var marshaller = StartConfigurationRecorderRequestMarshaller.Instance; var unmarshaller = StartConfigurationRecorderResponseUnmarshaller.Instance; return BeginInvoke<StartConfigurationRecorderRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the StartConfigurationRecorder operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginStartConfigurationRecorder.</param> /// /// <returns>Returns a StartConfigurationRecorderResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/StartConfigurationRecorder">REST API Reference for StartConfigurationRecorder Operation</seealso> public virtual StartConfigurationRecorderResponse EndStartConfigurationRecorder(IAsyncResult asyncResult) { return EndInvoke<StartConfigurationRecorderResponse>(asyncResult); } #endregion #region StopConfigurationRecorder /// <summary> /// Stops recording configurations of the AWS resources you have selected to record in /// your AWS account. /// </summary> /// <param name="configurationRecorderName">The name of the recorder object that records each configuration change made to the resources.</param> /// /// <returns>The response from the StopConfigurationRecorder service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationRecorderException"> /// You have specified a configuration recorder that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/StopConfigurationRecorder">REST API Reference for StopConfigurationRecorder Operation</seealso> public virtual StopConfigurationRecorderResponse StopConfigurationRecorder(string configurationRecorderName) { var request = new StopConfigurationRecorderRequest(); request.ConfigurationRecorderName = configurationRecorderName; return StopConfigurationRecorder(request); } /// <summary> /// Stops recording configurations of the AWS resources you have selected to record in /// your AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the StopConfigurationRecorder service method.</param> /// /// <returns>The response from the StopConfigurationRecorder service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationRecorderException"> /// You have specified a configuration recorder that does not exist. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/StopConfigurationRecorder">REST API Reference for StopConfigurationRecorder Operation</seealso> public virtual StopConfigurationRecorderResponse StopConfigurationRecorder(StopConfigurationRecorderRequest request) { var marshaller = StopConfigurationRecorderRequestMarshaller.Instance; var unmarshaller = StopConfigurationRecorderResponseUnmarshaller.Instance; return Invoke<StopConfigurationRecorderRequest,StopConfigurationRecorderResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the StopConfigurationRecorder operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StopConfigurationRecorder operation on AmazonConfigServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStopConfigurationRecorder /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/StopConfigurationRecorder">REST API Reference for StopConfigurationRecorder Operation</seealso> public virtual IAsyncResult BeginStopConfigurationRecorder(StopConfigurationRecorderRequest request, AsyncCallback callback, object state) { var marshaller = StopConfigurationRecorderRequestMarshaller.Instance; var unmarshaller = StopConfigurationRecorderResponseUnmarshaller.Instance; return BeginInvoke<StopConfigurationRecorderRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the StopConfigurationRecorder operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginStopConfigurationRecorder.</param> /// /// <returns>Returns a StopConfigurationRecorderResult from ConfigService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/StopConfigurationRecorder">REST API Reference for StopConfigurationRecorder Operation</seealso> public virtual StopConfigurationRecorderResponse EndStopConfigurationRecorder(IAsyncResult asyncResult) { return EndInvoke<StopConfigurationRecorderResponse>(asyncResult); } #endregion } }
60.826839
217
0.693187
[ "Apache-2.0" ]
InsiteVR/aws-sdk-net
sdk/src/Services/ConfigService/Generated/_bcl35/AmazonConfigServiceClient.cs
221,653
C#
 using JetBrains.Annotations; using Newtonsoft.Json; namespace Crowdin.Api.Labels { [PublicAPI] public class AddLabelRequest { [JsonProperty("title")] public string Title { get; set; } } }
17.076923
41
0.648649
[ "MIT" ]
crowdin/crowdin-api-client-dotnet
src/Crowdin.Api/Labels/AddLabelRequest.cs
224
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Chaow.Numeric")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Chaow.Numeric")] [assembly: AssemblyCopyright("Copyright © 2008")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("526e6ae4-9495-4c0a-9198-8f6dc1bca37f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
34.948718
84
0.738811
[ "MIT" ]
chaowlert/algorithm
Numeric/Properties/AssemblyInfo.cs
1,366
C#
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; using NLog.Internal; using NLog.Targets; using System.Runtime.Serialization; using System.Xml.Serialization; #if NET4_5 using System.Web.Http; using Owin; using Microsoft.Owin.Hosting; using System.Web.Http.Dependencies; #endif using Xunit; namespace NLog.UnitTests.Targets { public class WebServiceTargetTests : NLogTestBase { [Fact] public void Stream_CopyWithOffset_test() { var text = @" Lorem ipsum dolor sit amet consectetuer tellus semper dictum urna consectetuer. Eu iaculis enim tincidunt mi pede id ut sociis non vitae. Condimentum augue Nam Vestibulum faucibus tortor et at Sed et molestie. Interdum morbi Nullam pellentesque Vestibulum pede et eget semper Pellentesque quis. Velit cursus nec dolor vitae id et urna quis ante velit. Neque urna et vitae neque Vestibulum tellus convallis dui. Tellus nibh enim augue senectus ut augue Donec Pellentesque Sed pretium. Volutpat nunc rutrum auctor dolor pharetra malesuada elit sapien ac nec. Adipiscing et id penatibus turpis a odio risus orci Suspendisse eu. Nibh eu facilisi eu consectetuer nibh eu in Nunc Curabitur rutrum. Quisque sit lacus consectetuer eu Duis quis felis hendrerit lobortis mauris. Nam Vivamus enim Aenean rhoncus. Nulla tellus dui orci montes Vestibulum Aenean condimentum non id vel. Euismod Nam libero odio ut ut Nunc ac dui Nulla volutpat. Quisque facilisis consequat tempus tempus Curabitur tortor id Phasellus Suspendisse In. Lorem et Phasellus wisi Fusce fringilla pretium pede sapien amet ligula. In sed id In eget tristique quam sed interdum wisi commodo. Volutpat neque nibh mauris Quisque lorem nunc porttitor Cras faucibus augue. Sociis tempus et. Morbi Nulla justo Aenean orci Vestibulum ullamcorper tincidunt mollis et hendrerit. Enim at laoreet elit eros ut at laoreet vel velit quis. Netus sed Suspendisse sed Curabitur vel sed wisi sapien nonummy congue. Semper Sed a malesuada tristique Vivamus et est eu quis ante. Wisi cursus Suspendisse dictum pretium habitant sodales scelerisque dui tempus libero. Venenatis consequat Lorem eu. "; var textStream = GenerateStreamFromString(text); var textBytes = StreamToBytes(textStream); textStream.Position = 0; textStream.Flush(); var resultStream = new MemoryStream(); textStream.CopyWithOffset(resultStream, 3); var result = StreamToBytes(resultStream); var expected = textBytes.Skip(3).ToArray(); Assert.Equal(result.Length, expected.Length); Assert.Equal(result, expected); } [Fact] public void WebserviceTest_httppost_utf8_default_no_bom() { WebserviceTest_httppost_utf8("", false); } [Fact] public void WebserviceTest_httppost_utf8_with_bom() { WebserviceTest_httppost_utf8("includeBOM='true'", true); } [Fact] public void WebserviceTest_httppost_utf8_no_boml() { WebserviceTest_httppost_utf8("includeBOM='false'", false); } private void WebserviceTest_httppost_utf8(string bomAttr, bool includeBom) { var configuration = CreateConfigurationFromString(@" <nlog> <targets> <target type='WebService' name='webservice' url='http://localhost:57953/Home/Foo2' protocol='HttpPost' " + bomAttr + @" encoding='UTF-8' methodName='Foo'> <parameter name='empty' type='System.String' layout=''/> <!-- work around so the guid is decoded properly --> <parameter name='guid' type='System.String' layout='${guid}'/> <parameter name='m' type='System.String' layout='${message}'/> <parameter name='date' type='System.String' layout='${longdate}'/> <parameter name='logger' type='System.String' layout='${logger}'/> <parameter name='level' type='System.String' layout='${level}'/> </target> </targets> </nlog>"); var target = configuration.FindTargetByName("webservice") as WebServiceTarget; Assert.NotNull(target); Assert.Equal(target.Parameters.Count, 6); Assert.Equal(target.Encoding.WebName, "utf-8"); //async call with mockup stream WebRequest webRequest = WebRequest.Create("http://www.test.com"); var request = (HttpWebRequest)webRequest; var streamMock = new StreamMock(); //event for async testing var counterEvent = new ManualResetEvent(false); var parameterValues = new object[] { "", "336cec87129942eeabab3d8babceead7", "Debg", "2014-06-26 23:15:14.6348", "TestClient.Program", "Debug" }; target.DoInvoke(parameterValues, c => counterEvent.Set(), request, callback => { var t = new Task(() => { }); callback(t); return t; }, result => streamMock); counterEvent.WaitOne(10000); var bytes = streamMock.bytes; var url = streamMock.stringed; const string expectedUrl = "empty=&guid=336cec87129942eeabab3d8babceead7&m=Debg&date=2014-06-26+23%3a15%3a14.6348&logger=TestClient.Program&level=Debug"; Assert.Equal(expectedUrl, url); Assert.True(bytes.Length > 3); //not bom var possbleBomBytes = bytes.Take(3).ToArray(); if (includeBom) { Assert.Equal(possbleBomBytes, EncodingHelpers.Utf8BOM); } else { Assert.NotEqual(possbleBomBytes, EncodingHelpers.Utf8BOM); } Assert.Equal(bytes.Length, includeBom ? 126 : 123); } #region helpers private Stream GenerateStreamFromString(string s) { MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream); writer.Write(s); writer.Flush(); stream.Position = 0; return stream; } private static byte[] StreamToBytes(Stream stream) { stream.Flush(); stream.Position = 0; byte[] buffer = new byte[16 * 1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } /// <summary> /// Mock the stream /// </summary> private class StreamMock : MemoryStream { public byte[] bytes; public string stringed; #region Overrides of MemoryStream /// <summary> /// Releases the unmanaged resources used by the <see cref="T:System.IO.MemoryStream"/> class and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { //save stuff before dispose this.Flush(); bytes = this.ToArray(); stringed = StreamToString(this); base.Dispose(disposing); } private static string StreamToString(Stream s) { s.Position = 0; var sr = new StreamReader(s); return sr.ReadToEnd(); } #endregion } #endregion #if NET4_5 const string WsAddress = "http://localhost:9000/"; private static string getWsAddress(int portOffset) { return WsAddress.Substring(0, WsAddress.Length - 5) + (9000 + portOffset).ToString() + "/"; } /// <summary> /// Test the Webservice with REST api - <see cref="WebServiceProtocol.HttpPost"/> (only checking for no exception) /// </summary> [Fact] public void WebserviceTest_restapi_httppost() { var configuration = CreateConfigurationFromString(string.Format(@" <nlog throwExceptions='true'> <targets> <target type='WebService' name='ws' url='{0}{1}' protocol='HttpPost' encoding='UTF-8' > <parameter name='param1' type='System.String' layout='${{message}}'/> <parameter name='param2' type='System.String' layout='${{level}}'/> </target> </targets> <rules> <logger name='*' writeTo='ws'> </logger> </rules> </nlog>", WsAddress, "api/logme")); LogManager.Configuration = configuration; var logger = LogManager.GetCurrentClassLogger(); LogMeController.ResetState(1); LogMeController.ResetState(2); var message1 = "message 1 with a post"; var message2 = "a b c é k è ï ?"; StartOwinTest(() => { logger.Info(message1); logger.Info(message2); }); Assert.Equal(LogMeController.CountdownEvent.CurrentCount, 0); Assert.Equal(2, LogMeController.RecievedLogsPostParam1.Count); CheckQueueMessage(message1, LogMeController.RecievedLogsPostParam1); CheckQueueMessage(message2, LogMeController.RecievedLogsPostParam1); } /// <summary> /// Test the Webservice with REST api - <see cref="WebServiceProtocol.HttpGet"/> (only checking for no exception) /// </summary> [Fact] public void WebserviceTest_restapi_httpget() { var logger = SetUpHttpGetWebservice("api/logme"); LogMeController.ResetState(2); var message1 = "message 1 with a post"; var message2 = "a b c é k è ï ?"; StartOwinTest(() => { logger.Info(message1); logger.Info(message2); }); Assert.Equal(LogMeController.CountdownEvent.CurrentCount, 0); Assert.Equal(2, LogMeController.RecievedLogsGetParam1.Count); CheckQueueMessage(message1, LogMeController.RecievedLogsGetParam1); CheckQueueMessage(message2, LogMeController.RecievedLogsGetParam1); } /// <summary> /// Test the Webservice with REST api - <see cref="WebServiceProtocol.HttpGet"/> (only checking for no exception) /// </summary> [Fact] public void WebserviceTest_restapi_httpget_flush() { var logger = SetUpHttpGetWebservice("api/logme"); LogMeController.ResetState(0); var message1 = "message with a post"; StartOwinTest(() => { for (int i = 0; i < 100; ++i) logger.Info(message1); // Make triple-flush to fully exercise the async flushing logic try { LogManager.Flush(0); } catch (NLog.NLogRuntimeException) { } LogManager.Flush(); // Waits for flush (Scheduled on top of the previous flush) LogManager.Flush(); // Nothing to flush }); Assert.Equal(100, LogMeController.RecievedLogsGetParam1.Count); } [Fact] public void WebServiceTest_restapi_httpget_querystring() { var logger = SetUpHttpGetWebservice("api/logme?paramFromConfig=valueFromConfig"); LogMeController.ResetState(1); StartOwinTest(() => { logger.Info("another message"); }); Assert.Equal(LogMeController.CountdownEvent.CurrentCount, 0); Assert.Equal(1, LogMeController.RecievedLogsGetParam1.Count); CheckQueueMessage("another message", LogMeController.RecievedLogsGetParam1); } private static Logger SetUpHttpGetWebservice(string relativeUrl) { var configuration = CreateConfigurationFromString(string.Format(@" <nlog throwExceptions='true' > <targets> <target type='WebService' name='ws' url='{0}{1}' protocol='HttpGet' encoding='UTF-8' > <parameter name='param1' type='System.String' layout='${{message}}'/> <parameter name='param2' type='System.String' layout='${{level}}'/> </target> </targets> <rules> <logger name='*' writeTo='ws'> </logger> </rules> </nlog>", WsAddress, relativeUrl)); LogManager.Configuration = configuration; var logger = LogManager.GetCurrentClassLogger(); return logger; } private static void CheckQueueMessage(string message1, ConcurrentBag<string> recievedLogsGetParam1) { var success = recievedLogsGetParam1.Contains(message1); Assert.True(success, string.Format("message '{0}' not found", message1)); } /// <summary> /// Timeout for <see cref="WebserviceTest_restapi_httppost_checkingLost"/>. /// /// in miliseconds. 20000 = 20 sec /// </summary> const int webserviceCheckTimeoutMs = 20000; /// <summary> /// Test the Webservice with REST api - <see cref="WebServiceProtocol.HttpPost"/> (only checking for no exception) /// /// repeats for checking 'lost messages' /// </summary> [Fact] public void WebserviceTest_restapi_httppost_checkingLost() { var configuration = CreateConfigurationFromString(string.Format(@" <nlog throwExceptions='true'> <targets> <target type='WebService' name='ws' url='{0}{1}' protocol='HttpPost' encoding='UTF-8' > <parameter name='param1' type='System.String' layout='${{message}}'/> <parameter name='param2' type='System.String' layout='${{level}}'/> </target> </targets> <rules> <logger name='*' writeTo='ws'> </logger> </rules> </nlog>", WsAddress, "api/logme")); LogManager.Configuration = configuration; var logger = LogManager.GetCurrentClassLogger(); const int messageCount = 1000; var createdMessages = new List<string>(messageCount); for (int i = 0; i < messageCount; i++) { var message = "message " + i; createdMessages.Add(message); } //reset LogMeController.ResetState(messageCount); StartOwinTest(() => { foreach (var createdMessage in createdMessages) { logger.Info(createdMessage); } }); Assert.Equal(LogMeController.CountdownEvent.CurrentCount, 0); Assert.Equal(createdMessages.Count, LogMeController.RecievedLogsPostParam1.Count); //Assert.Equal(createdMessages, ValuesController.RecievedLogsPostParam1); } /// <summary> /// Test the Webservice with REST api - <see cref="WebServiceProtocol.JsonPost"/> /// </summary> [Fact] public void WebserviceTest_restapi_json() { var configuration = CreateConfigurationFromString(string.Format(@" <nlog throwExceptions='true'> <targets> <target type='WebService' name='ws' url='{0}{1}' protocol='JsonPost' encoding='UTF-8' > <parameter name='param1' ParameterType='System.String' layout='${{message}}'/> <parameter name='param2' ParameterType='System.String' layout='${{level}}'/> <parameter name='param3' ParameterType='System.Boolean' layout='True'/> <parameter name='param4' ParameterType='System.DateTime' layout='${{date:universalTime=true:format=o}}'/> </target> </targets> <rules> <logger name='*' writeTo='ws'> </logger> </rules> </nlog>", getWsAddress(1), "api/logdoc/json")); LogManager.Configuration = configuration; var logger = LogManager.GetCurrentClassLogger(); var txt = "message 1 with a JSON POST<hello><again\\>\"\b"; // Lets tease the JSON serializer and see it can handle valid and invalid xml chars var count = 101; var context = new LogDocController.TestContext(1, count, false, txt, "info", true, DateTime.UtcNow); StartOwinDocTest(context, () => { for (int i = 0; i < count; i++) logger.Info(txt); }); Assert.Equal<int>(0, context.CountdownEvent.CurrentCount); } /// <summary> /// Test the Webservice with REST api - <see cref="WebServiceProtocol.XmlPost"/> /// </summary> [Fact] public void WebserviceTest_restapi_xml() { var configuration = CreateConfigurationFromString(string.Format(@" <nlog throwExceptions='true'> <targets> <target type='WebService' name='ws' url='{0}{1}' protocol='XmlPost' XmlRoot='ComplexType' encoding='UTF-8' > <parameter name='param1' ParameterType='System.String' layout='${{message}}'/> <parameter name='param2' ParameterType='System.String' layout='${{level}}'/> <parameter name='param3' ParameterType='System.Boolean' layout='True'/> <parameter name='param4' ParameterType='System.DateTime' layout='${{date:universalTime=true:format=o}}'/> </target> </targets> <rules> <logger name='*' writeTo='ws'> </logger> </rules> </nlog>", getWsAddress(1), "api/logdoc/xml")); LogManager.Configuration = configuration; var logger = LogManager.GetCurrentClassLogger(); var txt = "message 1 with a XML POST<hello><again\\>\""; // Lets tease the Xml-Serializer, and see it can handle xml-tags var count = 101; var context = new LogDocController.TestContext(1, count, true, txt, "info", true, DateTime.UtcNow); StartOwinDocTest(context, () => { for (int i = 0; i < count; i++) logger.Info(txt + "\b"); // Lets tease the Xml-Serializer, and see it can remove invalid chars }); Assert.Equal<int>(0, context.CountdownEvent.CurrentCount); } /// <summary> /// Start/config route of WS /// </summary> private class Startup { // This code configures Web API. The Startup class is specified as a type // parameter in the WebApp.Start method. public void Configuration(IAppBuilder appBuilder) { // Configure Web API for self-host. HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); appBuilder.UseWebApi(config); } } ///<remarks>Must be public </remarks> public class LogMeController : ApiController { /// <summary> /// Reset the state for unit testing /// </summary> /// <param name="expectedMessages"></param> public static void ResetState(int expectedMessages) { RecievedLogsPostParam1 = new ConcurrentBag<string>(); RecievedLogsGetParam1 = new ConcurrentBag<string>(); if (expectedMessages > 0) CountdownEvent = new CountdownEvent(expectedMessages); else CountdownEvent = null; } /// <summary> /// Countdown event for keeping WS alive. /// </summary> public static CountdownEvent CountdownEvent = null; /// <summary> /// Recieved param1 values (get) /// </summary> public static ConcurrentBag<string> RecievedLogsGetParam1 = new ConcurrentBag<string>(); /// <summary> /// Recieved param1 values(post) /// </summary> public static ConcurrentBag<string> RecievedLogsPostParam1 = new ConcurrentBag<string>(); /// <summary> /// We need a complex type for modelbinding because of content-type: "application/x-www-form-urlencoded" in <see cref="WebServiceTarget"/> /// </summary> [DataContract(Namespace = "")] [XmlRoot(ElementName = "ComplexType", Namespace = "")] public class ComplexType { [DataMember(Name = "param1")] [XmlElement("param1")] public string Param1 { get; set; } [DataMember(Name = "param2")] [XmlElement("param2")] public string Param2 { get; set; } [DataMember(Name = "param3")] [XmlElement("param3")] public bool Param3 { get; set; } [DataMember(Name = "param4")] [XmlElement("param4")] public DateTime Param4 { get; set; } } /// <summary> /// Get /// </summary> public string Get(int id) { return "value"; } // GET api/values public IEnumerable<string> Get(string param1 = "", string param2 = "") { RecievedLogsGetParam1.Add(param1); if (CountdownEvent != null) { CountdownEvent.Signal(); } return new string[] { "value1", "value2" }; } /// <summary> /// Post /// </summary> public void Post([FromBody] ComplexType complexType) { //this is working. if (complexType == null) { throw new ArgumentNullException("complexType"); } RecievedLogsPostParam1.Add(complexType.Param1); if (CountdownEvent != null) { CountdownEvent.Signal(); } } /// <summary> /// Put /// </summary> public void Put(int id, [FromBody]string value) { } /// <summary> /// Delete /// </summary> public void Delete(int id) { } } internal static void StartOwinTest(Action testsFunc) { // HttpSelfHostConfiguration. So info: http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api // Start webservice using (WebApp.Start<Startup>(url: WsAddress)) { testsFunc(); //wait for all recieved message, or timeout. There is no exception on timeout, so we have to check carefully in the unit test. if (LogMeController.CountdownEvent != null) { LogMeController.CountdownEvent.Wait(webserviceCheckTimeoutMs); //we need some extra time for completion Thread.Sleep(1000); } } } internal static void StartOwinDocTest(LogDocController.TestContext testContext, Action testsFunc) { var stu = new StartupDoc(testContext); using (WebApp.Start(getWsAddress(testContext.PortOffset), stu.Configuration)) { testsFunc(); if (testContext.CountdownEvent != null) { testContext.CountdownEvent.Wait(webserviceCheckTimeoutMs); Thread.Sleep(1000); } } } private class StartupDoc { LogDocController.TestContext _testContext; public StartupDoc(LogDocController.TestContext testContext) { _testContext = testContext; } // This code configures Web API. The Startup class is specified as a type // parameter in the WebApp.Start method. public void Configuration(IAppBuilder appBuilder) { // Configure Web API for self-host. HttpConfiguration config = new HttpConfiguration(); config.DependencyResolver = new ControllerResolver(_testContext); config.Routes.MapHttpRoute( name: "ApiWithAction", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); if (_testContext.XmlInsteadOfJson) { // Default Xml Formatter uses DataContractSerializer, changing it to XmlSerializer config.Formatters.XmlFormatter.UseXmlSerializer = true; } else { // Use ISO 8601 / RFC 3339 Date-Format (2012-07-27T18:51:45.53403Z), instead of Microsoft JSON date format ("\/Date(ticks)\/") config.Formatters.JsonFormatter.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat; config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false; // JSON.NET serializer instead of the ancient DataContractJsonSerializer } appBuilder.UseWebApi(config); } private class ControllerResolver : IDependencyResolver, IDependencyScope { private LogDocController.TestContext _testContext; public ControllerResolver(LogDocController.TestContext testContext) { _testContext = testContext; } public IDependencyScope BeginScope() { return this; } public void Dispose() { } public object GetService(Type serviceType) { if (serviceType == typeof(LogDocController)) { return new LogDocController() { Context = _testContext }; } else { return null; } } public IEnumerable<object> GetServices(Type serviceType) { if (serviceType == typeof(LogDocController)) { return new object[] { new LogDocController() { Context = _testContext } }; } else { return new object[0]; } } } } ///<remarks>Must be public </remarks> public class LogDocController : ApiController { public TestContext Context { get; set; } [HttpPost] public void Json(LogMeController.ComplexType complexType) { if (complexType == null) { throw new ArgumentNullException("complexType"); } processRequest(complexType); } private void processRequest(LogMeController.ComplexType complexType) { if (Context != null) { if (string.Equals(Context.ExpectedParam2, complexType.Param2, StringComparison.OrdinalIgnoreCase) && Context.ExpectedParam1 == complexType.Param1 && Context.ExpectedParam3 == complexType.Param3 && Context.ExpectedParam4.Date == complexType.Param4.Date) { Context.CountdownEvent.Signal(); } } } [HttpPost] public void Xml(LogMeController.ComplexType complexType) { if (complexType == null) { throw new ArgumentNullException("complexType"); } processRequest(complexType); } public class TestContext { public CountdownEvent CountdownEvent { get; } public int PortOffset { get; } public bool XmlInsteadOfJson { get; } = false; public string ExpectedParam1 { get; } public string ExpectedParam2 { get; } public bool ExpectedParam3 { get; } public DateTime ExpectedParam4 { get; } public TestContext(int portOffset, int expectedMessages, bool xmlInsteadOfJson, string expected1, string expected2, bool expected3, DateTime expected4) { CountdownEvent = new CountdownEvent(expectedMessages); PortOffset = portOffset; XmlInsteadOfJson = xmlInsteadOfJson; ExpectedParam1 = expected1; ExpectedParam2 = expected2; ExpectedParam3 = expected3; ExpectedParam4 = expected4; } } } #endif } }
37.162664
444
0.531624
[ "BSD-3-Clause" ]
mexzo/Nlogcompile
tests/NLog.UnitTests/Targets/WebServiceTargetTests.cs
34,049
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PasswordResetNotification.cs" company="BringDream"> // BringDream 2016 // </copyright> // <summary> // The password reset notification. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace RainMakr.Web.Models.Notifications { /// <summary> /// The password reset notification. /// </summary> public class PasswordResetNotification { /// <summary> /// Gets or sets the person id. /// </summary> public string PersonId { get; set; } /// <summary> /// Gets or sets the code. /// </summary> public string Code { get; set; } } }
30.321429
120
0.415783
[ "MIT" ]
thanhquyphan/RainMakr
RainMakr.Web.Models/Notifications/PasswordResetNotification.cs
851
C#