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 |
|---|---|---|---|---|---|---|---|---|
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: ComplexType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type IosVppAppRevokeLicensesActionResult.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
[JsonConverter(typeof(DerivedTypeConverter))]
public partial class IosVppAppRevokeLicensesActionResult
{
/// <summary>
/// Initializes a new instance of the <see cref="IosVppAppRevokeLicensesActionResult"/> class.
/// </summary>
public IosVppAppRevokeLicensesActionResult()
{
this.ODataType = "microsoft.graph.iosVppAppRevokeLicensesActionResult";
}
/// <summary>
/// Gets or sets actionFailureReason.
/// The reason for the revoke licenses action failure. Possible values are: none, appleFailure, internalError, expiredVppToken, expiredApplePushNotificationCertificate.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "actionFailureReason", Required = Newtonsoft.Json.Required.Default)]
public VppTokenActionFailureReason? ActionFailureReason { get; set; }
/// <summary>
/// Gets or sets actionName.
/// Action name
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "actionName", Required = Newtonsoft.Json.Required.Default)]
public string ActionName { get; set; }
/// <summary>
/// Gets or sets actionState.
/// State of the action. Possible values are: none, pending, canceled, active, done, failed, notSupported.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "actionState", Required = Newtonsoft.Json.Required.Default)]
public ActionState? ActionState { get; set; }
/// <summary>
/// Gets or sets failedLicensesCount.
/// A count of the number of licenses for which revoke failed.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "failedLicensesCount", Required = Newtonsoft.Json.Required.Default)]
public Int32? FailedLicensesCount { get; set; }
/// <summary>
/// Gets or sets lastUpdatedDateTime.
/// Time the action state was last updated
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "lastUpdatedDateTime", Required = Newtonsoft.Json.Required.Default)]
public DateTimeOffset? LastUpdatedDateTime { get; set; }
/// <summary>
/// Gets or sets managedDeviceId.
/// DeviceId associated with the action.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "managedDeviceId", Required = Newtonsoft.Json.Required.Default)]
public string ManagedDeviceId { get; set; }
/// <summary>
/// Gets or sets startDateTime.
/// Time the action was initiated
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "startDateTime", Required = Newtonsoft.Json.Required.Default)]
public DateTimeOffset? StartDateTime { get; set; }
/// <summary>
/// Gets or sets totalLicensesCount.
/// A count of the number of licenses for which revoke was attempted.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "totalLicensesCount", Required = Newtonsoft.Json.Required.Default)]
public Int32? TotalLicensesCount { get; set; }
/// <summary>
/// Gets or sets userId.
/// UserId associated with the action.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "userId", Required = Newtonsoft.Json.Required.Default)]
public string UserId { get; set; }
/// <summary>
/// Gets or sets additional data.
/// </summary>
[JsonExtensionData(ReadData = true)]
public IDictionary<string, object> AdditionalData { get; set; }
/// <summary>
/// Gets or sets @odata.type.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "@odata.type", Required = Newtonsoft.Json.Required.Default)]
public string ODataType { get; set; }
}
}
| 45.636364 | 176 | 0.636255 | [
"MIT"
] | GeertVL/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/model/IosVppAppRevokeLicensesActionResult.cs | 5,020 | C# |
// Copyright (c) Daniel Crenna & Contributors. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
namespace Demo
{
public class TokenController : Controller
{
private readonly JwtSecurityTokenHandler _handler;
private readonly IOptionsSnapshot<TokenOptions> _options;
public TokenController(IOptionsSnapshot<TokenOptions> options)
{
_options = options;
_handler = new JwtSecurityTokenHandler();
}
[HttpPost("token")]
public IActionResult GenerateToken([FromBody] TokenRequestModel model)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, model.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.Value.Key));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(_options.Value.Issuer, _options.Value.Audience, claims,
expires: DateTime.Now.AddHours(1),
signingCredentials: credentials);
return Ok(new {token = _handler.WriteToken(token)});
}
}
} | 31.477273 | 111 | 0.768231 | [
"Apache-2.0"
] | danielcrenna/ActiveRoutes | src/Demo/TokenController.cs | 1,387 | C# |
// Copyright 2020 Energinet DataHub A/S
//
// Licensed under the Apache License, Version 2.0 (the "License2");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Xml;
namespace GreenEnergyHub.TimeSeries.Infrastructure.Messaging.Serialization
{
public static class XmlReaderExtension
{
public static bool Is(
[NotNull]this XmlReader reader,
[NotNull]string localName,
[NotNull]string ns,
XmlNodeType xmlNodeType = XmlNodeType.Element)
{
return reader.LocalName.Equals(localName) && reader.NamespaceURI.Equals(ns) &&
reader.NodeType == xmlNodeType;
}
public static bool IsElement([NotNull] this XmlReader reader)
{
return reader.NodeType == XmlNodeType.Element;
}
}
}
| 33.948718 | 90 | 0.685801 | [
"Apache-2.0"
] | Energinet-DataHub/geh-timeseries | source/GreenEnergyHub.TimeSeries/source/GreenEnergyHub.TimeSeries.Infrastructure/Messaging/Serialization/XmlReaderExtension.cs | 1,326 | 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>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("Regeh")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("Regeh")]
[assembly: System.Reflection.AssemblyTitleAttribute("Regeh")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 40.291667 | 80 | 0.642192 | [
"MIT"
] | NickolayNanov/Software-Engineering | C# Fundamentals/C#_Advanced/Exams/C# Advanced Exam - 11 February 2018/11 February 2018/Regeh/obj/Release/netcoreapp2.1/Regeh.AssemblyInfo.cs | 967 | C# |
//
// <copyright file="AssemblyInfo.cs" company="Microsoft">
// Copyright (C) Microsoft. All rights reserved.
// </copyright>
//
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("WSSSubTabWinFormsSample4")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("WSSSubTabWinFormsSample4")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[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("e2a0a4ac-3eb6-46da-ad4d-f42f90abd2d4")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.47619 | 85 | 0.728081 | [
"MIT"
] | 9578577/Windows-classic-samples | Samples/ServerEssentialsDashboard/cs/WSSSubTabWinFormsSample/Properties/AssemblyInfo.cs | 1,534 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool<T> where T : Component
{
T _prefabToPool;
Transform _parent;
int _startSize;
protected Queue<T> Pool = new Queue<T>();
public ObjectPool(T prefabToPool, Transform parent, int startSize)
{
_prefabToPool = prefabToPool;
_parent = parent;
_startSize = startSize;
CreateStartingPool();
}
public T GetObject()
{
if (Pool.Count == 0)
CreateNewPoolObject();
T newPoolObject = Pool.Dequeue();
newPoolObject.gameObject.SetActive(true);
return newPoolObject;
}
public void ReturnObject(T poolObject)
{
poolObject.gameObject.SetActive(false);
Pool.Enqueue(poolObject);
}
void CreateStartingPool()
{
for (int i = 0; i < _startSize; i++)
{
CreateNewPoolObject();
}
}
void CreateNewPoolObject()
{
T newObject = GameObject.Instantiate(_prefabToPool);
newObject.transform.SetParent(_parent);
newObject.gameObject.name = _prefabToPool.gameObject.name;
newObject.gameObject.SetActive(false);
Pool.Enqueue(newObject);
}
}
| 22.122807 | 70 | 0.623315 | [
"MIT"
] | metalac190/FF6Rebuild | Assets/_Game/Scripts/_Common/ObjectPool.cs | 1,261 | C# |
using GetIntoTeachingApi.Services;
using GetIntoTeachingApi.Validators;
using Moq;
using Xunit;
using System;
using FluentValidation;
using FluentValidation.Internal;
using FluentValidation.Validators;
using GetIntoTeachingApi.Models;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
namespace GetIntoTeachingApiTests.Validators
{
public class LookupItemIdValidatorTests
{
private readonly Mock<IStore> _mockStore;
private readonly LookupItem _item;
private readonly LookupItemIdValidator _validator;
public LookupItemIdValidatorTests()
{
_mockStore = new Mock<IStore>();
_validator = new LookupItemIdValidator("dfe_country", _mockStore.Object);
_item = new LookupItem() { Id = Guid.NewGuid() };
_mockStore.Setup(m => m.GetLookupItems("dfe_country")).Returns(new List<LookupItem>() { _item }.AsQueryable());
}
[Fact]
public void IsValid_WhenValidId_ReturnsTrue()
{
var selector = ValidatorOptions.ValidatorSelectors.DefaultValidatorSelectorFactory();
var validationContext = new ValidationContext(_item.Id, new PropertyChain(), selector);
var propertyValidatorContext = new PropertyValidatorContext(validationContext, PropertyRule.Create<Guid, Guid>(t => t), "Prop");
var errors = _validator.Validate(propertyValidatorContext);
errors.Should().BeEmpty();
}
[Fact]
public void IsValid_WhenInvalidId_ReturnsFalse()
{
var selector = ValidatorOptions.ValidatorSelectors.DefaultValidatorSelectorFactory();
var validationContext = new ValidationContext(Guid.NewGuid(), new PropertyChain(), selector);
var propertyValidatorContext = new PropertyValidatorContext(validationContext, PropertyRule.Create<Guid, Guid>(t => t), "Prop");
var errors = _validator.Validate(propertyValidatorContext);
errors.Should().NotBeEmpty();
errors.First().ErrorMessage.Should().Equals("Prop must be a valid dfe_country item.");
}
}
}
| 37.701754 | 140 | 0.694742 | [
"MIT"
] | uk-gov-mirror/DFE-Digital.get-into-teaching-api | GetIntoTeachingApiTests/Validators/LookupItemIdValidatorTests.cs | 2,151 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Core;
namespace Azure.ResourceManager.Network
{
/// <summary> A class representing collection of VirtualApplianceSite and their operations over its parent. </summary>
public partial class VirtualApplianceSiteCollection : ArmCollection, IEnumerable<VirtualApplianceSite>, IAsyncEnumerable<VirtualApplianceSite>
{
private readonly ClientDiagnostics _virtualApplianceSiteClientDiagnostics;
private readonly VirtualApplianceSitesRestOperations _virtualApplianceSiteRestClient;
/// <summary> Initializes a new instance of the <see cref="VirtualApplianceSiteCollection"/> class for mocking. </summary>
protected VirtualApplianceSiteCollection()
{
}
/// <summary> Initializes a new instance of the <see cref="VirtualApplianceSiteCollection"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the parent resource that is the target of operations. </param>
internal VirtualApplianceSiteCollection(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_virtualApplianceSiteClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Network", VirtualApplianceSite.ResourceType.Namespace, DiagnosticOptions);
Client.TryGetApiVersion(VirtualApplianceSite.ResourceType, out string virtualApplianceSiteApiVersion);
_virtualApplianceSiteRestClient = new VirtualApplianceSitesRestOperations(_virtualApplianceSiteClientDiagnostics, Pipeline, DiagnosticOptions.ApplicationId, BaseUri, virtualApplianceSiteApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != NetworkVirtualAppliance.ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, NetworkVirtualAppliance.ResourceType), nameof(id));
}
/// <summary> Creates or updates the specified Network Virtual Appliance Site. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="siteName"> The name of the site. </param>
/// <param name="parameters"> Parameters supplied to the create or update Network Virtual Appliance Site operation. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="siteName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="siteName"/> or <paramref name="parameters"/> is null. </exception>
public async virtual Task<ArmOperation<VirtualApplianceSite>> CreateOrUpdateAsync(bool waitForCompletion, string siteName, VirtualApplianceSiteData parameters, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(siteName, nameof(siteName));
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var scope = _virtualApplianceSiteClientDiagnostics.CreateScope("VirtualApplianceSiteCollection.CreateOrUpdate");
scope.Start();
try
{
var response = await _virtualApplianceSiteRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, siteName, parameters, cancellationToken).ConfigureAwait(false);
var operation = new NetworkArmOperation<VirtualApplianceSite>(new VirtualApplianceSiteOperationSource(Client), _virtualApplianceSiteClientDiagnostics, Pipeline, _virtualApplianceSiteRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, siteName, parameters).Request, response, OperationFinalStateVia.AzureAsyncOperation);
if (waitForCompletion)
await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Creates or updates the specified Network Virtual Appliance Site. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="siteName"> The name of the site. </param>
/// <param name="parameters"> Parameters supplied to the create or update Network Virtual Appliance Site operation. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="siteName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="siteName"/> or <paramref name="parameters"/> is null. </exception>
public virtual ArmOperation<VirtualApplianceSite> CreateOrUpdate(bool waitForCompletion, string siteName, VirtualApplianceSiteData parameters, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(siteName, nameof(siteName));
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var scope = _virtualApplianceSiteClientDiagnostics.CreateScope("VirtualApplianceSiteCollection.CreateOrUpdate");
scope.Start();
try
{
var response = _virtualApplianceSiteRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, siteName, parameters, cancellationToken);
var operation = new NetworkArmOperation<VirtualApplianceSite>(new VirtualApplianceSiteOperationSource(Client), _virtualApplianceSiteClientDiagnostics, Pipeline, _virtualApplianceSiteRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, siteName, parameters).Request, response, OperationFinalStateVia.AzureAsyncOperation);
if (waitForCompletion)
operation.WaitForCompletion(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets the specified Virtual Appliance Site. </summary>
/// <param name="siteName"> The name of the site. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="siteName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="siteName"/> is null. </exception>
public async virtual Task<Response<VirtualApplianceSite>> GetAsync(string siteName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(siteName, nameof(siteName));
using var scope = _virtualApplianceSiteClientDiagnostics.CreateScope("VirtualApplianceSiteCollection.Get");
scope.Start();
try
{
var response = await _virtualApplianceSiteRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, siteName, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _virtualApplianceSiteClientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new VirtualApplianceSite(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets the specified Virtual Appliance Site. </summary>
/// <param name="siteName"> The name of the site. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="siteName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="siteName"/> is null. </exception>
public virtual Response<VirtualApplianceSite> Get(string siteName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(siteName, nameof(siteName));
using var scope = _virtualApplianceSiteClientDiagnostics.CreateScope("VirtualApplianceSiteCollection.Get");
scope.Start();
try
{
var response = _virtualApplianceSiteRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, siteName, cancellationToken);
if (response.Value == null)
throw _virtualApplianceSiteClientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new VirtualApplianceSite(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Lists all Network Virtual Appliance Sites in a Network Virtual Appliance resource. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="VirtualApplianceSite" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<VirtualApplianceSite> GetAllAsync(CancellationToken cancellationToken = default)
{
async Task<Page<VirtualApplianceSite>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _virtualApplianceSiteClientDiagnostics.CreateScope("VirtualApplianceSiteCollection.GetAll");
scope.Start();
try
{
var response = await _virtualApplianceSiteRestClient.ListAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new VirtualApplianceSite(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<VirtualApplianceSite>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _virtualApplianceSiteClientDiagnostics.CreateScope("VirtualApplianceSiteCollection.GetAll");
scope.Start();
try
{
var response = await _virtualApplianceSiteRestClient.ListNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new VirtualApplianceSite(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Lists all Network Virtual Appliance Sites in a Network Virtual Appliance resource. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="VirtualApplianceSite" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<VirtualApplianceSite> GetAll(CancellationToken cancellationToken = default)
{
Page<VirtualApplianceSite> FirstPageFunc(int? pageSizeHint)
{
using var scope = _virtualApplianceSiteClientDiagnostics.CreateScope("VirtualApplianceSiteCollection.GetAll");
scope.Start();
try
{
var response = _virtualApplianceSiteRestClient.List(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new VirtualApplianceSite(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<VirtualApplianceSite> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _virtualApplianceSiteClientDiagnostics.CreateScope("VirtualApplianceSiteCollection.GetAll");
scope.Start();
try
{
var response = _virtualApplianceSiteRestClient.ListNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new VirtualApplianceSite(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Checks to see if the resource exists in azure. </summary>
/// <param name="siteName"> The name of the site. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="siteName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="siteName"/> is null. </exception>
public async virtual Task<Response<bool>> ExistsAsync(string siteName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(siteName, nameof(siteName));
using var scope = _virtualApplianceSiteClientDiagnostics.CreateScope("VirtualApplianceSiteCollection.Exists");
scope.Start();
try
{
var response = await GetIfExistsAsync(siteName, cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Checks to see if the resource exists in azure. </summary>
/// <param name="siteName"> The name of the site. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="siteName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="siteName"/> is null. </exception>
public virtual Response<bool> Exists(string siteName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(siteName, nameof(siteName));
using var scope = _virtualApplianceSiteClientDiagnostics.CreateScope("VirtualApplianceSiteCollection.Exists");
scope.Start();
try
{
var response = GetIfExists(siteName, cancellationToken: cancellationToken);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="siteName"> The name of the site. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="siteName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="siteName"/> is null. </exception>
public async virtual Task<Response<VirtualApplianceSite>> GetIfExistsAsync(string siteName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(siteName, nameof(siteName));
using var scope = _virtualApplianceSiteClientDiagnostics.CreateScope("VirtualApplianceSiteCollection.GetIfExists");
scope.Start();
try
{
var response = await _virtualApplianceSiteRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, siteName, cancellationToken: cancellationToken).ConfigureAwait(false);
if (response.Value == null)
return Response.FromValue<VirtualApplianceSite>(null, response.GetRawResponse());
return Response.FromValue(new VirtualApplianceSite(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="siteName"> The name of the site. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="siteName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="siteName"/> is null. </exception>
public virtual Response<VirtualApplianceSite> GetIfExists(string siteName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(siteName, nameof(siteName));
using var scope = _virtualApplianceSiteClientDiagnostics.CreateScope("VirtualApplianceSiteCollection.GetIfExists");
scope.Start();
try
{
var response = _virtualApplianceSiteRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, siteName, cancellationToken: cancellationToken);
if (response.Value == null)
return Response.FromValue<VirtualApplianceSite>(null, response.GetRawResponse());
return Response.FromValue(new VirtualApplianceSite(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
IEnumerator<VirtualApplianceSite> IEnumerable<VirtualApplianceSite>.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IAsyncEnumerator<VirtualApplianceSite> IAsyncEnumerable<VirtualApplianceSite>.GetAsyncEnumerator(CancellationToken cancellationToken)
{
return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken);
}
}
}
| 56.109859 | 372 | 0.6543 | [
"MIT"
] | vidai-msft/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/VirtualApplianceSiteCollection.cs | 19,919 | C# |
// Copyright 2018-2020 Finbuckle LLC, Andrew White, and Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Finbuckle.MultiTenant.Options
{
interface ITenantConfigureOptions<TOptions, TTenantInfo>
where TOptions : class, new()
where TTenantInfo : class, ITenantInfo, new()
{
void Configure(TOptions options, TTenantInfo tenantInfo);
}
} | 40.695652 | 78 | 0.708333 | [
"Apache-2.0"
] | 861191244/Finbuckle.MultiTenant | src/Finbuckle.MultiTenant/Options/ITenantConfigureOptions.cs | 938 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Adapters;
using Microsoft.Recognizers.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Bot.Builder.Dialogs.Tests
{
[TestClass]
public class WaterfallTests
{
[TestMethod]
public async Task Waterfall()
{
TestAdapter adapter = new TestAdapter()
.Use(new ConversationState<Dictionary<string, object>>(new MemoryStorage()));
await new TestFlow(adapter, async (turnContext) =>
{
var waterfall = new Waterfall(new WaterfallStep[]
{
async (dc, args, next) => { await dc.Context.SendActivityAsync("step1"); },
async (dc, args, next) => { await dc.Context.SendActivityAsync("step2"); },
async (dc, args, next) => { await dc.Context.SendActivityAsync("step3"); },
});
var state = ConversationState<Dictionary<string, object>>.Get(turnContext);
var dialogCompletion = await waterfall.Continue(turnContext, state);
if (!dialogCompletion.IsActive && !dialogCompletion.IsCompleted)
{
await waterfall.Begin(turnContext, state);
}
})
.Send("hello")
.AssertReply("step1")
.Send("hello")
.AssertReply("step2")
.Send("hello")
.AssertReply("step3")
.StartTestAsync();
}
[TestMethod]
public async Task WaterfallPrompt()
{
TestAdapter adapter = new TestAdapter()
.Use(new ConversationState<Dictionary<string, object>>(new MemoryStorage()));
await new TestFlow(adapter, async (turnContext) =>
{
var dialogs = new DialogSet();
dialogs.Add("test-waterfall", Create_Waterfall2());
dialogs.Add("number", new NumberPrompt<int>(Culture.English));
var state = ConversationState<Dictionary<string, object>>.Get(turnContext);
var dc = dialogs.CreateContext(turnContext, state);
await dc.Continue();
if (!turnContext.Responded)
{
await dc.Begin("test-waterfall");
}
})
.Send("hello")
.AssertReply("step1")
.AssertReply("Enter a number.")
.Send("hello again")
.AssertReply("It must be a number")
.Send("42")
.AssertReply("Thanks for '42'")
.AssertReply("step2")
.AssertReply("Enter a number.")
.Send("apple")
.AssertReply("It must be a number")
.Send("orange")
.AssertReply("It must be a number")
.Send("64")
.AssertReply("Thanks for '64'")
.AssertReply("step3")
.StartTestAsync();
}
private static WaterfallStep[] Create_Waterfall2()
{
return new WaterfallStep[] {
Waterfall2_Step1,
Waterfall2_Step2,
Waterfall2_Step3
};
}
private static async Task Waterfall2_Step1(DialogContext dc, object args, SkipStepFunction next)
{
await dc.Context.SendActivityAsync("step1");
await dc.Prompt("number", "Enter a number.", new PromptOptions { RetryPromptString = "It must be a number" });
}
private static async Task Waterfall2_Step2(DialogContext dc, object args, SkipStepFunction next)
{
if (args != null)
{
var numberResult = (NumberResult<int>)args;
await dc.Context.SendActivityAsync($"Thanks for '{numberResult.Value}'");
}
await dc.Context.SendActivityAsync("step2");
await dc.Prompt("number", "Enter a number.", new PromptOptions { RetryPromptString = "It must be a number" });
}
private static async Task Waterfall2_Step3(DialogContext dc, object args, SkipStepFunction next)
{
if (args != null)
{
var numberResult = (NumberResult<int>)args;
await dc.Context.SendActivityAsync($"Thanks for '{numberResult.Value}'");
}
await dc.Context.SendActivityAsync("step3");
await dc.End(new Dictionary<string, object> { { "Value", "All Done!" } });
}
[TestMethod]
public async Task WaterfallNested()
{
TestAdapter adapter = new TestAdapter()
.Use(new ConversationState<Dictionary<string, object>>(new MemoryStorage()));
await new TestFlow(adapter, async (turnContext) =>
{
var dialogs = new DialogSet();
dialogs.Add("test-waterfall-a", Create_Waterfall3());
dialogs.Add("test-waterfall-b", Create_Waterfall4());
dialogs.Add("test-waterfall-c", Create_Waterfall5());
var state = ConversationState<Dictionary<string, object>>.Get(turnContext);
var dc = dialogs.CreateContext(turnContext, state);
await dc.Continue();
if (!turnContext.Responded)
{
await dc.Begin("test-waterfall-a");
}
})
.Send("hello")
.AssertReply("step1")
.AssertReply("step1.1")
.Send("hello")
.AssertReply("step1.2")
.Send("hello")
.AssertReply("step2")
.AssertReply("step2.1")
.Send("hello")
.AssertReply("step2.2")
.StartTestAsync();
}
private static WaterfallStep[] Create_Waterfall3()
{
return new WaterfallStep[] {
Waterfall3_Step1,
Waterfall3_Step2
};
}
private static WaterfallStep[] Create_Waterfall4()
{
return new WaterfallStep[] {
Waterfall4_Step1,
Waterfall4_Step2
};
}
private static WaterfallStep[] Create_Waterfall5()
{
return new WaterfallStep[] {
Waterfall5_Step1,
Waterfall5_Step2
};
}
private static async Task Waterfall3_Step1(DialogContext dc, object args, SkipStepFunction next)
{
await dc.Context.SendActivityAsync("step1");
await dc.Begin("test-waterfall-b");
}
private static async Task Waterfall3_Step2(DialogContext dc, object args, SkipStepFunction next)
{
await dc.Context.SendActivityAsync("step2");
await dc.Begin("test-waterfall-c");
}
private static async Task Waterfall4_Step1(DialogContext dc, object args, SkipStepFunction next)
{
await dc.Context.SendActivityAsync("step1.1");
}
private static async Task Waterfall4_Step2(DialogContext dc, object args, SkipStepFunction next)
{
await dc.Context.SendActivityAsync("step1.2");
}
private static async Task Waterfall5_Step1(DialogContext dc, object args, SkipStepFunction next)
{
await dc.Context.SendActivityAsync("step2.1");
}
private static async Task Waterfall5_Step2(DialogContext dc, object args, SkipStepFunction next)
{
await dc.Context.SendActivityAsync("step2.2");
await dc.End();
}
}
}
| 36.549296 | 122 | 0.548748 | [
"MIT"
] | fahadash/botbuilder-dotnet | tests/Microsoft.Bot.Builder.Dialogs.Tests/WaterfallTests.cs | 7,785 | 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 clouddirectory-2017-01-11.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.CloudDirectory.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CloudDirectory.Model.Internal.MarshallTransformations
{
/// <summary>
/// ListPolicyAttachments Request Marshaller
/// </summary>
public class ListPolicyAttachmentsRequestMarshaller : IMarshaller<IRequest, ListPolicyAttachmentsRequest> , 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((ListPolicyAttachmentsRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(ListPolicyAttachmentsRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.CloudDirectory");
request.Headers["Content-Type"] = "application/x-amz-json-";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-01-11";
request.HttpMethod = "POST";
string uriResourcePath = "/amazonclouddirectory/2017-01-11/policy/attachment";
request.ResourcePath = uriResourcePath;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetMaxResults())
{
context.Writer.WritePropertyName("MaxResults");
context.Writer.Write(publicRequest.MaxResults);
}
if(publicRequest.IsSetNextToken())
{
context.Writer.WritePropertyName("NextToken");
context.Writer.Write(publicRequest.NextToken);
}
if(publicRequest.IsSetPolicyReference())
{
context.Writer.WritePropertyName("PolicyReference");
context.Writer.WriteObjectStart();
var marshaller = ObjectReferenceMarshaller.Instance;
marshaller.Marshall(publicRequest.PolicyReference, context);
context.Writer.WriteObjectEnd();
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
if(publicRequest.IsSetConsistencyLevel())
request.Headers["x-amz-consistency-level"] = publicRequest.ConsistencyLevel;
if(publicRequest.IsSetDirectoryArn())
request.Headers["x-amz-data-partition"] = publicRequest.DirectoryArn;
return request;
}
private static ListPolicyAttachmentsRequestMarshaller _instance = new ListPolicyAttachmentsRequestMarshaller();
internal static ListPolicyAttachmentsRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListPolicyAttachmentsRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.031746 | 157 | 0.624946 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/CloudDirectory/Generated/Model/Internal/MarshallTransformations/ListPolicyAttachmentsRequestMarshaller.cs | 4,666 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CandleDrawer : AbstractDrawer
{
}
| 14.666667 | 42 | 0.787879 | [
"CC0-1.0"
] | GilbertoZinourov/GGJ21 | InSearchOfACat/Assets/Scripts/Interactables/CandleDrawer.cs | 132 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using SharpBrick.PoweredUp.Protocol;
using SharpBrick.PoweredUp.Utils;
namespace SharpBrick.PoweredUp
{
public class MarioHubDebug : Device, IPoweredUpDevice
{
public MarioHubDebug()
{ }
public MarioHubDebug(ILegoWirelessProtocol protocol, byte hubId, byte portId)
: base(protocol, hubId, portId)
{
}
public IEnumerable<byte[]> GetStaticPortInfoMessages(Version softwareVersion, Version hardwareVersion, SystemType systemType)
=> @"
0B-00-43-03-01-02-04-0F-00-00-00
05-00-43-03-02
11-00-44-03-00-00-43-48-41-4C-00-00-00-00-00-00-00
0E-00-44-03-00-01-00-00-00-00-00-FF-7F-47
0E-00-44-03-00-02-00-00-00-00-00-00-C8-42
0E-00-44-03-00-03-00-00-00-00-00-FF-7F-47
0A-00-44-03-00-04-6E-61-00-00
08-00-44-03-00-05-84-00
0A-00-44-03-00-80-02-01-03-00
11-00-44-03-01-00-56-45-52-53-00-00-00-00-00-00-00
0E-00-44-03-01-01-00-00-00-00-00-00-7F-43
0E-00-44-03-01-02-00-00-00-00-00-00-C8-42
0E-00-44-03-01-03-00-00-00-00-00-00-7F-43
0A-00-44-03-01-04-6E-61-00-00
08-00-44-03-01-05-84-00
0A-00-44-03-01-80-04-02-0A-00
11-00-44-03-02-00-45-56-45-4E-54-53-00-00-00-00-00
0E-00-44-03-02-01-00-00-00-00-00-FF-7F-47
0E-00-44-03-02-02-00-00-00-00-00-00-C8-42
0E-00-44-03-02-03-00-00-00-00-00-FF-7F-47
0A-00-44-03-02-04-6E-61-00-00
08-00-44-03-02-05-84-00
0A-00-44-03-02-80-02-01-0A-00
11-00-44-03-03-00-44-45-42-55-47-00-00-00-00-00-00
0E-00-44-03-03-01-00-00-00-00-00-FF-7F-47
0E-00-44-03-03-02-00-00-00-00-00-00-C8-42
0E-00-44-03-03-03-00-00-00-00-00-FF-7F-47
0A-00-44-03-03-04-6E-61-00-00
08-00-44-03-03-05-84-00
0A-00-44-03-03-80-04-02-0A-00
".Trim().Split("\n").Select(s => BytesStringUtil.StringToData(s));
}
} | 32.907407 | 133 | 0.678109 | [
"MIT"
] | KeyDecoder/powered-up | src/SharpBrick.PoweredUp/Devices/MarioHubDebug.cs | 1,777 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBitcoin.RPC
{
//from rpcserver.h
public enum RPCOperations
{
getconnectioncount,
getpeerinfo,
ping,
addnode,
getaddednodeinfo,
getnettotals,
dumpprivkey,
importprivkey,
importaddress,
dumpwallet,
importwallet,
getgenerate,
setgenerate,
generate,
generatetoaddress,
getnetworkhashps,
gethashespersec,
getmininginfo,
prioritisetransaction,
getwork,
getblocktemplate,
submitblock,
estimatefee,
estimatesmartfee,
getnewaddress,
getaccountaddress,
getrawchangeaddress,
setaccount,
getaccount,
getaddressesbyaccount,
sendtoaddress,
signmessage,
verifymessage,
getreceivedbyaddress,
getreceivedbyaccount,
getaddressinfo,
getbalance,
getunconfirmedbalance,
movecmd,
sendfrom,
sendmany,
addmultisigaddress,
createmultisig,
listreceivedbyaddress,
listreceivedbyaccount,
listtransactions,
listaddressgroupings,
listsinceblock,
gettransaction,
backupwallet,
keypoolrefill,
walletpassphrase,
walletpassphrasechange,
walletlock,
encryptwallet,
validateaddress,
[Obsolete("Deprecated in Bitcoin Core 0.16.0 use getblockchaininfo, getnetworkinfo, getwalletinfo or getmininginfo instead")]
getinfo,
getwalletinfo,
getblockchaininfo,
getnetworkinfo,
getrawtransaction,
listunspent,
lockunspent,
listlockunspent,
createrawtransaction,
decoderawtransaction,
decodescript,
signrawtransaction,
sendrawtransaction,
gettxoutproof,
verifytxoutproof,
decodepsbt,
combinepsbt,
finalizepsbt,
createpsbt,
convertopsbt,
walletprocesspsbt,
walletcreatefundedpsbt,
getblockcount,
getblockfilter,
getbestblockhash,
getdifficulty,
settxfee,
getmempoolinfo,
getrawmempool,
testmempoolaccept,
getblockhash,
getblock,
gettxoutsetinfo,
gettxout,
verifychain,
getchaintips,
invalidateblock,
bumpfee,
abandontransaction,
signrawtransactionwithkey,
scantxoutset,
getmempoolentry,
stop,
uptime,
createwallet,
loadwallet,
unloadwallet,
addpeeraddress,
savemempool,
}
}
| 18.141732 | 128 | 0.729601 | [
"MIT"
] | macloviw/NBitcoin | NBitcoin/RPC/RPCOperations.cs | 2,306 | C# |
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
namespace Converto
{
public static partial class Main
{
/// <summary>
/// The ConvertTo function allows you to create an object of a different type using the matching properties of another object.
/// </summary>
/// <typeparam name="T">The type of the new object.</typeparam>
/// <param name="object">Blueprint object to use to convert to another type.</param>
/// <returns>Returns an object of a different type.</returns>
public static T ConvertTo<T>(this object @object) where T : class
{
if (@object == null)
return default;
if (@object is JObject jsonObject)
return jsonObject.ToObject<T>();
var objectTypeInfo = GetCachedTypeInfo(@object.GetType());
var targetTypeInfo = GetCachedTypeInfo(typeof(T));
var result = Activator.CreateInstance(targetTypeInfo.Type, false);
var targetPropertiesInfo = targetTypeInfo.Properties.Where(p => p.CanWrite);
foreach (var targetPropertyInfo in targetPropertiesInfo)
{
var objectPropertyInfo = objectTypeInfo.Properties.FirstOrDefault(p => p.Name == targetPropertyInfo.Name && p.CanRead);
if (objectPropertyInfo != null)
{
CopyPropertyValue(@object, objectPropertyInfo, result, targetPropertyInfo);
}
}
return (T)result;
}
/// <summary>
/// The TryConvertTo function allows you to create an object of a different type using the matching properties of another object.
/// </summary>
/// <typeparam name="T">The type of the new object.</typeparam>
/// <param name="object">Blueprint object to use to convert to another type.</param>
/// <param name="result">Returns the result of the function.</param>
/// <returns>Returns true if the ConvertTo function succeed.</returns>
public static bool TryConvertTo<T>(this object @object, out T result) where T : class
{
result = ConvertTo<T>(@object);
return result != null;
}
}
}
| 40.963636 | 137 | 0.608966 | [
"MIT"
] | Odonno/Converto | Converto/Main.ConvertTo.cs | 2,255 | C# |
#pragma checksum "..\..\UserControl1.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "A6E2AC39FB946193F82764287806E9A9F6AD2E66F40E80294E69AE4811F1AD55"
//------------------------------------------------------------------------------
// <auto-generated>
// Este código fue generado por una herramienta.
// Versión de runtime:4.0.30319.42000
//
// Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
// se vuelve a generar el código.
// </auto-generated>
//------------------------------------------------------------------------------
using ControlDeVentana;
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;
namespace ControlDeVentana {
/// <summary>
/// ControlVentana
/// </summary>
public partial class ControlVentana : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector {
#line 164 "..\..\UserControl1.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Grid grMain;
#line default
#line hidden
#line 165 "..\..\UserControl1.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button btMinimizar;
#line default
#line hidden
#line 166 "..\..\UserControl1.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button btMaximizar;
#line default
#line hidden
#line 167 "..\..\UserControl1.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button btRestaurar;
#line default
#line hidden
#line 168 "..\..\UserControl1.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button btCerrar;
#line default
#line hidden
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/ControlDeVentana;component/usercontrol1.xaml", System.UriKind.Relative);
#line 1 "..\..\UserControl1.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
switch (connectionId)
{
case 1:
this.grMain = ((System.Windows.Controls.Grid)(target));
return;
case 2:
this.btMinimizar = ((System.Windows.Controls.Button)(target));
#line 165 "..\..\UserControl1.xaml"
this.btMinimizar.Click += new System.Windows.RoutedEventHandler(this.btMinimizar_Click);
#line default
#line hidden
return;
case 3:
this.btMaximizar = ((System.Windows.Controls.Button)(target));
#line 166 "..\..\UserControl1.xaml"
this.btMaximizar.Click += new System.Windows.RoutedEventHandler(this.btMaximizar_Click);
#line default
#line hidden
return;
case 4:
this.btRestaurar = ((System.Windows.Controls.Button)(target));
#line 167 "..\..\UserControl1.xaml"
this.btRestaurar.Click += new System.Windows.RoutedEventHandler(this.btRestaurar_Click);
#line default
#line hidden
return;
case 5:
this.btCerrar = ((System.Windows.Controls.Button)(target));
#line 168 "..\..\UserControl1.xaml"
this.btCerrar.Click += new System.Windows.RoutedEventHandler(this.btCerrar_Click);
#line default
#line hidden
return;
}
this._contentLoaded = true;
}
}
}
| 38.487342 | 151 | 0.624897 | [
"MIT"
] | O-Debegnach/Supervisor-de-Comercio | ControlDeVentana/obj/Debug/UserControl1.g.i.cs | 6,088 | C# |
using Microsoft.AspNetCore.Mvc;
using SocialNetwork.Business.Contracts.ViewModels;
namespace SocialNetwork.Controllers
{
public class ProfileController : Controller
{
[HttpGet]
public IActionResult Edit()
{
return View();
}
[HttpPost]
public IActionResult Edit(EditProfileViewModel viewModel)
{
return RedirectToAction("Index", "Home");
}
}
}
| 21.238095 | 65 | 0.61435 | [
"MIT"
] | EugeneLevchenkov/Learn-ASP.NET-Core | SocialNetwork/src/SocialNetwork/Controllers/ProfileController.cs | 448 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Linguistics.Core
{
[Serializable]
public class EntityTypeStructure
{
public EntityType? EntityType { get; set; }
public string CustomType { get; set; }
public string GetFullType()
{
if (EntityType.HasValue)
return EntityType.Value.ToString();
return CustomType;
}
}
}
| 17.173913 | 45 | 0.718987 | [
"MIT"
] | elzin/SentimentAnalysisService | Sources/Core/csharp/Linguistics.Core/Entity/EntityTypeStructure.cs | 397 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v6/enums/policy_topic_evidence_destination_not_working_dns_error_type.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Ads.GoogleAds.V6.Enums {
/// <summary>Holder for reflection information generated from google/ads/googleads/v6/enums/policy_topic_evidence_destination_not_working_dns_error_type.proto</summary>
public static partial class PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeReflection {
#region Descriptor
/// <summary>File descriptor for google/ads/googleads/v6/enums/policy_topic_evidence_destination_not_working_dns_error_type.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CmBnb29nbGUvYWRzL2dvb2dsZWFkcy92Ni9lbnVtcy9wb2xpY3lfdG9waWNf",
"ZXZpZGVuY2VfZGVzdGluYXRpb25fbm90X3dvcmtpbmdfZG5zX2Vycm9yX3R5",
"cGUucHJvdG8SHWdvb2dsZS5hZHMuZ29vZ2xlYWRzLnY2LmVudW1zGhxnb29n",
"bGUvYXBpL2Fubm90YXRpb25zLnByb3RvIscBCjhQb2xpY3lUb3BpY0V2aWRl",
"bmNlRGVzdGluYXRpb25Ob3RXb3JraW5nRG5zRXJyb3JUeXBlRW51bSKKAQo0",
"UG9saWN5VG9waWNFdmlkZW5jZURlc3RpbmF0aW9uTm90V29ya2luZ0Ruc0Vy",
"cm9yVHlwZRIPCgtVTlNQRUNJRklFRBAAEgsKB1VOS05PV04QARIWChJIT1NU",
"TkFNRV9OT1RfRk9VTkQQAhIcChhHT09HTEVfQ1JBV0xFUl9ETlNfSVNTVUUQ",
"A0KOAgohY29tLmdvb2dsZS5hZHMuZ29vZ2xlYWRzLnY2LmVudW1zQjlQb2xp",
"Y3lUb3BpY0V2aWRlbmNlRGVzdGluYXRpb25Ob3RXb3JraW5nRG5zRXJyb3JU",
"eXBlUHJvdG9QAVpCZ29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xl",
"YXBpcy9hZHMvZ29vZ2xlYWRzL3Y2L2VudW1zO2VudW1zogIDR0FBqgIdR29v",
"Z2xlLkFkcy5Hb29nbGVBZHMuVjYuRW51bXPKAh1Hb29nbGVcQWRzXEdvb2ds",
"ZUFkc1xWNlxFbnVtc+oCIUdvb2dsZTo6QWRzOjpHb29nbGVBZHM6OlY2OjpF",
"bnVtc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V6.Enums.PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum), global::Google.Ads.GoogleAds.V6.Enums.PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V6.Enums.PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum.Types.PolicyTopicEvidenceDestinationNotWorkingDnsErrorType) }, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Container for enum describing possible policy topic evidence destination not
/// working DNS error types.
/// </summary>
public sealed partial class PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum : pb::IMessage<PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum> _parser = new pb::MessageParser<PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum>(() => new PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Ads.GoogleAds.V6.Enums.PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum(PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum other) : this() {
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum Clone() {
return new PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum other) {
if (other == null) {
return;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// The possible policy topic evidence destination not working DNS error types.
/// </summary>
public enum PolicyTopicEvidenceDestinationNotWorkingDnsErrorType {
/// <summary>
/// No value has been specified.
/// </summary>
[pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// The received value is not known in this version.
///
/// This is a response-only value.
/// </summary>
[pbr::OriginalName("UNKNOWN")] Unknown = 1,
/// <summary>
/// Host name not found in DNS when fetching landing page.
/// </summary>
[pbr::OriginalName("HOSTNAME_NOT_FOUND")] HostnameNotFound = 2,
/// <summary>
/// Google internal crawler issue when communicating with DNS. This error
/// doesn't mean the landing page doesn't work. Google will recrawl the
/// landing page.
/// </summary>
[pbr::OriginalName("GOOGLE_CRAWLER_DNS_ISSUE")] GoogleCrawlerDnsIssue = 3,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| 41.765217 | 444 | 0.729336 | [
"Apache-2.0"
] | GraphikaPS/google-ads-dotnet | src/V6/Types/PolicyTopicEvidenceDestinationNotWorkingDnsErrorType.cs | 9,606 | C# |
using System;
using System.Web.Http;
using System.Web.Mvc;
using BooksService.Areas.HelpPage.ModelDescriptions;
using BooksService.Areas.HelpPage.Models;
namespace BooksService.Areas.HelpPage.Controllers
{
/// <summary>
/// The controller that will handle requests for the help page.
/// </summary>
public class HelpController : Controller
{
private const string ErrorViewName = "Error";
public HelpController()
: this(GlobalConfiguration.Configuration)
{
}
public HelpController(HttpConfiguration config)
{
Configuration = config;
}
public HttpConfiguration Configuration { get; private set; }
public ActionResult Index()
{
ViewBag.DocumentationProvider = Configuration.Services.GetDocumentationProvider();
return View(Configuration.Services.GetApiExplorer().ApiDescriptions);
}
public ActionResult Api(string apiId)
{
if (!String.IsNullOrEmpty(apiId))
{
HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId);
if (apiModel != null)
{
return View(apiModel);
}
}
return View(ErrorViewName);
}
public ActionResult ResourceModel(string modelName)
{
if (!String.IsNullOrEmpty(modelName))
{
ModelDescriptionGenerator modelDescriptionGenerator = Configuration.GetModelDescriptionGenerator();
ModelDescription modelDescription;
if (modelDescriptionGenerator.GeneratedModels.TryGetValue(modelName, out modelDescription))
{
return View(modelDescription);
}
}
return View(ErrorViewName);
}
}
} | 30.079365 | 115 | 0.598417 | [
"MIT"
] | CNinnovation/azureandwebservices | webapi/BooksService/BooksService/Areas/HelpPage/Controllers/HelpController.cs | 1,895 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace MakersOfDenmark.Domain.Models
{
public class Event : Entity<Guid>
{
public string Address { get; set; }
public string Title { get; set; }
public string Start { get; set; }
public string End { get; set; }
public string Description { get; set; }
public ICollection<User> Participants { get; set; } = new List<User>();
public string Badge { get; set; }
public MakerSpace MakerSpace { get; set; }
public Guid MakerSpaceId { get; set; }
}
}
| 29.95 | 79 | 0.619366 | [
"Apache-2.0"
] | julian-code/makersofdenmark | src/MakersOfDenmark.Domain/Models/Event.cs | 601 | C# |
using Newtonsoft.Json;
using Umbraco.Cms.Infrastructure.Serialization;
namespace Umbraco.Cms.Core.Models.Blocks
{
/// <summary>
/// Used for deserializing the block list layout
/// </summary>
public class BlockListLayoutItem
{
[JsonProperty("contentUdi", Required = Required.Always)]
[JsonConverter(typeof(UdiJsonConverter))]
public Udi ContentUdi { get; set; }
[JsonProperty("settingsUdi", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(UdiJsonConverter))]
public Udi SettingsUdi { get; set; }
}
}
| 29.8 | 83 | 0.681208 | [
"MIT"
] | Ambertvu/Umbraco-CMS | src/Umbraco.Infrastructure/Models/Blocks/BlockListLayoutItem.cs | 598 | C# |
using FriendOrganizer.UI.Event;
using Prism.Commands;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace FriendOrganizer.UI.ViewModel
{
public class NavigationItemViewModel : ViewModelBase
{
private IEventAggregator _eventAggregator;
private string _displayMember;
public int Id { get; }
private string _detailViewModelName;
public string DisplayMember
{
get { return _displayMember; }
set
{
_displayMember = value;
OnPropertyChanged();
}
}
public ICommand OpenDetailViewCommand { get; }
public NavigationItemViewModel(int id, string displayMember, IEventAggregator eventAggregator,
string detailViewModelName)
{
_eventAggregator = eventAggregator;
DisplayMember = displayMember;
Id = id;
_detailViewModelName = detailViewModelName;
OpenDetailViewCommand = new DelegateCommand(OnOpenDetailViewExecute);
}
private void OnOpenDetailViewExecute()
{
_eventAggregator.GetEvent<OpenDetailViewEvent>()
.Publish(new OpenDetailViewEventArgs
{
Id = Id,
ViewModelName = _detailViewModelName
});
}
}
}
| 27.464286 | 102 | 0.596229 | [
"MIT"
] | PezeM/FriendOrganizer | FriendOrganizer.UI/ViewModel/NavigationItemViewModel.cs | 1,540 | C# |
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.SpacingRules
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using StyleCop.Analyzers.SpacingRules;
using Xunit;
using static StyleCop.Analyzers.Test.Verifiers.StyleCopCodeFixVerifier<
StyleCop.Analyzers.SpacingRules.SA1020IncrementDecrementSymbolsMustBeSpacedCorrectly,
StyleCop.Analyzers.SpacingRules.TokenSpacingCodeFixProvider>;
/// <summary>
/// Unit tests for <see cref="SA1020IncrementDecrementSymbolsMustBeSpacedCorrectly"/>.
/// </summary>
public class SA1020UnitTests
{
/// <summary>
/// Verifies that the analyzer will properly valid symbol spacing.
/// </summary>
/// <param name="symbol">The operator to test.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Theory]
[InlineData("++")]
[InlineData("--")]
public async Task TestValidSymbolSpacingAsync(string symbol)
{
var testCode = $@"
class ClassName
{{
void MethodName()
{{
int x = 0;
x{symbol};
{symbol}x;
for (int y = 0; y < 30; {symbol}x, y{symbol})
{{
}}
}}
}}
";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
/// <summary>
/// Verifies that the analyzer will properly invalid symbol spacing.
/// </summary>
/// <param name="symbol">The operator to test.</param>
/// <param name="symbolName">The name of the symbol, as it appears in diagnostics.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Theory]
[InlineData("++", "Increment")]
[InlineData("--", "Decrement")]
public async Task TestInvalidSymbolSpacingAsync(string symbol, string symbolName)
{
var testCode = $@"
class ClassName
{{
void MethodName()
{{
int x = 0;
x {symbol};
{symbol} x;
for (int y = 0; y < 30; {symbol} x, y {symbol})
{{
}}
x
{symbol};
{symbol}
x;
for (int y = 0; y < 30; {symbol}
x,
y
{symbol})
{{
}}
}}
}}
";
var fixedCode = $@"
class ClassName
{{
void MethodName()
{{
int x = 0;
x{symbol};
{symbol}x;
for (int y = 0; y < 30; {symbol}x, y{symbol})
{{
}}
x{symbol};
{symbol}x;
for (int y = 0; y < 30; {symbol}x,
y{symbol})
{{
}}
}}
}}
";
DiagnosticResult[] expected =
{
Diagnostic().WithLocation(7, 11).WithArguments(symbolName, symbol, "preceded"),
Diagnostic().WithLocation(8, 9).WithArguments(symbolName, symbol, "followed"),
Diagnostic().WithLocation(9, 33).WithArguments(symbolName, symbol, "followed"),
Diagnostic().WithLocation(9, 41).WithArguments(symbolName, symbol, "preceded"),
Diagnostic().WithLocation(14, 9).WithArguments(symbolName, symbol, "preceded"),
Diagnostic().WithLocation(15, 9).WithArguments(symbolName, symbol, "followed"),
Diagnostic().WithLocation(17, 33).WithArguments(symbolName, symbol, "followed"),
Diagnostic().WithLocation(20, 13).WithArguments(symbolName, symbol, "preceded"),
};
await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false);
}
}
}
| 31.691057 | 143 | 0.578245 | [
"MIT"
] | AraHaan/StyleCopAnalyzers | StyleCop.Analyzers/StyleCop.Analyzers.Test/SpacingRules/SA1020UnitTests.cs | 3,900 | C# |
using Reductech.Sequence.Core.Steps;
namespace Reductech.Sequence.Connectors.Nuix.Tests.Steps;
public partial class NuixCountItemsTests : NuixStepTestBase<NuixCountItems, SCLInt>
{
/// <inheritdoc />
protected override IEnumerable<NuixIntegrationTestCase> NuixTestCases
{
get
{
yield return new NuixIntegrationTestCase(
"Ingest and count items",
SetupCase,
new AssertTrue
{
Boolean = new Equals<SCLInt>
{
Terms = new ArrayNew<SCLInt>
{
Elements = new List<IStep<SCLInt>>
{
Constant(1),
new NuixCountItems
{
SearchTerm = Constant("jellyfish"),
SearchOptions = Constant(
Entity.Create(
("defaultFields", new[] { "name" })
)
)
}
}
}
}
},
CleanupCase
);
}
}
}
| 33.214286 | 83 | 0.355556 | [
"Apache-2.0"
] | reductech/Nuix | Nuix.Tests/Steps/NuixCountItemsTests.cs | 1,397 | C# |
//------------------------------------------------------------------------------
// <自动生成>
// 此代码由工具生成。
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </自动生成>
//------------------------------------------------------------------------------
namespace MxWeiXinPF.Web.api.payment.wxpay {
public partial class feedback {
}
}
| 22.5 | 81 | 0.319444 | [
"MIT"
] | herrylau/wwzkushop | MxWeiXinPF.Web/api/payment/wxpay/feedback.aspx.designer.cs | 474 | C# |
using NUnit.Framework;
using NUnit.Framework.Constraints;
using System;
using System.Drawing;
using System.IO;
namespace ThermalTalk.Imaging.Test
{
[TestFixture]
public class PrintImageTests
{
private const string baseDir = "test_data";
[OneTimeSetUp]
public void Setup()
{
var dir = Path.GetDirectoryName(typeof(PrintImageTests).Assembly.Location);
Directory.SetCurrentDirectory(dir);
if (Directory.Exists(baseDir))
{
Directory.Delete(baseDir, true);
}
Directory.CreateDirectory(baseDir);
}
[OneTimeTearDown]
public void TearDown()
{
if (Directory.Exists(baseDir))
{
Directory.Delete(baseDir, true);
}
}
[Test()]
public void ApplyColorInversionTest()
{
// Input are expected are provided as resources, dithered is what
// we are testing
Bitmap input, inverted, expected;
input = Properties.Resources.white_bitmap;
var path = Path.Combine(baseDir, "white_inverse_test.bmp");
input.Save(path);
using (var logo = new PrinterImage(path))
{
logo.Resize(input.Width, 0, true);
Assert.IsFalse(logo.IsInverted);
logo.ApplyColorInversion();
inverted = logo.ImageData.ToBitmap();
expected = Properties.Resources.black_bitmap;
// White should ivnert to black
Assert.IsTrue(ImageTestHelpers.CompareMemCmp(expected, inverted));
Assert.True(logo.IsInverted);
// Flip back to white, test that the inversion flag is cleared
logo.ApplyColorInversion();
Assert.IsFalse(logo.IsInverted);
};
}
[Test()]
public void ResizeWidthTest()
{
// Input are expected are provided as resources, dithered is what
// we are testing
Bitmap input = Properties.Resources.white_bitmap;
using (var logo = new PrinterImage(input))
{
// Use the RoundUp method since that is done internally
// in PrinterImage. This is to allow for Assert.AreEqual tests
// First scale down by 50%
var shrink = (input.Width / 2).RoundUp(8);
var expectedH = (input.Height / 2).RoundUp(8);
logo.Resize(shrink, 0, true);
Assert.AreEqual(shrink, logo.Width);
Assert.AreEqual(expectedH, logo.Height);
// Now double in size
var grow = (input.Width * 2).RoundUp(8);
expectedH = (input.Height * 2).RoundUp(8);
logo.Resize(grow, 0, true);
Assert.AreEqual(grow, logo.Width);
Assert.AreEqual(expectedH, logo.Height);
};
}
[Test()]
public void ResizeHeightTest()
{
// Input are expected are provided as resources, dithered is what
// we are testing
Bitmap input = Properties.Resources.white_bitmap;
using (var logo = new PrinterImage(input))
{
// Use the RoundUp method since that is done internally
// in PrinterImage. This is to allow for Assert.AreEqual tests
// First scale down by 50%
var shrink = (input.Height / 2).RoundUp(8);
var expectedW = (input.Width / 2).RoundUp(8);
logo.Resize(0, shrink, true);
Assert.AreEqual(shrink, logo.Height);
Assert.AreEqual(expectedW, logo.Width);
// Now double in size
var grow = (input.Height * 2).RoundUp(8);
expectedW = (input.Width * 2).RoundUp(8);
logo.Resize(0, grow, true);
Assert.AreEqual(grow, logo.Height);
Assert.AreEqual(expectedW, logo.Width);
};
}
[Test()]
public void ResizeNoneTest()
{
// Input are expected are provided as resources, dithered is what
// we are testing
Bitmap input = Properties.Resources.white_bitmap;
using (var logo = new PrinterImage(input))
{
var oldW = logo.Width.RoundUp(8);
var oldH = logo.Height.RoundUp(8);
logo.Resize(logo.Width, logo.Height, false);
Assert.AreEqual(oldW, logo.Width);
Assert.AreEqual(oldH, logo.Height);
}
}
[Test()]
public void ResizeZeroExceptionTest()
{
Bitmap input = Properties.Resources.white_bitmap;
using (var logo = new PrinterImage(input))
{
Assert.Throws<ImagingException>(() => logo.Resize(0, 0, true));
}
using (var logo = new PrinterImage(input))
{
Assert.Throws<ImagingException>(() => logo.Resize(0, 0, false));
}
}
}
}
| 32.559006 | 90 | 0.525563 | [
"MIT"
] | Calonious/ThermalTalk | ThermalTalk.Imaging.Test/PrintImageTests.cs | 5,244 | C# |
namespace BaristaLabs.Skrapr.ChromeDevTools.Network
{
using Newtonsoft.Json;
/// <summary>
/// Returns all browser cookies for the current URL. Depending on the backend support, will return detailed cookie information in the <code>cookies</code> field.
/// </summary>
public sealed class GetCookiesCommand : ICommand
{
private const string ChromeRemoteInterface_CommandName = "Network.getCookies";
[JsonIgnore]
public string CommandName
{
get { return ChromeRemoteInterface_CommandName; }
}
/// <summary>
/// The list of URLs for which applicable cookies will be fetched
/// </summary>
[JsonProperty("urls", DefaultValueHandling = DefaultValueHandling.Ignore)]
public string[] Urls
{
get;
set;
}
}
public sealed class GetCookiesCommandResponse : ICommandResponse<GetCookiesCommand>
{
/// <summary>
/// Array of cookie objects.
///</summary>
[JsonProperty("cookies")]
public Cookie[] Cookies
{
get;
set;
}
}
} | 28.878049 | 177 | 0.59375 | [
"MIT"
] | BaristaLabs/BaristaLabs.Skrapr | src/BaristaLabs.Skrapr.ChromeDevTools/Network/GetCookiesCommand.cs | 1,184 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace cs_timed_silver
{
public class RelayCommand : ICommand
{
protected Action MyExecuteMethod;
protected Func<bool> MyCanExecuteMethod;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public RelayCommand(Action a)
{
MyExecuteMethod = a;
}
public RelayCommand(Action a, Func<bool> c)
{
MyExecuteMethod = a;
MyCanExecuteMethod = c;
}
public bool CanExecute(object parameter)
{
if (MyCanExecuteMethod != null)
{
return MyCanExecuteMethod();
}
if (MyExecuteMethod != null)
{
return true;
}
return false;
}
public void Execute(object parameter)
{
if (MyExecuteMethod != null)
{
MyExecuteMethod();
}
}
}
}
| 22.490909 | 64 | 0.533549 | [
"MIT"
] | silviubogan/timed-silver | Source/cs-timeout/WPF/RelayCommand.cs | 1,239 | C# |
using EasyChallenge.Domain.Constants;
using Newtonsoft.Json;
using System;
namespace EasyChallenge.Domain
{
public class Fund : BaseInvestment
{
[JsonProperty("capitalInvestido")]
public override decimal InvestedAmount { get; init; }
[JsonProperty("ValorAtual")]
public override decimal TotalValue { get; init; }
[JsonProperty("dataResgate")]
public override DateTime DueDate { get; init; }
[JsonProperty("dataCompra")]
public override DateTime PurchaseDate { get; init; }
public override decimal IR => Profitability() >= 0 ? Profitability() * IRPercents.FUNDS : 0;
}
}
| 28.652174 | 100 | 0.664643 | [
"MIT"
] | guilhermeor/easy_challenge | Src/EasyChallenge.Domain/Fund.cs | 661 | C# |
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace Rssdp.Infrastructure
{
/// <summary>
/// Provides the platform independent logic for publishing device existence and responding to search requests.
/// </summary>
internal sealed class SsdpCommunicationsServer : DisposableManagedObjectBase, ISsdpCommunicationsServer
{
#region Fields
/*
We could technically use one socket listening on port 1900 for everything.
This should get both multicast (notifications) and unicast (search response) messages, however
this often doesn't work under Windows because the MS SSDP service is running. If that service
is running then it will steal the unicast messages and we will never see search responses.
Since stopping the service would be a bad idea (might not be allowed security wise and might
break other apps running on the system) the only other work around is to use two sockets.
We use one socket to listen for/receive notifications and search requests (_BroadcastListenSocket).
We use a second socket, bound to a different local port, to send search requests and listen for
responses (_SendSocket). The responses are sent to the local port this socket is bound to,
which isn't port 1900 so the MS service doesn't steal them. While the caller can specify a local
port to use, we will default to 0 which allows the underlying system to auto-assign a free port.
*/
private readonly object _BroadcastListenSocketSynchroniser = new object();
private IUdpSocket _BroadcastListenSocket;
private readonly object _SendSocketSynchroniser = new object();
private IUdpSocket _SendSocket;
private HttpRequestParser _RequestParser;
private HttpResponseParser _ResponseParser;
private ISocketFactory _SocketFactory;
private readonly int _LocalPort;
private readonly int _MulticastTtl;
private bool _IsShared;
#endregion Fields
#region Events
/// <summary>
/// Raised when a HTTPU request message is received by a socket (unicast or multicast).
/// </summary>
public event EventHandler<RequestReceivedEventArgs> RequestReceived;
/// <summary>
/// Raised when an HTTPU response message is received by a socket (unicast or multicast).
/// </summary>
public event EventHandler<ResponseReceivedEventArgs> ResponseReceived;
#endregion Events
#region Public Properties
/// <summary>
/// The number of times the Udp message is sent. Any value less than 2 will result in one message being sent. SSDP spec recommends sending messages multiple times (not more than 3) to account for possible packet loss over UDP.
/// </summary>
/// <seealso cref="UdpSendDelay"/>
public int UdpSendCount { get; set; } = SsdpConstants.DefaultUdpResendCount;
/// <summary>
/// The delay between repeating messages (as specified in UdpSendCount).
/// </summary>
/// <seealso cref="UdpSendCount"/>
public TimeSpan UdpSendDelay { get; set; } = SsdpConstants.DefaultUdpResendDelay;
#endregion Public Properties
#region Constructors
/// <summary>
/// Minimum constructor.
/// </summary>
/// <param name="socketFactory">An implementation of the <see cref="ISocketFactory"/> interface that can be used to make new unicast and multicast sockets. Cannot be null.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="socketFactory"/> argument is null.</exception>
public SsdpCommunicationsServer(ISocketFactory socketFactory)
: this(socketFactory, 0, SsdpConstants.SsdpDefaultMulticastTimeToLive)
{
}
/// <summary>
/// Full constructor.
/// </summary>
/// <param name="socketFactory">An implementation of the <see cref="ISocketFactory"/> interface that can be used to make new unicast and multicast sockets. Cannot be null.</param>
/// <param name="localPort">The specific local port to use for all sockets created by this instance. Specify zero to indicate the system should choose a free port itself.</param>
/// <param name="multicastTimeToLive">The multicast time to live value for multicast sockets. Technically this is a number of router hops, not a 'Time'. Must be greater than zero.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="socketFactory"/> argument is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">The <paramref name="multicastTimeToLive"/> argument is less than or equal to zero.</exception>
public SsdpCommunicationsServer(ISocketFactory socketFactory, int localPort, int multicastTimeToLive)
{
if (socketFactory == null) throw new ArgumentNullException(nameof(socketFactory));
if (multicastTimeToLive <= 0) throw new ArgumentOutOfRangeException(nameof(multicastTimeToLive), "multicastTimeToLive must be greater than zero.");
_BroadcastListenSocketSynchroniser = new object();
_SendSocketSynchroniser = new object();
_LocalPort = localPort;
_SocketFactory = socketFactory;
_RequestParser = new HttpRequestParser();
_ResponseParser = new HttpResponseParser();
_MulticastTtl = multicastTimeToLive;
}
#endregion Constructors
#region Public Methods
/// <summary>
/// Causes the server to begin listening for multicast messages, being SSDP search requests and notifications.
/// </summary>
/// <exception cref="System.ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
public void BeginListeningForBroadcasts()
{
ThrowIfDisposed();
if (_BroadcastListenSocket == null)
{
lock (_BroadcastListenSocketSynchroniser)
{
if (_BroadcastListenSocket == null)
_BroadcastListenSocket = ListenForBroadcastsAsync();
}
}
}
/// <summary>
/// Causes the server to stop listening for multicast messages, being SSDP search requests and notifications.
/// </summary>
/// <exception cref="System.ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
public void StopListeningForBroadcasts()
{
ThrowIfDisposed();
lock (_BroadcastListenSocketSynchroniser)
{
if (_BroadcastListenSocket != null)
{
_BroadcastListenSocket.Dispose();
_BroadcastListenSocket = null;
}
}
}
/// <summary>
/// Sends a message to a particular address (uni or multicast) and port.
/// </summary>
/// <param name="messageData">A byte array containing the data to send.</param>
/// <param name="destination">A <see cref="UdpEndPoint"/> representing the destination address for the data. Can be either a multicast or unicast destination.</param>
/// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="messageData"/> argument is null.</exception>
/// <exception cref="System.ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
public void SendMessage(byte[] messageData, UdpEndPoint destination)
{
if (messageData == null) throw new ArgumentNullException(nameof(messageData));
ThrowIfDisposed();
EnsureSendSocketCreated();
// SSDP spec recommends sending messages multiple times (not more than 3) to account for possible packet loss over UDP.
Repeat(UdpSendCount, UdpSendDelay, () =>
{
SendMessageIfSocketNotDisposed(messageData, destination);
});
}
/// <summary>
/// Stops listening for search responses on the local, unicast socket.
/// </summary>
/// <exception cref="System.ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
public void StopListeningForResponses()
{
ThrowIfDisposed();
lock (_SendSocketSynchroniser)
{
var socket = _SendSocket;
_SendSocket = null;
if (socket != null)
socket.Dispose();
}
}
#endregion Public Methods
#region Public Properties
/// <summary>
/// Gets or sets a boolean value indicating whether or not this instance is shared amongst multiple <see cref="SsdpDeviceLocatorBase"/> and/or <see cref="ISsdpDevicePublisher"/> instances.
/// </summary>
/// <remarks>
/// <para>If true, disposing an instance of a <see cref="SsdpDeviceLocatorBase"/>or a <see cref="ISsdpDevicePublisher"/> will not dispose this comms server instance. The calling code is responsible for managing the lifetime of the server.</para>
/// </remarks>
public bool IsShared
{
get { return _IsShared; }
set { _IsShared = value; }
}
/// <summary>
/// What type of sockets will be created: ipv6 or ipv4
/// </summary>
public DeviceNetworkType DeviceNetworkType { get { return _SocketFactory.DeviceNetworkType; } }
#endregion Public Properties
#region Overrides
/// <summary>
/// Stops listening for requests, disposes this instance and all internal resources.
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
lock (_BroadcastListenSocketSynchroniser)
{
if (_BroadcastListenSocket != null)
_BroadcastListenSocket.Dispose();
}
lock (_SendSocketSynchroniser)
{
if (_SendSocket != null)
_SendSocket.Dispose();
}
}
}
#endregion Overrides
#region Private Methods
private void SendMessageIfSocketNotDisposed(byte[] messageData, UdpEndPoint destination)
{
var socket = _SendSocket;
if (socket != null)
{
_SendSocket.SendTo(messageData, destination);
}
else
{
ThrowIfDisposed();
}
}
private static void Repeat(int repetitions, TimeSpan delay, Action work)
{
if (repetitions < 2)
repetitions = 1;
for (int cnt = 0; cnt < repetitions; cnt++)
{
work();
if (delay != TimeSpan.Zero)
TaskEx.Delay(delay).Wait();
}
}
private IUdpSocket ListenForBroadcastsAsync()
{
var socket = _SocketFactory.CreateUdpMulticastSocket(_MulticastTtl, SsdpConstants.MulticastPort);
ListenToSocket(socket);
return socket;
}
private IUdpSocket CreateSocketAndListenForResponsesAsync()
{
_SendSocket = _SocketFactory.CreateUdpSocket(_LocalPort);
ListenToSocket(_SendSocket);
return _SendSocket;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capturing task to local variable removes compiler warning, task is not otherwise required.")]
private async void ListenToSocket(IUdpSocket socket)
{
// Tasks are captured to local variables even if we don't use them just to avoid compiler warnings.
try
{
await TaskEx.Run(async () =>
{
var cancelled = false;
while (!cancelled)
{
try
{
var result = await socket.ReceiveAsync().ConfigureAwait(false);
if (result.ReceivedBytes > 0)
{
// Strange cannot convert compiler error here if I don't explicitly
// assign or cast to Action first. Assignment is easier to read,
// so went with that.
Action processWork = () => ProcessMessage(System.Text.Encoding.UTF8.GetString(result.Buffer, 0, result.ReceivedBytes), result.ReceivedFrom);
var processTask = TaskEx.Run(processWork);
}
}
catch (SocketClosedException)
{
if (IsDisposed) return; //No error or reconnect if we're shutdown.
await ReconnectBroadcastListeningSocket().ConfigureAwait(false);
cancelled = true;
break;
}
catch (Exception)
{
cancelled = true;
}
}
}).ConfigureAwait(false);
}
catch
{
if (IsDisposed) return;
await ReconnectBroadcastListeningSocket().ConfigureAwait(false);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private async Task ReconnectBroadcastListeningSocket()
{
var success = false;
while (!success)
{
try
{
var oldSocket = _BroadcastListenSocket;
_BroadcastListenSocket = null;
BeginListeningForBroadcasts();
try
{
oldSocket?.Dispose();
}
catch { }
success = true;
break;
}
catch
{
await TaskEx.Delay(30000).ConfigureAwait(false);
}
}
}
private void EnsureSendSocketCreated()
{
if (_SendSocket == null)
{
lock (_SendSocketSynchroniser)
{
if (_SendSocket == null)
_SendSocket = CreateSocketAndListenForResponsesAsync();
}
}
}
private void ProcessMessage(string data, UdpEndPoint endPoint)
{
//Responses start with the HTTP version, prefixed with HTTP/ while
//requests start with a method which can vary and might be one we haven't
//seen/don't know. We'll check if this message is a request or a response
//by checking for the static HTTP/ prefix on the start of the message.
if (data.StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase))
{
HttpResponseMessage responseMessage = null;
try
{
responseMessage = _ResponseParser.Parse(data);
}
catch (ArgumentException) { } // Ignore invalid packets.
catch (FormatException) { } // Ignore invalid packets.
if (responseMessage != null)
OnResponseReceived(responseMessage, endPoint);
}
else
{
HttpRequestMessage requestMessage = null;
try
{
requestMessage = _RequestParser.Parse(data);
}
catch (ArgumentException) { } // Ignore invalid packets.
catch (FormatException) { } // Ignore invalid packets.
if (requestMessage != null)
OnRequestReceived(requestMessage, endPoint);
}
}
private void OnRequestReceived(HttpRequestMessage data, UdpEndPoint endPoint)
{
var handlers = RequestReceived;
if (handlers != null)
handlers(this, new RequestReceivedEventArgs(data, endPoint));
}
private void OnResponseReceived(HttpResponseMessage data, UdpEndPoint endPoint)
{
var handlers = ResponseReceived;
if (handlers != null)
handlers(this, new ResponseReceivedEventArgs(data, endPoint));
}
#endregion Private Methods
}
} | 41.163551 | 253 | 0.588092 | [
"MIT"
] | dk307/HSPI_RemoteHelper | Roku/ssdp/SsdpCommunicationsServer.cs | 17,620 | C# |
using CoinGecko.Interfaces;
using Cryptofolio.Collector.Job.Data;
using Cryptofolio.Infrastructure;
using Cryptofolio.Infrastructure.Data;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace Cryptofolio.Collector.Job.IntegrationTests.Data
{
public class ExchangeDataRequestHandlerTests : IClassFixture<WebApplicationFactory>, IDisposable
{
private readonly IServiceScope _scope;
private readonly ExchangeDataRequestHandler _handler;
private readonly IExchangesClient _exchangesClient;
private readonly CryptofolioContext _context;
public ExchangeDataRequestHandlerTests(WebApplicationFactory factory)
{
_scope = factory.Services.CreateScope();
_handler = _scope.ServiceProvider.GetRequiredService<ExchangeDataRequestHandler>();
_exchangesClient = _scope.ServiceProvider.GetRequiredService<IExchangesClient>();
_context = _scope.ServiceProvider.GetRequiredService<CryptofolioContext>();
}
public void Dispose() => _scope.Dispose();
[Fact]
public async Task Handle_Test()
{
// Setup
var exchangeId = "gdax";
var gdax = await _exchangesClient.GetExchangesByExchangeId(exchangeId);
var request = new ExchangeDataRequest
{
TraceIdentifier = Guid.NewGuid().ToString(),
Date = DateTimeOffset.UtcNow,
Id = exchangeId
};
// Act
await _handler.Handle(request, CancellationToken.None, null);
// Assert
var exchange = _context.Exchanges.SingleOrDefault(a => a.Id == exchangeId);
exchange.Id.Should().Be(exchangeId);
exchange.Name.Should().Be(gdax.Name);
exchange.Description.Should().Be(gdax.Description);
exchange.YearEstablished.Should().Be(gdax.YearEstablished);
exchange.Url.Should().Be(gdax.Url);
exchange.Image.Should().Be(gdax.Image);
}
[Fact]
public async Task Handle_RequestCancelled_Test()
{
// Setup
var exchangeId = "gdax";
var request = new ExchangeDataRequest
{
TraceIdentifier = Guid.NewGuid().ToString(),
Date = DateTimeOffset.UtcNow,
Id = exchangeId
};
var cancellationToken = new CancellationToken(true);
// Act
await _handler.Awaiting(h => h.Handle(request, cancellationToken, null)).Should().ThrowAsync<OperationCanceledException>();
}
}
}
| 36.289474 | 135 | 0.639956 | [
"MIT"
] | fperronnet/cryptofolio | test/Cryptofolio.Collector.Job.IntegrationTests/Data/ExchangeDataRequestHandlerTests.cs | 2,758 | C# |
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SevenTiny.Bantina.Validation;
using SevenTiny.Cloud.MultiTenantPlatform.Core.Entity;
using SevenTiny.Cloud.MultiTenantPlatform.Core.Enum;
using SevenTiny.Cloud.MultiTenantPlatform.Core.ServiceContract;
using SevenTiny.Cloud.MultiTenantPlatform.Web.Models;
using System;
namespace Seventiny.Cloud.DevelopmentWeb.Controllers
{
public class IndexViewController : ControllerBase
{
readonly IIndexViewService indexViewService;
readonly IFieldListService interfaceFieldService;
readonly ISearchConditionService searchConditionService;
public IndexViewController(
IIndexViewService _indexViewService,
IFieldListService _interfaceFieldService,
ISearchConditionService _searchConditionService
)
{
this.indexViewService = _indexViewService;
this.interfaceFieldService = _interfaceFieldService;
this.searchConditionService = _searchConditionService;
}
public IActionResult List()
{
return View(indexViewService.GetEntitiesUnDeletedByMetaObjectId(CurrentMetaObjectId));
}
public IActionResult DeleteList()
{
return View(indexViewService.GetEntitiesDeletedByMetaObjectId(CurrentMetaObjectId));
}
public IActionResult Add()
{
var indexView = new SevenTiny.Cloud.MultiTenantPlatform.Core.Entity.IndexView();
indexView.Icon = "bars";
ViewData["InterfaceFields"] = interfaceFieldService.GetEntitiesUnDeletedByMetaObjectId(CurrentMetaObjectId);
ViewData["SearchConditions"] = searchConditionService.GetEntitiesUnDeletedByMetaObjectId(CurrentMetaObjectId);
return View(ResponseModel.Success(indexView));
}
public IActionResult AddLogic(IndexView entity)
{
ViewData["InterfaceFields"] = interfaceFieldService.GetEntitiesUnDeletedByMetaObjectId(CurrentMetaObjectId);
ViewData["SearchConditions"] = searchConditionService.GetEntitiesUnDeletedByMetaObjectId(CurrentMetaObjectId);
if (string.IsNullOrEmpty(entity.Name))
{
return View("Add", ResponseModel.Error("名称不能为空", entity));
}
if (string.IsNullOrEmpty(entity.Code))
{
return View("Add", ResponseModel.Error("编码不能为空", entity));
}
//校验code格式
if (!entity.Code.IsAlnum(2, 50))
{
return View("Add", ResponseModel.Error("编码不合法,2-50位且只能包含字母和数字(字母开头)", entity));
}
//检查编码或名称重复
var checkResult = indexViewService.CheckSameCodeOrName(CurrentMetaObjectId, entity);
if (!checkResult.IsSuccess)
{
return View("Add", checkResult.ToResponseModel());
}
if (entity.FieldListId == default(int))
{
return View("Add", ResponseModel.Error("接口字段不能为空", entity));
}
if (entity.SearchConditionId == default(int))
{
return View("Add", ResponseModel.Error("条件不能为空", entity));
}
entity.MetaObjectId = CurrentMetaObjectId;
//组合编码
entity.Code = $"{CurrentMetaObjectCode}.IndexView.{entity.Code}";
indexViewService.Add(entity);
return RedirectToAction("List");
}
public IActionResult Update(int id)
{
ViewData["InterfaceFields"] = interfaceFieldService.GetEntitiesUnDeletedByMetaObjectId(CurrentMetaObjectId);
ViewData["SearchConditions"] = searchConditionService.GetEntitiesUnDeletedByMetaObjectId(CurrentMetaObjectId);
var metaObject = indexViewService.GetById(id);
return View(ResponseModel.Success(metaObject));
}
public IActionResult UpdateLogic(IndexView entity)
{
ViewData["InterfaceFields"] = interfaceFieldService.GetEntitiesUnDeletedByMetaObjectId(CurrentMetaObjectId);
ViewData["SearchConditions"] = searchConditionService.GetEntitiesUnDeletedByMetaObjectId(CurrentMetaObjectId);
if (entity.Id == 0)
{
return View("Update", ResponseModel.Error("修改的id传递错误", entity));
}
if (string.IsNullOrEmpty(entity.Name))
{
return View("Update", ResponseModel.Error("名称不能为空", entity));
}
if (string.IsNullOrEmpty(entity.Code))
{
return View("Update", ResponseModel.Error("编码不能为空", entity));
}
////校验code格式
//if (!entity.Code.IsAlnum(2, 50))
//{
// return View("Add", ResponseModel.Error("编码不合法,2-50位且只能包含字母和数字(字母开头)", entity));
//}
//检查编码或名称重复
var checkResult = indexViewService.CheckSameCodeOrName(CurrentMetaObjectId, entity);
if (!checkResult.IsSuccess)
{
return View("Update", checkResult.ToResponseModel());
}
if (entity.FieldListId == default(int))
{
return View("Add", ResponseModel.Error("接口字段不能为空", entity));
}
if (entity.SearchConditionId == default(int))
{
return View("Add", ResponseModel.Error("条件不能为空", entity));
}
indexViewService.Update(entity);
return RedirectToAction("List");
}
public IActionResult Delete(int id)
{
indexViewService.Delete(id);
return JsonResultModel.Success("删除成功");
}
public IActionResult LogicDelete(int id)
{
indexViewService.LogicDelete(id);
return JsonResultModel.Success("删除成功");
}
public IActionResult Recover(int id)
{
indexViewService.Recover(id);
return JsonResultModel.Success("恢复成功");
}
}
} | 37.04878 | 122 | 0.615372 | [
"Apache-2.0"
] | PayHard/SevenTiny.Cloud.MultiTenantPlatform | 10-Code/Seventiny.Cloud.DevelopmentWeb/Controllers/IndexViewController.cs | 6,372 | C# |
using Cybtans.Graphics.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cybtans.Graphics.Shading
{
public class Shader
{
public Dictionary<string, string> Inputs { get; set; }
public Dictionary<string, ShaderParameter> Parameters { get; set; }
public string Location { get; set; }
public Task<string> LoadSourceStringAsync(string basePath)
{
return File.ReadAllTextAsync(Path.Combine(basePath, Location));
}
public string LoadSourceString(string basePath)
{
return File.ReadAllText(Path.Combine(basePath, Location));
}
public ShaderDto ToDto(ShaderProgram shaderProgram)
{
return new ShaderDto
{
Inputs = Inputs,
Parameters = Parameters.ToDictionary(x => x.Key, v => new ShaderParameterDto
{
Property = v.Value.Property,
Target = v.Value.Target,
Type = v.Value.Type,
Path = v.Value.Path
}),
Source = LoadSourceString(shaderProgram.BasePath)
};
}
}
public class ShaderParameter
{
public string Target { get; set; }
public string Property { get; set; }
public string Type { get; set; }
public string Path { get; set; }
}
public enum ShaderType
{
Float,
Float2,
Floa3,
Int,
Int2,
Int3,
Matrix
}
}
| 23.068493 | 92 | 0.542755 | [
"MIT"
] | ansel86castro/cybtans-sdk | CybtansSDK/Graphics/Cybtans.Graphics/Shading/Shader.cs | 1,686 | C# |
using AV.Middle.Pattern.Behavioral.ComputerParts.Concrete;
using AV.Middle.Pattern.Behavioral.ComputerParts.Visitor;
using AV.Middle.Reflector.IService;
using System;
using System.Collections;
namespace AV.Middle.Pattern.Behavioral.ComputerParts
{
public class VisitorProcess : IProcess
{
public Hashtable Hashtable { get; set; }
public void Start()
{
var computer = new Computer();
computer.Accept(new ComputerPartDisplayVisitor());
}
public bool Validate() => true;
}
}
| 22.5 | 59 | 0.759596 | [
"MIT"
] | iAvinashVarma/RunnerCore | Middle/Pattern/Behavioral/AV.Middle.Pattern.Behavioral.ComputerParts/VisitorProcess.cs | 497 | C# |
//
// NullDhtListener.cs
//
// Authors:
// Alan McGovern <alan.mcgovern@gmail.com>
//
// Copyright (C) 2020 Alan McGovern
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Net;
using System.Threading.Tasks;
namespace MonoTorrent.Connections.Dht
{
class NullDhtListener : IDhtListener
{
#pragma warning disable 0067
public event Action<byte[], IPEndPoint>? MessageReceived;
public event EventHandler<EventArgs>? StatusChanged;
#pragma warning restore 0067
public NullDhtListener ()
{
}
public IPEndPoint? LocalEndPoint { get; }
public ListenerStatus Status { get; } = ListenerStatus.NotListening;
public Task SendAsync (byte[] buffer, IPEndPoint endpoint)
{
return Task.CompletedTask;
}
public void Start ()
{
}
public void Stop ()
{
}
}
}
| 29.757576 | 76 | 0.697556 | [
"MIT"
] | Tansien/MonoTorrent | src/MonoTorrent.Client/MonoTorrent.Connections.Dht/NullDhtListener.cs | 1,966 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModelsLibrary
{
public class StoreModel
{
public int LocationID { get; set; }
public int ProductID { get; set; }
[Display(Name = "Product Name")]
public string ProductName { get; set; }
[Display(Name = "Price")]
public decimal ProductPrice { get; set; }
[Display(Name = "Description")]
public string ProductDescription { get; set; }
[Display(Name = "Quantity Avalible")]
public int InventoryAmount { get; set; }
}
}
| 21.482759 | 48 | 0.70626 | [
"MIT"
] | 06012021-dotnet-uta/EthanBakerP1 | Project1Folder/ModelsLibrary/StoreModel.cs | 625 | C# |
namespace WIC
{
public enum WICPngIccpProperties
{
ProfileName = 1,
ProfileData,
}
}
| 10.222222 | 33 | 0.706522 | [
"MIT"
] | udaken/interop.wincodec | WIC/WICPngIccpProperties.cs | 92 | 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.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// A container synthesized for a lambda, iterator method, async method, or dynamic-sites.
/// </summary>
internal abstract class SynthesizedContainer : NamedTypeSymbol
{
private readonly ImmutableArray<TypeParameterSymbol> _typeParameters;
private readonly ImmutableArray<TypeParameterSymbol> _constructedFromTypeParameters;
protected SynthesizedContainer(string name, int parameterCount, bool returnsVoid)
{
Debug.Assert(name != null);
Name = name;
TypeMap = TypeMap.Empty;
_typeParameters = CreateTypeParameters(parameterCount, returnsVoid);
_constructedFromTypeParameters = default(ImmutableArray<TypeParameterSymbol>);
}
protected SynthesizedContainer(string name, MethodSymbol containingMethod)
{
Debug.Assert(name != null);
Name = name;
if (containingMethod == null)
{
TypeMap = TypeMap.Empty;
_typeParameters = ImmutableArray<TypeParameterSymbol>.Empty;
}
else
{
TypeMap = TypeMap.Empty.WithConcatAlphaRename(containingMethod, this, out _typeParameters, out _constructedFromTypeParameters);
}
}
protected SynthesizedContainer(string name, ImmutableArray<TypeParameterSymbol> typeParameters, TypeMap typeMap)
{
Debug.Assert(name != null);
Debug.Assert(!typeParameters.IsDefault);
Debug.Assert(typeMap != null);
Name = name;
_typeParameters = typeParameters;
TypeMap = typeMap;
}
private ImmutableArray<TypeParameterSymbol> CreateTypeParameters(int parameterCount, bool returnsVoid)
{
var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(parameterCount + (returnsVoid ? 0 : 1));
for (int i = 0; i < parameterCount; i++)
{
typeParameters.Add(new AnonymousTypeManager.AnonymousTypeParameterSymbol(this, i, "T" + (i + 1)));
}
if (!returnsVoid)
{
typeParameters.Add(new AnonymousTypeManager.AnonymousTypeParameterSymbol(this, parameterCount, "TResult"));
}
return typeParameters.ToImmutableAndFree();
}
internal TypeMap TypeMap { get; }
internal virtual MethodSymbol Constructor => null;
internal sealed override bool IsInterface => this.TypeKind == TypeKind.Interface;
internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
base.AddSynthesizedAttributes(moduleBuilder, ref attributes);
if (ContainingSymbol.Kind == SymbolKind.NamedType && (ContainingSymbol.IsImplicitlyDeclared || ContainingSymbol is SimpleProgramNamedTypeSymbol))
{
return;
}
var compilation = ContainingSymbol.DeclaringCompilation;
// this can only happen if frame is not nested in a source type/namespace (so far we do not do this)
// if this happens for whatever reason, we do not need "CompilerGenerated" anyways
Debug.Assert(compilation != null, "SynthesizedClass is not contained in a source module?");
AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(
WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor));
}
protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData)
=> throw ExceptionUtilities.Unreachable;
/// <summary>
/// Note: Can be default if this SynthesizedContainer was constructed with <see cref="SynthesizedContainer(string, int, bool)"/>
/// </summary>
internal ImmutableArray<TypeParameterSymbol> ConstructedFromTypeParameters => _constructedFromTypeParameters;
public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters => _typeParameters;
public sealed override string Name { get; }
public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty;
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty;
public override IEnumerable<string> MemberNames => SpecializedCollections.EmptyEnumerable<string>();
public override NamedTypeSymbol ConstructedFrom => this;
public override bool IsSealed => true;
public override bool IsAbstract => (object)Constructor == null && this.TypeKind != TypeKind.Struct;
internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics
{
get { return GetTypeParametersAsTypeArguments(); }
}
internal override bool HasCodeAnalysisEmbeddedAttribute => false;
internal sealed override bool IsInterpolatedStringHandlerType => false;
public override ImmutableArray<Symbol> GetMembers()
{
Symbol constructor = this.Constructor;
return (object)constructor == null ? ImmutableArray<Symbol>.Empty : ImmutableArray.Create(constructor);
}
public override ImmutableArray<Symbol> GetMembers(string name)
{
var ctor = Constructor;
return ((object)ctor != null && name == ctor.Name) ? ImmutableArray.Create<Symbol>(ctor) : ImmutableArray<Symbol>.Empty;
}
internal override IEnumerable<FieldSymbol> GetFieldsToEmit()
{
foreach (var m in this.GetMembers())
{
switch (m.Kind)
{
case SymbolKind.Field:
yield return (FieldSymbol)m;
break;
}
}
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() => this.GetMembersUnordered();
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) => this.GetMembers(name);
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() => ImmutableArray<NamedTypeSymbol>.Empty;
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) => ImmutableArray<NamedTypeSymbol>.Empty;
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) => ImmutableArray<NamedTypeSymbol>.Empty;
public override Accessibility DeclaredAccessibility => Accessibility.Private;
public override bool IsStatic => false;
public sealed override bool IsRefLikeType => false;
public sealed override bool IsReadOnly => false;
internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved) => ImmutableArray<NamedTypeSymbol>.Empty;
internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() => CalculateInterfacesToEmit();
internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => ContainingAssembly.GetSpecialType(this.TypeKind == TypeKind.Struct ? SpecialType.System_ValueType : SpecialType.System_Object);
internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved) => BaseTypeNoUseSiteDiagnostics;
internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved) => InterfacesNoUseSiteDiagnostics(basesBeingResolved);
public override bool MightContainExtensionMethods => false;
public override int Arity => TypeParameters.Length;
internal override bool MangleName => Arity > 0;
public override bool IsImplicitlyDeclared => true;
internal override bool ShouldAddWinRTMembers => false;
internal override bool IsWindowsRuntimeImport => false;
internal override bool IsComImport => false;
internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null;
internal sealed override ImmutableArray<string> GetAppliedConditionalSymbols() => ImmutableArray<string>.Empty;
internal override bool HasDeclarativeSecurity => false;
internal override CharSet MarshallingCharSet => DefaultMarshallingCharSet;
public override bool IsSerializable => false;
internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal override AttributeUsageInfo GetAttributeUsageInfo() => default(AttributeUsageInfo);
internal override TypeLayout Layout => default(TypeLayout);
internal override bool HasSpecialName => false;
internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable;
internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null;
internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls()
{
return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>();
}
}
}
| 42.304721 | 201 | 0.697474 | [
"MIT"
] | 333fred/roslyn | src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedContainer.cs | 9,859 | 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>
/// FaxDocument
/// </summary>
[DataContract]
public partial class FaxDocument : IEquatable<FaxDocument>
{
/// <summary>
/// Initializes a new instance of the <see cref="FaxDocument" /> class.
/// </summary>
/// <param name="Name">Name.</param>
/// <param name="DateCreated">Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z.</param>
/// <param name="DateModified">Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z.</param>
/// <param name="ContentUri">ContentUri.</param>
/// <param name="Workspace">Workspace.</param>
/// <param name="CreatedBy">CreatedBy.</param>
/// <param name="SharingUri">SharingUri.</param>
/// <param name="ContentType">ContentType.</param>
/// <param name="ContentLength">ContentLength.</param>
/// <param name="Filename">Filename.</param>
/// <param name="Read">Read.</param>
/// <param name="PageCount">PageCount.</param>
/// <param name="CallerAddress">CallerAddress.</param>
/// <param name="ReceiverAddress">ReceiverAddress.</param>
/// <param name="Thumbnails">Thumbnails.</param>
/// <param name="DownloadSharingUri">DownloadSharingUri.</param>
public FaxDocument(string Name = null, DateTime? DateCreated = null, DateTime? DateModified = null, string ContentUri = null, DomainEntityRef Workspace = null, DomainEntityRef CreatedBy = null, string SharingUri = null, string ContentType = null, long? ContentLength = null, string Filename = null, bool? Read = null, long? PageCount = null, string CallerAddress = null, string ReceiverAddress = null, List<DocumentThumbnail> Thumbnails = null, string DownloadSharingUri = null)
{
this.Name = Name;
this.DateCreated = DateCreated;
this.DateModified = DateModified;
this.ContentUri = ContentUri;
this.Workspace = Workspace;
this.CreatedBy = CreatedBy;
this.SharingUri = SharingUri;
this.ContentType = ContentType;
this.ContentLength = ContentLength;
this.Filename = Filename;
this.Read = Read;
this.PageCount = PageCount;
this.CallerAddress = CallerAddress;
this.ReceiverAddress = ReceiverAddress;
this.Thumbnails = Thumbnails;
this.DownloadSharingUri = DownloadSharingUri;
}
/// <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>
/// Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z
/// </summary>
/// <value>Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z</value>
[DataMember(Name="dateCreated", EmitDefaultValue=false)]
public DateTime? DateCreated { get; set; }
/// <summary>
/// Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z
/// </summary>
/// <value>Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z</value>
[DataMember(Name="dateModified", EmitDefaultValue=false)]
public DateTime? DateModified { get; set; }
/// <summary>
/// Gets or Sets ContentUri
/// </summary>
[DataMember(Name="contentUri", EmitDefaultValue=false)]
public string ContentUri { get; set; }
/// <summary>
/// Gets or Sets Workspace
/// </summary>
[DataMember(Name="workspace", EmitDefaultValue=false)]
public DomainEntityRef Workspace { get; set; }
/// <summary>
/// Gets or Sets CreatedBy
/// </summary>
[DataMember(Name="createdBy", EmitDefaultValue=false)]
public DomainEntityRef CreatedBy { get; set; }
/// <summary>
/// Gets or Sets SharingUri
/// </summary>
[DataMember(Name="sharingUri", EmitDefaultValue=false)]
public string SharingUri { get; set; }
/// <summary>
/// Gets or Sets ContentType
/// </summary>
[DataMember(Name="contentType", EmitDefaultValue=false)]
public string ContentType { get; set; }
/// <summary>
/// Gets or Sets ContentLength
/// </summary>
[DataMember(Name="contentLength", EmitDefaultValue=false)]
public long? ContentLength { get; set; }
/// <summary>
/// Gets or Sets Filename
/// </summary>
[DataMember(Name="filename", EmitDefaultValue=false)]
public string Filename { get; set; }
/// <summary>
/// Gets or Sets Read
/// </summary>
[DataMember(Name="read", EmitDefaultValue=false)]
public bool? Read { get; set; }
/// <summary>
/// Gets or Sets PageCount
/// </summary>
[DataMember(Name="pageCount", EmitDefaultValue=false)]
public long? PageCount { get; set; }
/// <summary>
/// Gets or Sets CallerAddress
/// </summary>
[DataMember(Name="callerAddress", EmitDefaultValue=false)]
public string CallerAddress { get; set; }
/// <summary>
/// Gets or Sets ReceiverAddress
/// </summary>
[DataMember(Name="receiverAddress", EmitDefaultValue=false)]
public string ReceiverAddress { get; set; }
/// <summary>
/// Gets or Sets Thumbnails
/// </summary>
[DataMember(Name="thumbnails", EmitDefaultValue=false)]
public List<DocumentThumbnail> Thumbnails { get; set; }
/// <summary>
/// Gets or Sets DownloadSharingUri
/// </summary>
[DataMember(Name="downloadSharingUri", EmitDefaultValue=false)]
public string DownloadSharingUri { 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 FaxDocument {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" DateCreated: ").Append(DateCreated).Append("\n");
sb.Append(" DateModified: ").Append(DateModified).Append("\n");
sb.Append(" ContentUri: ").Append(ContentUri).Append("\n");
sb.Append(" Workspace: ").Append(Workspace).Append("\n");
sb.Append(" CreatedBy: ").Append(CreatedBy).Append("\n");
sb.Append(" SharingUri: ").Append(SharingUri).Append("\n");
sb.Append(" ContentType: ").Append(ContentType).Append("\n");
sb.Append(" ContentLength: ").Append(ContentLength).Append("\n");
sb.Append(" Filename: ").Append(Filename).Append("\n");
sb.Append(" Read: ").Append(Read).Append("\n");
sb.Append(" PageCount: ").Append(PageCount).Append("\n");
sb.Append(" CallerAddress: ").Append(CallerAddress).Append("\n");
sb.Append(" ReceiverAddress: ").Append(ReceiverAddress).Append("\n");
sb.Append(" Thumbnails: ").Append(Thumbnails).Append("\n");
sb.Append(" DownloadSharingUri: ").Append(DownloadSharingUri).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 FaxDocument);
}
/// <summary>
/// Returns true if FaxDocument instances are equal
/// </summary>
/// <param name="other">Instance of FaxDocument to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(FaxDocument 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.DateCreated == other.DateCreated ||
this.DateCreated != null &&
this.DateCreated.Equals(other.DateCreated)
) &&
(
this.DateModified == other.DateModified ||
this.DateModified != null &&
this.DateModified.Equals(other.DateModified)
) &&
(
this.ContentUri == other.ContentUri ||
this.ContentUri != null &&
this.ContentUri.Equals(other.ContentUri)
) &&
(
this.Workspace == other.Workspace ||
this.Workspace != null &&
this.Workspace.Equals(other.Workspace)
) &&
(
this.CreatedBy == other.CreatedBy ||
this.CreatedBy != null &&
this.CreatedBy.Equals(other.CreatedBy)
) &&
(
this.SharingUri == other.SharingUri ||
this.SharingUri != null &&
this.SharingUri.Equals(other.SharingUri)
) &&
(
this.ContentType == other.ContentType ||
this.ContentType != null &&
this.ContentType.Equals(other.ContentType)
) &&
(
this.ContentLength == other.ContentLength ||
this.ContentLength != null &&
this.ContentLength.Equals(other.ContentLength)
) &&
(
this.Filename == other.Filename ||
this.Filename != null &&
this.Filename.Equals(other.Filename)
) &&
(
this.Read == other.Read ||
this.Read != null &&
this.Read.Equals(other.Read)
) &&
(
this.PageCount == other.PageCount ||
this.PageCount != null &&
this.PageCount.Equals(other.PageCount)
) &&
(
this.CallerAddress == other.CallerAddress ||
this.CallerAddress != null &&
this.CallerAddress.Equals(other.CallerAddress)
) &&
(
this.ReceiverAddress == other.ReceiverAddress ||
this.ReceiverAddress != null &&
this.ReceiverAddress.Equals(other.ReceiverAddress)
) &&
(
this.Thumbnails == other.Thumbnails ||
this.Thumbnails != null &&
this.Thumbnails.SequenceEqual(other.Thumbnails)
) &&
(
this.DownloadSharingUri == other.DownloadSharingUri ||
this.DownloadSharingUri != null &&
this.DownloadSharingUri.Equals(other.DownloadSharingUri)
) &&
(
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.DateCreated != null)
hash = hash * 59 + this.DateCreated.GetHashCode();
if (this.DateModified != null)
hash = hash * 59 + this.DateModified.GetHashCode();
if (this.ContentUri != null)
hash = hash * 59 + this.ContentUri.GetHashCode();
if (this.Workspace != null)
hash = hash * 59 + this.Workspace.GetHashCode();
if (this.CreatedBy != null)
hash = hash * 59 + this.CreatedBy.GetHashCode();
if (this.SharingUri != null)
hash = hash * 59 + this.SharingUri.GetHashCode();
if (this.ContentType != null)
hash = hash * 59 + this.ContentType.GetHashCode();
if (this.ContentLength != null)
hash = hash * 59 + this.ContentLength.GetHashCode();
if (this.Filename != null)
hash = hash * 59 + this.Filename.GetHashCode();
if (this.Read != null)
hash = hash * 59 + this.Read.GetHashCode();
if (this.PageCount != null)
hash = hash * 59 + this.PageCount.GetHashCode();
if (this.CallerAddress != null)
hash = hash * 59 + this.CallerAddress.GetHashCode();
if (this.ReceiverAddress != null)
hash = hash * 59 + this.ReceiverAddress.GetHashCode();
if (this.Thumbnails != null)
hash = hash * 59 + this.Thumbnails.GetHashCode();
if (this.DownloadSharingUri != null)
hash = hash * 59 + this.DownloadSharingUri.GetHashCode();
if (this.SelfUri != null)
hash = hash * 59 + this.SelfUri.GetHashCode();
return hash;
}
}
}
}
| 33.2603 | 486 | 0.475874 | [
"MIT"
] | F-V-L/platform-client-sdk-dotnet | build/src/PureCloudPlatform.Client.V2/Model/FaxDocument.cs | 17,761 | C# |
using System;
using System.Formats.Asn1;
using System.Numerics;
using System.Security;
namespace OpenGost.Security.Cryptography.Asn1;
[SecuritySafeCritical]
internal ref struct AsnValueReader
{
private static readonly byte[] _singleByte = new byte[1];
private ReadOnlySpan<byte> _span;
private readonly AsnEncodingRules _ruleSet;
public AsnValueReader(ReadOnlySpan<byte> span, AsnEncodingRules ruleSet)
{
_span = span;
_ruleSet = ruleSet;
}
public bool HasData => !_span.IsEmpty;
public void ThrowIfNotEmpty()
{
if (!_span.IsEmpty)
{
new AsnReader(_singleByte, _ruleSet).ThrowIfNotEmpty();
}
}
public Asn1Tag PeekTag()
{
return Asn1Tag.Decode(_span, out _);
}
public ReadOnlySpan<byte> PeekEncodedValue()
{
AsnDecoder.ReadEncodedValue(_span, _ruleSet, out _, out _, out int consumed);
return _span.Slice(0, consumed);
}
public ReadOnlySpan<byte> ReadEncodedValue()
{
var value = PeekEncodedValue();
_span = _span.Slice(value.Length);
return value;
}
public bool ReadBoolean(Asn1Tag? expectedTag = default)
{
var ret = AsnDecoder.ReadBoolean(_span, _ruleSet, out int consumed, expectedTag);
_span = _span.Slice(consumed);
return ret;
}
public BigInteger ReadInteger(Asn1Tag? expectedTag = default)
{
var ret = AsnDecoder.ReadInteger(_span, _ruleSet, out int consumed, expectedTag);
_span = _span.Slice(consumed);
return ret;
}
public bool TryReadInt32(out int value, Asn1Tag? expectedTag = default)
{
var ret = AsnDecoder.TryReadInt32(_span, _ruleSet, out value, out int consumed, expectedTag);
_span = _span.Slice(consumed);
return ret;
}
public ReadOnlySpan<byte> ReadIntegerBytes(Asn1Tag? expectedTag = default)
{
var ret = AsnDecoder.ReadIntegerBytes(_span, _ruleSet, out int consumed, expectedTag);
_span = _span.Slice(consumed);
return ret;
}
public bool TryReadPrimitiveBitString(
out int unusedBitCount,
out ReadOnlySpan<byte> value,
Asn1Tag? expectedTag = default)
{
bool ret = AsnDecoder.TryReadPrimitiveBitString(
_span,
_ruleSet,
out unusedBitCount,
out value,
out int consumed,
expectedTag);
_span = _span.Slice(consumed);
return ret;
}
public byte[] ReadBitString(out int unusedBitCount, Asn1Tag? expectedTag = default)
{
byte[] ret = AsnDecoder.ReadBitString(
_span,
_ruleSet,
out unusedBitCount,
out int consumed,
expectedTag);
_span = _span.Slice(consumed);
return ret;
}
public T ReadNamedBitListValue<T>(Asn1Tag? expectedTag = default)
where T : Enum
{
var ret = AsnDecoder.ReadNamedBitListValue<T>(_span, _ruleSet, out int consumed, expectedTag);
_span = _span.Slice(consumed);
return ret;
}
public bool TryReadPrimitiveOctetString(
out ReadOnlySpan<byte> value,
Asn1Tag? expectedTag = default)
{
var ret = AsnDecoder.TryReadPrimitiveOctetString(
_span,
_ruleSet,
out value,
out int consumed,
expectedTag);
_span = _span.Slice(consumed);
return ret;
}
public byte[] ReadOctetString(Asn1Tag? expectedTag = default)
{
var ret = AsnDecoder.ReadOctetString(
_span,
_ruleSet,
out int consumed,
expectedTag);
_span = _span.Slice(consumed);
return ret;
}
public string ReadObjectIdentifier(Asn1Tag? expectedTag = default)
{
var ret = AsnDecoder.ReadObjectIdentifier(_span, _ruleSet, out int consumed, expectedTag);
_span = _span.Slice(consumed);
return ret;
}
public AsnValueReader ReadSequence(Asn1Tag? expectedTag = default)
{
AsnDecoder.ReadSequence(
_span,
_ruleSet,
out int contentOffset,
out int contentLength,
out int bytesConsumed,
expectedTag);
var content = _span.Slice(contentOffset, contentLength);
_span = _span.Slice(bytesConsumed);
return new AsnValueReader(content, _ruleSet);
}
public AsnValueReader ReadSetOf(Asn1Tag? expectedTag = default)
{
AsnDecoder.ReadSetOf(
_span,
_ruleSet,
out int contentOffset,
out int contentLength,
out int bytesConsumed,
expectedTag: expectedTag);
var content = _span.Slice(contentOffset, contentLength);
_span = _span.Slice(bytesConsumed);
return new AsnValueReader(content, _ruleSet);
}
public DateTimeOffset ReadUtcTime(Asn1Tag? expectedTag = default)
{
var ret = AsnDecoder.ReadUtcTime(_span, _ruleSet, out int consumed, expectedTag: expectedTag);
_span = _span.Slice(consumed);
return ret;
}
public DateTimeOffset ReadGeneralizedTime(Asn1Tag? expectedTag = default)
{
var ret = AsnDecoder.ReadGeneralizedTime(_span, _ruleSet, out int consumed, expectedTag);
_span = _span.Slice(consumed);
return ret;
}
public string ReadCharacterString(UniversalTagNumber encodingType, Asn1Tag? expectedTag = default)
{
var ret = AsnDecoder.ReadCharacterString(_span, _ruleSet, encodingType, out int consumed, expectedTag);
_span = _span.Slice(consumed);
return ret;
}
}
| 28.432836 | 111 | 0.624847 | [
"MIT"
] | sergezhigunov/gost | src/OpenGost.Security.Cryptography/Asn1/AsnValueReader.cs | 5,717 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Archigen;
namespace Archigen.Examples
{
/// <summary>
/// A random string generator.
/// </summary>
public class StringGenerator : IGenerator<string>
{
private Random Random = new Random();
public string Next()
{
var result = new StringBuilder();
for(int i = 0; i < 8; i++)
{
result.Append((char)this.Random.Next('a', 'z'));
}
return result.ToString();
}
}
/// <summary>
/// Really basic POCO
/// </summary>
public class Team
{
public string TeamName { get; set; }
public List<Player> Players { get; set; }
public override string ToString() => this.TeamName;
}
/// <summary>
/// Nested POCO
/// </summary>
public class Player
{
public string PlayerName { get; set; }
public override string ToString() => this.PlayerName;
}
/// <summary>
/// Generates random teams with full
/// ten named players each.
/// </summary>
public class Program
{
public static void Main(string[] args)
{
var g = new Generator<Team>()
.ForProperty<string>(x => x.TeamName, new StringGenerator())
.ForListProperty<Player>(x => x.Players, new Generator<Player>()
.ForProperty<string>(x => x.PlayerName, new StringGenerator()))
.UsingSize(10);
var c = new ConditionalGenerator<Team>(g)
.WithCondition(team => team.TeamName.Contains("a"));
for(int i = 0; i < 3; i++)
{
var team = c.Next();
Console.WriteLine("Team {0}", team);
foreach(var player in team.Players)
{
Console.WriteLine("Player {0}", player);
}
}
}
}
}
| 25.234568 | 87 | 0.500978 | [
"MIT"
] | kesac/Archigen | Archigen/Archigen.Examples/Program.cs | 2,046 | C# |
using Core;
using Core.Entities;
using System;
using System.Collections.Generic;
using System.Text;
namespace Entities.DTOs
{
public class UserForLoginDto : IDto
{
public string Email { get; set; }
public string Password { get; set; }
}
}
| 17.933333 | 44 | 0.672862 | [
"MIT"
] | aykutsahin98/ReCapProject | Entities/DTOs/UserForLoginDto.cs | 271 | C# |
using CairoDesktop.Common.Logging;
using CairoDesktop.Interop;
using CairoDesktop.SupportingClasses;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
namespace CairoDesktop.AppGrabber
{
/// <summary>
/// Interaction logic for AppGrabber.xaml
/// </summary>
public partial class AppGrabberUI : Window
{
private AppGrabber appGrabber;
ObservableCollection<ApplicationInfo> programsMenuAppsCollection;
public Visibility AppVisibility
{
get { return (Visibility)GetValue(AppVisibilityProperty); }
set { SetValue(AppVisibilityProperty, value); }
}
private bool bAppsHidden
{
get { return (AppVisibility != Visibility.Visible); }
set
{
if (value)
{
SetValue(AppVisibilityProperty, Visibility.Collapsed);
SetValue(bAppsHiddenProperty, true);
}
else
{
SetValue(AppVisibilityProperty, Visibility.Visible);
SetValue(bAppsHiddenProperty, false);
}
}
}
public static readonly DependencyProperty AppVisibilityProperty = DependencyProperty.Register("AppVisibility", typeof(Visibility), typeof(AppGrabberUI), new PropertyMetadata(null));
private static readonly DependencyProperty bAppsHiddenProperty = DependencyProperty.Register("bAppsHidden", typeof(bool), typeof(AppGrabberUI), new PropertyMetadata(null));
public AppGrabberUI()
: this(AppGrabber.Instance)
{
}
public AppGrabberUI(AppGrabber appGrabber)
{
this.appGrabber = appGrabber;
InitializeComponent();
Height = (SystemParameters.MaximizedPrimaryScreenHeight / Shell.DpiScaleAdjustment) - 100;
MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight / Shell.DpiScaleAdjustment;
}
#region Button Clicks
private void SkipWizard(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnContinue_Click(object sender, RoutedEventArgs e)
{
goPage2();
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
appGrabber.Save();
this.Close();
}
private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
string filter = "Programs and shortcuts|";
foreach (string ext in AppGrabber.ExecutableExtensions)
{
filter += $"*{ext};";
}
filter = filter.Substring(0, filter.Length - 2);
using (OpenFileDialog dlg = new OpenFileDialog
{
Filter = filter
})
{
if (dlg.SafeShowDialog() == System.Windows.Forms.DialogResult.OK && Interop.Shell.Exists(dlg.FileName))
{
ApplicationInfo customApp = AppGrabber.PathToApp(dlg.FileName, true);
if (!ReferenceEquals(customApp, null))
{
if (!programsMenuAppsCollection.Contains(customApp) && !(InstalledAppsView.ItemsSource as ObservableCollection<ApplicationInfo>).Contains(customApp))
{
programsMenuAppsCollection.Add(customApp);
}
else
{
// disallow adding a duplicate
CairoLogger.Instance.Debug("Excluded duplicate item: " + customApp.Name + ": " + customApp.Target);
}
}
}
}
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
appGrabber.CategoryList.Add(new Category(Localization.DisplayString.sAppGrabber_Untitled));
scrollViewer.ScrollToEnd();
}
private void tglHide_Click(object sender, RoutedEventArgs e)
{
if (!bAppsHidden)
bAppsHidden = true;
else
bAppsHidden = false;
}
#endregion
#region Events
void programsMenuAppsCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
{
foreach (ApplicationInfo app in e.OldItems)
{
if (app.Category != null)
{
app.Category.Remove(app);
}
}
}
}
private void ProgramsMenuAppsView_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (((FrameworkElement)e.OriginalSource).DataContext != null)
{
ApplicationInfo app = ((FrameworkElement)e.OriginalSource).DataContext as ApplicationInfo;
(ProgramsMenuAppsView.ItemsSource as ObservableCollection<ApplicationInfo>).Remove(app);
(InstalledAppsView.ItemsSource as ObservableCollection<ApplicationInfo>).Add(app);
}
}
private void InstalledAppsView_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (((FrameworkElement)e.OriginalSource).DataContext != null)
{
ApplicationInfo app = ((FrameworkElement)e.OriginalSource).DataContext as ApplicationInfo;
(InstalledAppsView.ItemsSource as ObservableCollection<ApplicationInfo>).Remove(app);
(ProgramsMenuAppsView.ItemsSource as ObservableCollection<ApplicationInfo>).Add(app);
}
}
private void Window_ContentRendered(object sender, EventArgs e)
{
// Now to add them to the list on the AppGrabber
// Create ObservableCollections to bind to the ListViews
ObservableCollection<ApplicationInfo> installedAppsCollection = new ObservableCollection<ApplicationInfo>();
programsMenuAppsCollection = appGrabber.CategoryList.FlatList;
InstalledAppsView.ItemsSource = installedAppsCollection;
ProgramsMenuAppsView.ItemsSource = programsMenuAppsCollection;
// Need to use an event handler to remove Apps from categories when moved to the "Installed Applications" listing
programsMenuAppsCollection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(programsMenuAppsCollection_CollectionChanged);
// Grab the Programs
List<ApplicationInfo> apps = appGrabber.ProgramList;
// automatically select apps if none have been yet
bool autoAddApps = programsMenuAppsCollection.Count < 1;
// Iterate thru the apps, creating ApplicationInfoPanels and
// add them to the installedAppsCollection
foreach (ApplicationInfo app in apps)
{
if (!programsMenuAppsCollection.Contains(app))
{
if (autoAddApps && ((app.IsStoreApp && autoSelectByName(app.Name)) || (!app.IsStoreApp && autoSelectByName(Path.GetFileNameWithoutExtension(app.Path)))))
programsMenuAppsCollection.Add(app);
else
installedAppsCollection.Add(app);
}
}
AppViewSorter.Sort(installedAppsCollection, "Name");
AppViewSorter.Sort(programsMenuAppsCollection, "Name");
// show content
bdrLoad.Visibility = Visibility.Collapsed;
bdrMain.Visibility = Visibility.Visible;
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
AppGrabber.uiInstance = null;
}
private void ScrollViewer_DragOver(object sender, System.Windows.DragEventArgs e)
{
int scrollTollerance = 12;
ScrollViewer scroller = sender as ScrollViewer;
if (e.GetPosition(scroller).Y > scroller.ActualHeight - scrollTollerance)
{
scroller.LineDown();
}
else if (e.GetPosition(scroller).Y < scrollTollerance)
{
scroller.LineUp();
}
}
#endregion
#region Auto selection
// categories
static string accessories = Localization.DisplayString.sAppGrabber_Category_Accessories;
static string productivity = Localization.DisplayString.sAppGrabber_Category_Productivity;
static string development = Localization.DisplayString.sAppGrabber_Category_Development;
static string graphics = Localization.DisplayString.sAppGrabber_Category_Graphics;
static string media = Localization.DisplayString.sAppGrabber_Category_Media;
static string internet = Localization.DisplayString.sAppGrabber_Category_Internet;
static string games = Localization.DisplayString.sAppGrabber_Category_Games;
string[] autoAppNames = {
// accessories
"File Explorer|full|" + accessories,
"Windows Explorer|full|" + accessories,
"Command Prompt|full|" + accessories,
"Calculator|full|" + accessories,
"Notepad|full|" + accessories,
"Snipping Tool|full|" + accessories,
"Wordpad|full|" + accessories,
"Sticky Notes|full|" + accessories,
"Paint|full|" + accessories,
// productivity
"LibreOffice|contains|" + productivity,
"OpenOffice|contains|" + productivity,
"Access 20|contains|" + productivity,
"Excel 20|contains|" + productivity,
"Lync 20|contains|" + productivity,
"PowerPoint 20|contains|" + productivity,
"Publisher 20|contains|" + productivity,
"OneNote 20|contains|" + productivity,
"Outlook 20|contains|" + productivity,
"Skype for Business 20|contains|" + productivity,
"Word 20|contains|" + productivity,
"Visio 20|contains|" + productivity,
"Access|full|" + productivity,
"Excel|full|" + productivity,
"PowerPoint|full|" + productivity,
"Publisher|full|" + productivity,
"OneNote|full|" + productivity,
"Outlook|full|" + productivity,
"Word|full|" + productivity,
"Visio|full|" + productivity,
"SumatraPDF|full|" + productivity,
"Microsoft Teams|full|" + productivity,
// development
"Android Studio|contains|" + development,
"Eclipse|contains|" + development,
"Netbeans IDE|contains|" + development,
"Notepad++|full|" + development,
"Sublime Text|contains|" + development,
"Visual Studio 20|contains|" + development,
// graphics
"Adobe After Effects|contains|" + graphics,
"Adobe Illustrator|contains|" + graphics,
"Adobe InDesign|contains|" + graphics,
"Adobe Dreamweaver|contains|" + graphics,
"Adobe Photoshop|contains|" + graphics,
"Adobe Premiere|contains|" + graphics,
"GIMP |contains|" + graphics,
"Inkscape|contains|" + graphics,
// media
"Windows Media Player|full|" + media,
"Spotify|full|" + media,
"iTunes|full|" + media,
"Audacity|full|" + media,
"VLC media player|full|" + media,
// internet
"Firefox|contains|" + internet,
"Thunderbird|contains|" + internet,
"Chrome|contains|" + internet,
"Remote Desktop Connection|full|" + internet,
"PuTTY|full|" + internet,
"WinSCP|full|" + internet,
"FileZilla|full|" + internet,
"Pidgin|full|" + internet,
"OneDrive|full|" + internet,
"Backup and Sync from Google|full|" + internet,
"Dropbox|full|" + internet,
"Skype|full|" + internet,
"Twitter|full|" + internet,
"Microsoft Edge|full|" + internet,
"Internet Explorer|full|" + internet,
"Slack|full|" + internet,
"PureCloud|full|" + internet,
"Discord|full|" + internet,
// games
"Steam|full|" + games,
"Epic Games|full|" + games,
"Uplay|full|" + games,
"Battle.net|full|" + games,
"OBS Studio|contains|" + games,
"Origin|full|" + games
};
private bool autoSelectByName(string name)
{
foreach (string autoApp in autoAppNames)
{
string[] autoAppName = autoApp.Split('|');
if (autoAppName[1] == "full" && autoAppName[0] == name)
return true;
if (autoAppName[1] == "contains" && name.Contains(autoAppName[0]))
return true;
}
return false;
}
private string autoCategorizeByName(string name)
{
foreach (string autoApp in autoAppNames)
{
string[] autoAppName = autoApp.Split('|');
if (autoAppName[1] == "full" && autoAppName[0] == name)
return autoAppName[2];
if (autoAppName[1] == "contains" && name.Contains(autoAppName[0]))
return autoAppName[2];
}
return "";
}
#endregion
private void goPage2()
{
bdrMain.Visibility = Visibility.Collapsed;
bdrPage2.Visibility = Visibility.Visible;
// Grab the Programs
CategoryList catList = appGrabber.CategoryList;
// Get the Uncategorized category
Category uncat = catList.GetSpecialCategory(AppCategoryType.Uncategorized);
// Get the Quick Launch category
Category quicklaunch = catList.GetSpecialCategory(AppCategoryType.QuickLaunch);
// Add apps to category if they haven't been added to one yet.
foreach (ApplicationInfo app in programsMenuAppsCollection)
{
if (app.Category == null)
{
string cat;
if (app.IsStoreApp)
cat = autoCategorizeByName(app.Name);
else
cat = autoCategorizeByName(Path.GetFileNameWithoutExtension(app.Path));
if (cat != "")
{
// Get the category - create it if it doesn't exist.
Category categoryToAdd = catList.GetCategory(cat);
if (categoryToAdd == null)
{
categoryToAdd = new Category(cat, true);
catList.Add(categoryToAdd);
}
categoryToAdd.Add(app);
}
else
{
// not a known app, add to Uncategorized
if (uncat != null)
uncat.Add(app);
}
}
}
categoryView.ItemsSource = catList;
categoryView.Visibility = Visibility.Visible;
}
}
}
| 38.882641 | 189 | 0.563353 | [
"Apache-2.0"
] | nlsantos/cairoshell | Cairo Desktop/CairoDesktop.AppGrabber/AppGrabberUI.xaml.cs | 15,905 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using Bicep.Core.Parsing;
using Bicep.Core.Syntax;
namespace Bicep.Core.UnitTests.Utils
{
public static class ParserHelper
{
public static ProgramSyntax Parse(string text)
{
var parser = new Parser(text);
return parser.Program();
}
public static SyntaxBase ParseExpression(string text, ExpressionFlags expressionFlags = ExpressionFlags.AllowComplexLiterals) => new Parser(text).Expression(expressionFlags);
public static (string file, IReadOnlyList<int> cursors) GetFileWithCursors(string fileWithCursors)
{
var bicepFile = fileWithCursors.Replace("|", "");
var cursors = new List<int>();
for (var i = 0; i < fileWithCursors.Length; i++)
{
if (fileWithCursors[i] == '|')
{
cursors.Add(i - cursors.Count);
}
}
return (bicepFile, cursors);
}
}
}
| 28.025641 | 182 | 0.594694 | [
"MIT"
] | AlanFlorance/bicep | src/Bicep.Core.UnitTests/Utils/ParserHelper.cs | 1,093 | C# |
using Leibit.Core.Common;
using Leibit.Core.Exceptions;
using Leibit.Entities.Settings;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Leibit.BLL
{
public class SettingsBLL : BLLBase
{
#region - Needs -
private static Settings m_Settings;
private readonly string m_SettingsFile;
#endregion
#region - Ctor -
public SettingsBLL()
{
m_SettingsFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "LeiBIT", "settings.json");
}
#endregion
#region - Public methods -
#region [GetSettings]
public OperationResult<Settings> GetSettings()
{
try
{
var Result = new OperationResult<Settings>();
Result.Result = __GetSettings();
Result.Succeeded = true;
return Result;
}
catch (Exception ex)
{
return new OperationResult<Settings> { Message = ex.Message };
}
}
#endregion
#region [GetPath]
public OperationResult<string> GetPath(string EstwId)
{
try
{
var Result = new OperationResult<string>();
var Settings = __GetSettings();
if (Settings.Paths.ContainsKey(EstwId))
Result.Result = Settings.Paths[EstwId];
Result.Succeeded = true;
return Result;
}
catch (Exception ex)
{
return new OperationResult<string> { Message = ex.Message };
}
}
#endregion
#region [SaveSettings]
public OperationResult<Settings> SaveSettings(Settings Setting)
{
try
{
__ValidateSettings(Setting);
__SaveSettings(Setting);
var Result = new OperationResult<Settings>();
Result.Result = __GetSettings();
Result.Succeeded = true;
return Result;
}
catch (Exception ex)
{
return new OperationResult<Settings> { Message = ex.Message };
}
}
#endregion
#region [AreSettingsComplete]
public OperationResult<bool> AreSettingsComplete()
{
try
{
var settings = __GetSettings();
__ValidateSettings(settings);
var result = new OperationResult<bool>();
result.Result = settings.Paths.Any();
result.Succeeded = true;
return result;
}
catch (ValidationFailedException)
{
var result = new OperationResult<bool>();
result.Result = false;
result.Succeeded = true;
return result;
}
catch (Exception ex)
{
return new OperationResult<bool> { Message = ex.Message };
}
}
#endregion
#region [GetWindowSettings]
public OperationResult<WindowSettings> GetWindowSettings()
{
try
{
var settings = __GetSettings();
var result = new OperationResult<WindowSettings>();
result.Result = settings.WindowSettings;
result.Succeeded = true;
return result;
}
catch (Exception ex)
{
return new OperationResult<WindowSettings> { Message = ex.Message };
}
}
#endregion
#region [SaveWindowSettings]
public OperationResult<WindowSettings> SaveWindowSettings(WindowSettings windowSettings)
{
try
{
var settings = __GetSettings();
settings.WindowSettings = windowSettings;
__SaveSettings(settings);
settings = __GetSettings();
var result = new OperationResult<WindowSettings>();
result.Result = settings.WindowSettings;
result.Succeeded = true;
return result;
}
catch (Exception ex)
{
return new OperationResult<WindowSettings> { Message = ex.Message };
}
}
#endregion
#endregion
#region - Helper methods -
private Settings __GetSettings()
{
if (m_Settings != null)
return m_Settings;
if (File.Exists(m_SettingsFile))
{
var json = File.ReadAllText(m_SettingsFile);
m_Settings = JsonConvert.DeserializeObject<Settings>(json);
__FillDefaultValuesIfNeeded(m_Settings);
}
else
m_Settings = __GetDefaultSettings();
return m_Settings;
}
private void __SaveSettings(Settings settings)
{
var settingsFile = new FileInfo(m_SettingsFile);
if (!settingsFile.Directory.Exists)
settingsFile.Directory.Create();
var json = JsonConvert.SerializeObject(settings);
File.WriteAllText(m_SettingsFile, json);
m_Settings = null;
}
private void __ValidateSettings(Settings Setting)
{
var Messages = new List<string>();
foreach (var Estw in Setting.Paths)
{
if (Estw.Value.IsNullOrWhiteSpace())
{
Messages.Add("Der Pfad zum ESTWsim Verzeichnis darf nicht leer sein.");
break;
}
if (!Directory.Exists(Estw.Value))
Messages.Add($"Das Verzeichnis '{Estw.Value}' existiert nicht.");
else if (!Directory.Exists(Path.Combine(Estw.Value, Constants.SCHEDULE_FOLDER)) || !Directory.Exists(Path.Combine(Estw.Value, Constants.LOCAL_ORDERS_FOLDER)))
Messages.Add($"Das Verzeichnis '{Estw.Value}' ist kein gültiges ESTWsim-Verzeichnis.");
}
if (Setting.DelayJustificationMinutes <= 0)
Messages.Add($"{Setting.DelayJustificationMinutes} ist keine gültige Verspätung");
if (Setting.EstwTimeout < 6)
Messages.Add("Die Zeit, nach der ein ESTW inaktiv wird, muss mindestens 6 Sekunden betragen.");
if (Setting.EstwOnlinePath.IsNullOrWhiteSpace())
Messages.Add("Der Pfad zu ESTWonline darf nicht leer sein.");
if (!Directory.Exists(Setting.EstwOnlinePath))
Messages.Add(String.Format("Das Verzeichnis '{0}' existiert nicht.", Setting.EstwOnlinePath));
else if (!File.Exists(Path.Combine(Setting.EstwOnlinePath, "ESTWonline.exe")))
Messages.Add(String.Format("Das Verzeichnis '{0}' ist kein gültiges ESTWonline-Verzeichnis.", Setting.EstwOnlinePath));
if (Messages.Count > 0)
throw new ValidationFailedException(String.Join(Environment.NewLine, Messages));
}
private void __FillDefaultValuesIfNeeded(Settings settings)
{
var defaultSettings = __GetDefaultSettings();
if (!settings.FollowUpTime.HasValue)
settings.FollowUpTime = defaultSettings.FollowUpTime;
if (!settings.AutomaticallyCheckForUpdates.HasValue)
settings.AutomaticallyCheckForUpdates = defaultSettings.AutomaticallyCheckForUpdates;
}
private Settings __GetDefaultSettings()
{
var settings = new Settings();
settings.DelayJustificationEnabled = true;
settings.DelayJustificationMinutes = 3;
settings.CheckPlausibility = true;
settings.DisplayCompleteTrainSchedule = true;
settings.EstwTimeout = 30;
settings.LoadInactiveEstws = true;
settings.AutomaticReadyMessageEnabled = true;
settings.AutomaticReadyMessageTime = 2;
settings.WindowColor = -16728065;
settings.WindowSettings = new WindowSettings { Width = 900, Height = 600, Maximized = true };
settings.EstwOnlinePath = @".\ESTWonline\";
settings.FollowUpTime = 5;
settings.AutomaticallyCheckForUpdates = true;
settings.AutomaticallyInstallUpdates = false;
return settings;
}
#endregion
}
}
| 33.631783 | 174 | 0.553187 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | jannikbecker/leib | Leibit.BLL/SettingsBLL.cs | 8,683 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type DeviceCategoryRequestBuilder.
/// </summary>
public partial class DeviceCategoryRequestBuilder : EntityRequestBuilder, IDeviceCategoryRequestBuilder
{
/// <summary>
/// Constructs a new DeviceCategoryRequestBuilder.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
public DeviceCategoryRequestBuilder(
string requestUrl,
IBaseClient client)
: base(requestUrl, client)
{
}
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
public new IDeviceCategoryRequest Request()
{
return this.Request(null);
}
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
public new IDeviceCategoryRequest Request(IEnumerable<Option> options)
{
return new DeviceCategoryRequest(this.RequestUrl, this.Client, options);
}
}
}
| 34.722222 | 153 | 0.5712 | [
"MIT"
] | AzureMentor/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/DeviceCategoryRequestBuilder.cs | 1,875 | C# |
using MDW.Entity;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MDW.Repository.Interfaces
{
public interface IRoleRepository
{
Task<List<Role>> GetRoles();
Task<Role> GetRole(string role);
Task<bool> CreateRole(Role role);
Task<bool> DeleteRole(string role);
}
} | 20.882353 | 44 | 0.64507 | [
"MIT"
] | parameshg/markdownwiki | Repository/Interfaces/IRoleRepository.cs | 357 | 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("5.BooleanVariable")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("5.BooleanVariable")]
[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("2ee58180-43db-4fe0-b57c-d872e2a07bb7")]
// 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")]
| 38.027027 | 84 | 0.745558 | [
"MIT"
] | DVidenov/TelerikHomeworks | PrimitiveDataTypes/5.BooleanVariable/Properties/AssemblyInfo.cs | 1,410 | 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;
namespace InternetPhoneBook
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
| 23.346154 | 61 | 0.665568 | [
"MIT"
] | KamilJerzyWojcik/InternetPhoneBook | InternetPhoneBook/Program.cs | 609 | C# |
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using TestCreator.Data.Converters.DTO.Interfaces;
using TestCreator.Data.Database;
using TestCreator.Data.Queries.Handlers.Common;
using TestCreator.Data.Queries.Results;
namespace TestCreator.Data.Queries.Handlers
{
public class GetTestQueryHandler : QueryHandler<GetTestQuery, GetTestQueryResult>
{
private readonly ITestDtoConverter _dtoConverter;
public GetTestQueryHandler(EfDbContext applicationDbContext, ITestDtoConverter dtoConverter) : base(applicationDbContext)
{
_dtoConverter = dtoConverter;
}
protected override GetTestQueryResult Handle(GetTestQuery request)
{
var test = DbContext.Tests.AsNoTracking().FirstOrDefault(t => t.Id.Equals(request.Id));
return new GetTestQueryResult
{
Test = _dtoConverter.Convert(test)
};
}
protected override async Task<GetTestQueryResult> HandleAsync(GetTestQuery request)
{
var test = await DbContext.Tests.AsNoTracking().FirstOrDefaultAsync(t => t.Id.Equals(request.Id));
return new GetTestQueryResult
{
Test = _dtoConverter.Convert(test)
};
}
}
}
| 32.243902 | 129 | 0.677005 | [
"MIT"
] | PDanowski/TestCreator_React | TestCreator/TestCreator.Data/Queries/Handlers/GetTestQueryHandler.cs | 1,324 | C# |
// Copyright © Conatus Creative, Inc. All rights reserved.
// Licensed under the Apache 2.0 License. See LICENSE.md in the project root for license terms.
using CRTSim;
using Microsoft.Xna.Framework.Graphics;
using Pixel3D.ActorManagement;
namespace Pixel3D.Levels
{
public interface ILevelEffect
{
void LevelEffect(GameState gameState, RenderTarget2D inputRenderTarget, SpriteBatch sb, FadeEffect fadeEffect,
int fadeLevel, bool disabled);
}
} | 31.933333 | 118 | 0.751566 | [
"Apache-2.0"
] | caogtaa/Pixel3D | src/Pixel3D.Levels/ILevelEffect.cs | 482 | C# |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using NPOI.POIFS.FileSystem;
using System.IO;
using System;
using System.Text;
using NPOI.HWPF.UserModel;
namespace NPOI.HWPF.Extractor
{
/**
* Class to extract the text from old (Word 6 / Word 95) Word Documents.
*
* This should only be used on the older files, for most uses you
* should call {@link WordExtractor} which deals properly
* with HWPF.
*
* @author Nick Burch
*/
public class Word6Extractor : POIOLE2TextExtractor
{
private HWPFOldDocument doc;
/**
* Create a new Word Extractor
* @param is InputStream Containing the word file
*/
public Word6Extractor(Stream is1)
: this(new POIFSFileSystem(is1))
{
}
/**
* Create a new Word Extractor
* @param fs POIFSFileSystem Containing the word file
*/
public Word6Extractor(POIFSFileSystem fs)
: this(fs.Root, fs)
{
}
public Word6Extractor(DirectoryNode dir, POIFSFileSystem fs)
: this(new HWPFOldDocument(dir, fs))
{
}
/**
* Create a new Word Extractor
* @param doc The HWPFOldDocument to extract from
*/
public Word6Extractor(HWPFOldDocument doc)
: base(doc)
{
this.doc = doc;
}
/**
* Get the text from the word file, as an array with one String
* per paragraph
*/
public String[] ParagraphText
{
get
{
String[] ret;
// Extract using the model code
try
{
Range r = doc.GetRange();
ret = WordExtractor.GetParagraphText(r);
}
catch (Exception)
{
// Something's up with turning the text pieces into paragraphs
// Fall back to ripping out the text pieces
ret = new String[doc.TextTable.TextPieces.Count];
for (int i = 0; i < ret.Length; i++)
{
ret[i] = doc.TextTable.TextPieces[i].GetStringBuilder().ToString();
// Fix the line endings
ret[i].Replace("\r", "\ufffe");
ret[i].Replace("\ufffe", "\r\n");
}
}
return ret;
}
}
public override String Text
{
get
{
StringBuilder text = new StringBuilder();
foreach (String t in ParagraphText)
{
text.Append(t);
}
return text.ToString();
}
}
}
}
| 30.5 | 92 | 0.497695 | [
"Apache-2.0"
] | sunshinele/npoi | scratchpad/HWPF/Extractor/Word6Extractor.cs | 3,904 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.UI.Xaml.Media.Animation
{
#if false || false || false || false
[global::Uno.NotImplemented]
#endif
public partial class EntranceNavigationTransitionInfo : global::Windows.UI.Xaml.Media.Animation.NavigationTransitionInfo
{
#if false || false || false || false
[global::Uno.NotImplemented]
public static global::Windows.UI.Xaml.DependencyProperty IsTargetElementProperty { get; } =
Windows.UI.Xaml.DependencyProperty.RegisterAttached(
"IsTargetElement", typeof(bool),
typeof(global::Windows.UI.Xaml.Media.Animation.EntranceNavigationTransitionInfo),
new FrameworkPropertyMetadata(default(bool)));
#endif
#if false || false || false || false
[global::Uno.NotImplemented]
public EntranceNavigationTransitionInfo() : base()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Media.Animation.EntranceNavigationTransitionInfo", "EntranceNavigationTransitionInfo.EntranceNavigationTransitionInfo()");
}
#endif
// Forced skipping of method Windows.UI.Xaml.Media.Animation.EntranceNavigationTransitionInfo.EntranceNavigationTransitionInfo()
// Forced skipping of method Windows.UI.Xaml.Media.Animation.EntranceNavigationTransitionInfo.IsTargetElementProperty.get
#if false || false || false || false
[global::Uno.NotImplemented]
public static bool GetIsTargetElement( global::Windows.UI.Xaml.UIElement element)
{
return (bool)element.GetValue(IsTargetElementProperty);
}
#endif
#if false || false || false || false
[global::Uno.NotImplemented]
public static void SetIsTargetElement( global::Windows.UI.Xaml.UIElement element, bool value)
{
element.SetValue(IsTargetElementProperty, value);
}
#endif
}
}
| 42.604651 | 216 | 0.774017 | [
"Apache-2.0"
] | nv-ksavaria/Uno | src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml.Media.Animation/EntranceNavigationTransitionInfo.cs | 1,832 | C# |
using ChartJs.Blazor.Common.Axes.Ticks;
using ChartJs.Blazor.Common.Enums;
namespace ChartJs.Blazor.Common.Axes;
/// <summary>
/// The linear scale is use to chart numerical data. It can be placed on either the x or y axis.
/// As the name suggests, linear interpolation is used to determine where a value lies on the axis.
/// <para>As per documentation <a href="https://www.chartjs.org/docs/latest/axes/cartesian/linear.html">here (Chart.js)</a>.</para>
/// </summary>
public class LinearCartesianAxis : CartesianAxis<LinearCartesianTicks>
{
/// <inheritdoc/>
public override AxisType Type => AxisType.Linear;
} | 41.6 | 131 | 0.741987 | [
"MIT"
] | Verent/ChartJs.Blazor | src/ChartJs.Blazor/Common/Axes/LinearCartesianAxis.cs | 626 | C# |
// Copyright 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using ArcGISRuntime.Samples.Managers;
using Esri.ArcGISRuntime.ArcGISServices;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks;
using Esri.ArcGISRuntime.Tasks.Offline;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.Xamarin.Forms;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Xamarin.Forms;
using Colors = System.Drawing.Color;
namespace ArcGISRuntime.Samples.EditAndSyncFeatures
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
"Edit and sync features",
"Data",
"This sample demonstrates how to synchronize offline edits with a feature service.",
"1. Pan and zoom to the area you would like to download point features for, ensuring that all point features are within the rectangle.\n2. Tap the 'generate' button. This will start the process of generating the offline geodatabase.\n3. Tap on a point feature within the area of the generated geodatabase. Then tap on the screen (anywhere within the range of the local geodatabase) to move the point to that location.\n4. Tap the 'Sync Geodatabase' button to synchronize the changes back to the feature service.\n\n Note that the basemap for this sample is downloaded from ArcGIS Online automatically.")]
[ArcGISRuntime.Samples.Shared.Attributes.OfflineData("3f1bbf0ec70b409a975f5c91f363fe7d")]
public partial class EditAndSyncFeatures : ContentPage
{
// Enumeration to track which phase of the workflow the sample is in.
private enum EditState
{
NotReady, // Geodatabase has not yet been generated.
Editing, // A feature is in the process of being moved.
Ready // The geodatabase is ready for synchronization or further edits.
}
// URL for a feature service that supports geodatabase generation.
private Uri _featureServiceUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/WildfireSync/FeatureServer");
// Path to the geodatabase file on disk.
private string _gdbPath;
// Task to be used for generating the geodatabase.
private GeodatabaseSyncTask _gdbSyncTask;
// Flag to indicate which stage of the edit process the sample is in.
private EditState _readyForEdits = EditState.NotReady;
// Hold a reference to the generated geodatabase.
private Geodatabase _resultGdb;
public EditAndSyncFeatures()
{
InitializeComponent();
// Create the UI, setup the control references and execute initialization.
Initialize();
}
private async void Initialize()
{
// Create a tile cache and load it with the SanFrancisco streets tpk.
try
{
TileCache tileCache = new TileCache(DataManager.GetDataFolder("3f1bbf0ec70b409a975f5c91f363fe7d", "SanFrancisco.tpk"));
// Create the corresponding layer based on the tile cache.
ArcGISTiledLayer tileLayer = new ArcGISTiledLayer(tileCache);
// Create the basemap based on the tile cache.
Basemap sfBasemap = new Basemap(tileLayer);
// Create the map with the tile-based basemap.
Map myMap = new Map(sfBasemap);
// Assign the map to the MapView.
myMapView.Map = myMap;
// Create a new symbol for the extent graphic.
SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Colors.Red, 2);
// Create a graphics overlay for the extent graphic and apply a renderer.
GraphicsOverlay extentOverlay = new GraphicsOverlay
{
Renderer = new SimpleRenderer(lineSymbol)
};
// Add the graphics overlay to the map view.
myMapView.GraphicsOverlays.Add(extentOverlay);
// Set up an event handler for when the viewpoint (extent) changes.
myMapView.ViewpointChanged += MapViewExtentChanged;
// Create a task for generating a geodatabase (GeodatabaseSyncTask).
_gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri);
// Add all layers from the service to the map.
foreach (IdInfo layer in _gdbSyncTask.ServiceInfo.LayerInfos)
{
// Get the URL for this layer.
Uri onlineTableUri = new Uri(_featureServiceUri + "/" + layer.Id);
// Create the ServiceFeatureTable.
ServiceFeatureTable onlineTable = new ServiceFeatureTable(onlineTableUri);
// Wait for the table to load.
await onlineTable.LoadAsync();
// Skip tables that aren't for point features.{
if (onlineTable.GeometryType != GeometryType.Point)
{
continue;
}
// Add the layer to the map's operational layers if load succeeds.
if (onlineTable.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded)
{
myMap.OperationalLayers.Add(new FeatureLayer(onlineTable));
}
}
// Update the graphic - needed in case the user decides not to interact before pressing the button.
UpdateMapExtent();
// Enable the generate button now that sample is ready.
myGenerateButton.IsEnabled = true;
}
catch (Exception ex)
{
await ((Page)Parent).DisplayAlert("Error", ex.ToString(), "OK");
}
}
private async void GeoViewTapped(object sender, GeoViewInputEventArgs e)
{
try
{
// Disregard if not ready for edits.
if (_readyForEdits == EditState.NotReady) { return; }
// If an edit is in process, finish it.
if (_readyForEdits == EditState.Editing)
{
// Hold a list of any selected features.
List<Feature> selectedFeatures = new List<Feature>();
// Get all selected features then clear selection.
foreach (FeatureLayer layer in myMapView.Map.OperationalLayers)
{
// Get the selected features.
FeatureQueryResult layerFeatures = await layer.GetSelectedFeaturesAsync();
// FeatureQueryResult implements IEnumerable, so it can be treated as a collection of features.
selectedFeatures.AddRange(layerFeatures);
// Clear the selection.
layer.ClearSelection();
}
// Update all selected features' geometry.
foreach (Feature feature in selectedFeatures)
{
// Get a reference to the correct feature table for the feature.
GeodatabaseFeatureTable table = (GeodatabaseFeatureTable)feature.FeatureTable;
// Ensure the geometry type of the table is point.
if (table.GeometryType != GeometryType.Point)
{
continue;
}
// Set the new geometry.
feature.Geometry = e.Location;
// Update the feature in the table.
await table.UpdateFeatureAsync(feature);
}
// Update the edit state.
_readyForEdits = EditState.Ready;
// Enable the sync button.
mySyncButton.IsEnabled = true;
// Update the help label.
MyHelpLabel.Text = "4. Click 'Synchronize' or keep editing";
}
// Otherwise, start an edit.
else
{
// Define a tolerance for use with identifying the feature.
double tolerance = 15 * myMapView.UnitsPerPixel;
// Define the selection envelope.
Envelope selectionEnvelope = new Envelope(e.Location.X - tolerance, e.Location.Y - tolerance, e.Location.X + tolerance, e.Location.Y + tolerance);
// Define query parameters for feature selection.
QueryParameters query = new QueryParameters()
{
Geometry = selectionEnvelope
};
// Track whether any selections were made.
bool selectedFeature = false;
// Select the feature in all applicable tables.
foreach (FeatureLayer layer in myMapView.Map.OperationalLayers)
{
FeatureQueryResult res = await layer.SelectFeaturesAsync(query, Esri.ArcGISRuntime.Mapping.SelectionMode.New);
selectedFeature = selectedFeature || res.Any();
}
// Only update state if a feature was selected.
if (selectedFeature)
{
// Set the edit state.
_readyForEdits = EditState.Editing;
// Update the help label.
MyHelpLabel.Text = "3. Tap on the map to move the point";
}
}
}
catch (Exception ex)
{
await ((Page)Parent).DisplayAlert("Error", ex.ToString(), "OK");
}
}
private void UpdateMapExtent()
{
// Return if mapview is null.
if (myMapView == null) { return; }
// Get the new viewpoint.
Viewpoint myViewPoint = myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
// Return if viewpoint is null.
if (myViewPoint == null) { return; }
// Get the updated extent for the new viewpoint.
Envelope extent = myViewPoint.TargetGeometry as Envelope;
// Return if extent is null.
if (extent == null) { return; }
// Create an envelope that is a bit smaller than the extent.
EnvelopeBuilder envelopeBldr = new EnvelopeBuilder(extent);
envelopeBldr.Expand(0.80);
// Get the (only) graphics overlay in the map view.
GraphicsOverlay extentOverlay = myMapView.GraphicsOverlays.FirstOrDefault();
// Return if the extent overlay is null.
if (extentOverlay == null) { return; }
// Get the extent graphic.
Graphic extentGraphic = extentOverlay.Graphics.FirstOrDefault();
// Create the extent graphic and add it to the overlay if it doesn't exist.
if (extentGraphic == null)
{
extentGraphic = new Graphic(envelopeBldr.ToGeometry());
extentOverlay.Graphics.Add(extentGraphic);
}
else
{
// Otherwise, update the graphic's geometry.
extentGraphic.Geometry = envelopeBldr.ToGeometry();
}
}
private async Task StartGeodatabaseGeneration()
{
// Update the geodatabase path.
_gdbPath = $"{Path.GetTempFileName()}.geodatabase";
// Create a task for generating a geodatabase (GeodatabaseSyncTask).
_gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri);
// Get the (only) graphic in the map view.
Graphic redPreviewBox = myMapView.GraphicsOverlays.First().Graphics.First();
// Get the current extent of the red preview box.
Envelope extent = redPreviewBox.Geometry as Envelope;
// Get the default parameters for the generate geodatabase task.
GenerateGeodatabaseParameters generateParams = await _gdbSyncTask.CreateDefaultGenerateGeodatabaseParametersAsync(extent);
// Create a generate geodatabase job.
GenerateGeodatabaseJob generateGdbJob = _gdbSyncTask.GenerateGeodatabase(generateParams, _gdbPath);
// Show the progress bar.
myProgressBar.IsVisible = true;
// Handle the progress changed event with an inline (lambda) function to show the progress bar.
generateGdbJob.ProgressChanged += (sender, e) =>
{
// Get the job.
GenerateGeodatabaseJob job = (GenerateGeodatabaseJob)sender;
// Update the progress bar.
UpdateProgressBar(job.Progress);
};
// Start the job.
generateGdbJob.Start();
// Get the result.
_resultGdb = await generateGdbJob.GetResultAsync();
// Hide the progress bar.
myProgressBar.IsVisible = false;
// Handle the job completion.
HandleGenerationStatusChange(generateGdbJob);
}
private async void HandleGenerationStatusChange(GenerateGeodatabaseJob job)
{
// If the job completed successfully, add the geodatabase data to the map.
if (job.Status == JobStatus.Succeeded)
{
// Clear out the existing layers.
myMapView.Map.OperationalLayers.Clear();
// Loop through all feature tables in the geodatabase and add a new layer to the map.
foreach (GeodatabaseFeatureTable table in _resultGdb.GeodatabaseFeatureTables)
{
// Skip non-point tables.
await table.LoadAsync();
if (table.GeometryType != GeometryType.Point)
{
continue;
}
// Create a new feature layer for the table.
FeatureLayer layer = new FeatureLayer(table);
// Add the new layer to the map.
myMapView.Map.OperationalLayers.Add(layer);
}
// Enable editing features.
_readyForEdits = EditState.Ready;
// Update the help label.
MyHelpLabel.Text = "2. Tap a point feature to select";
}
// See if the job failed.
else if (job.Status == JobStatus.Failed)
{
// Create a message to show the user.
string message = "Generate geodatabase job failed";
// Show an error message (if there is one).
if (job.Error != null)
{
message += ": " + job.Error.Message;
}
else
{
// If no error, show messages from the job.
foreach (JobMessage m in job.Messages)
{
// Get the text from the JobMessage and add it to the output string.
message += "\n" + m.Message;
}
}
// Show the message.
((Page)Parent).DisplayAlert("Error", message, "OK");
}
}
private async Task SyncGeodatabase()
{
// Return if not ready.
if (_readyForEdits != EditState.Ready) { return; }
// Create parameters for the sync task.
SyncGeodatabaseParameters parameters = new SyncGeodatabaseParameters()
{
GeodatabaseSyncDirection = SyncDirection.Bidirectional,
RollbackOnFailure = false
};
// Get the layer ID for each feature table in the geodatabase, then add to the sync job.
foreach (GeodatabaseFeatureTable table in _resultGdb.GeodatabaseFeatureTables)
{
// Get the ID for the layer.
long id = table.ServiceLayerId;
// Create the SyncLayerOption.
SyncLayerOption option = new SyncLayerOption(id);
// Add the option.
parameters.LayerOptions.Add(option);
}
// Create job.
SyncGeodatabaseJob job = _gdbSyncTask.SyncGeodatabase(parameters, _resultGdb);
// Subscribe to progress updates.
job.ProgressChanged += (o, e) =>
{
UpdateProgressBar(job.Progress);
};
// Show the progress bar.
myProgressBar.IsVisible = true;
// Disable the sync button.
mySyncButton.IsEnabled = false;
// Start the sync.
job.Start();
// Wait for the result.
await job.GetResultAsync();
// Hide the progress bar.
myProgressBar.IsVisible = false;
// Do the rest of the work.
HandleSyncCompleted(job);
// Re-enable the sync button.
mySyncButton.IsEnabled = true;
}
private void HandleSyncCompleted(SyncGeodatabaseJob job)
{
// Tell the user about job completion.
if (job.Status == JobStatus.Succeeded)
{
((Page)Parent).DisplayAlert("Alert", "Geodatabase synchronization succeeded.", "OK");
}
// See if the job failed.
else if (job.Status == JobStatus.Failed)
{
// Create a message to show the user.
string message = "Sync geodatabase job failed";
// Show an error message (if there is one).
if (job.Error != null)
{
message += ": " + job.Error.Message;
}
else
{
// If no error, show messages from the job.
foreach (JobMessage m in job.Messages)
{
// Get the text from the JobMessage and add it to the output string.
message += "\n" + m.Message;
}
}
// Show the message.
((Page)Parent).DisplayAlert("Error", message, "OK");
}
}
private async void GenerateButton_Clicked(object sender, EventArgs e)
{
// Fix the selection graphic extent.
myMapView.ViewpointChanged -= MapViewExtentChanged;
// Disable the generate button.
try
{
myGenerateButton.IsEnabled = false;
// Call the geodatabase generation method.
await StartGeodatabaseGeneration();
}
catch (Exception ex)
{
await ((Page)Parent).DisplayAlert("Error", ex.ToString(), "OK");
}
}
private void MapViewExtentChanged(object sender, EventArgs e)
{
// Call the map extent update method.
UpdateMapExtent();
}
private void UpdateProgressBar(int progress)
{
// Due to the nature of the threading implementation,
// the dispatcher needs to be used to interact with the UI.
// The dispatcher takes an Action, provided here as a lambda function.
Device.BeginInvokeOnMainThread(() =>
{
// Update the progress bar value.
myProgressBar.Progress = progress / 100.0;
});
}
private async void SyncButton_Click(object sender, EventArgs e)
{
try
{
await SyncGeodatabase();
}
catch (Exception ex)
{
await ((Page)Parent).DisplayAlert("Alert", ex.ToString(), "OK");
}
}
}
} | 40.022945 | 612 | 0.554414 | [
"Apache-2.0"
] | ChrisFrenchPDX/arcgis-runtime-samples-dotnet | src/Forms/Shared/Samples/Data/EditAndSyncFeatures/EditAndSyncFeatures.xaml.cs | 20,932 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("01.delegateSample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HP Inc.")]
[assembly: AssemblyProduct("01.delegateSample")]
[assembly: AssemblyCopyright("Copyright © HP Inc. 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("16080c78-817d-4cc8-96c8-88eafbd24320")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 26.027027 | 57 | 0.717549 | [
"MIT"
] | 2539187294/GitHub_Test | SangFor.LHT/01.delegateSample/Properties/AssemblyInfo.cs | 1,304 | C# |
//-----------------------------------------------------------------------------
// Filename: DtlsSrtpTransport.cs
//
// Description: This class represents the DTLS SRTP transport connection to use
// as Client or Server.
//
// Author(s):
// Rafael Soares (raf.csoares@kyubinteractive.com)
//
// History:
// 01 Jul 2020 Rafael Soares Created.
// 02 Jul 2020 Aaron Clauson Switched underlying transport from socket to
// piped memory stream.
//
// License:
// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Org.BouncyCastle.Crypto.Tls;
using Org.BouncyCastle.Security;
using SIPSorcery.Sys;
namespace SIPSorcery.Net
{
public class DtlsSrtpTransport : DatagramTransport, IDisposable
{
public const int DEFAULT_MTU = 1500;
public const int MIN_IP_OVERHEAD = 20;
public const int MAX_IP_OVERHEAD = MIN_IP_OVERHEAD + 64;
public const int UDP_OVERHEAD = 8;
public const int DEFAULT_TIMEOUT_MILLISECONDS = 20000;
public const int DTLS_RETRANSMISSION_CODE = -1;
public const int DTLS_RECEIVE_ERROR_CODE = -2;
private static readonly ILogger logger = Log.Logger;
private static readonly Random random = new Random();
private IPacketTransformer srtpEncoder;
private IPacketTransformer srtpDecoder;
private IPacketTransformer srtcpEncoder;
private IPacketTransformer srtcpDecoder;
IDtlsSrtpPeer connection = null;
/// <summary>The collection of chunks to be written.</summary>
private BlockingCollection<byte[]> _chunks = new BlockingCollection<byte[]>(new ConcurrentQueue<byte[]>());
public DtlsTransport Transport { get; private set; }
/// <summary>
/// Sets the period in milliseconds that the handshake attempt will timeout
/// after.
/// </summary>
public int TimeoutMilliseconds = DEFAULT_TIMEOUT_MILLISECONDS;
public Action<byte[]> OnDataReady;
/// <summary>
/// Parameters:
/// - alert level,
/// - alert type,
/// - alert description.
/// </summary>
public event Action<AlertLevelsEnum, AlertTypesEnum, string> OnAlert;
private System.DateTime startTime = System.DateTime.MinValue;
private bool _isClosed = false;
// Network properties
private int mtu;
private int receiveLimit;
private int sendLimit;
private volatile bool handshakeComplete;
private volatile bool handshakeFailed;
private volatile bool handshaking;
public DtlsSrtpTransport(IDtlsSrtpPeer connection, int mtu = DEFAULT_MTU)
{
// Network properties
this.mtu = mtu;
this.receiveLimit = System.Math.Max(0, mtu - MIN_IP_OVERHEAD - UDP_OVERHEAD);
this.sendLimit = System.Math.Max(0, mtu - MAX_IP_OVERHEAD - UDP_OVERHEAD);
this.connection = connection;
connection.OnAlert += (level, type, description) => OnAlert?.Invoke(level, type, description);
}
public IPacketTransformer SrtpDecoder
{
get
{
return srtpDecoder;
}
}
public IPacketTransformer SrtpEncoder
{
get
{
return srtpEncoder;
}
}
public IPacketTransformer SrtcpDecoder
{
get
{
return srtcpDecoder;
}
}
public IPacketTransformer SrtcpEncoder
{
get
{
return srtcpEncoder;
}
}
public bool IsHandshakeComplete()
{
return handshakeComplete;
}
public bool IsHandshakeFailed()
{
return handshakeFailed;
}
public bool IsHandshaking()
{
return handshaking;
}
public bool DoHandshake()
{
if (connection.IsClient())
{
return DoHandshakeAsClient();
}
else
{
return DoHandshakeAsServer();
}
}
public bool IsClient
{
get { return connection.IsClient(); }
}
public bool DoHandshakeAsClient()
{
logger.LogDebug("DTLS commencing handshake as client.");
if (!handshaking && !handshakeComplete)
{
this.startTime = System.DateTime.Now;
this.handshaking = true;
SecureRandom secureRandom = new SecureRandom();
DtlsClientProtocol clientProtocol = new DtlsClientProtocol(secureRandom);
try
{
var client = (DtlsSrtpClient)connection;
// Perform the handshake in a non-blocking fashion
Transport = clientProtocol.Connect(client, this);
// Prepare the shared key to be used in RTP streaming
//client.PrepareSrtpSharedSecret();
// Generate encoders for DTLS traffic
if (client.GetSrtpPolicy() != null)
{
srtpDecoder = GenerateRtpDecoder();
srtpEncoder = GenerateRtpEncoder();
srtcpDecoder = GenerateRtcpDecoder();
srtcpEncoder = GenerateRtcpEncoder();
}
// Declare handshake as complete
handshakeComplete = true;
handshakeFailed = false;
handshaking = false;
// Warn listeners handshake completed
//UnityEngine.Debug.Log("DTLS Handshake Completed");
return true;
}
catch (System.Exception excp)
{
logger.LogWarning($"DTLS handshake as client failed. {excp.Message}");
// Declare handshake as failed
handshakeComplete = false;
handshakeFailed = true;
handshaking = false;
// Warn listeners handshake completed
//UnityEngine.Debug.Log("DTLS Handshake failed\n" + e);
}
}
return false;
}
public bool DoHandshakeAsServer()
{
logger.LogDebug("DTLS commencing handshake as server.");
if (!handshaking && !handshakeComplete)
{
this.startTime = System.DateTime.Now;
this.handshaking = true;
SecureRandom secureRandom = new SecureRandom();
DtlsServerProtocol serverProtocol = new DtlsServerProtocol(secureRandom);
try
{
var server = (DtlsSrtpServer)connection;
// Perform the handshake in a non-blocking fashion
Transport = serverProtocol.Accept(server, this);
// Prepare the shared key to be used in RTP streaming
//server.PrepareSrtpSharedSecret();
// Generate encoders for DTLS traffic
if (server.GetSrtpPolicy() != null)
{
srtpDecoder = GenerateRtpDecoder();
srtpEncoder = GenerateRtpEncoder();
srtcpDecoder = GenerateRtcpDecoder();
srtcpEncoder = GenerateRtcpEncoder();
}
// Declare handshake as complete
handshakeComplete = true;
handshakeFailed = false;
handshaking = false;
// Warn listeners handshake completed
//UnityEngine.Debug.Log("DTLS Handshake Completed");
return true;
}
catch (System.Exception excp)
{
logger.LogWarning($"DTLS handshake as server failed. {excp.Message}");
// Declare handshake as failed
handshakeComplete = false;
handshakeFailed = true;
handshaking = false;
// Warn listeners handshake completed
//UnityEngine.Debug.Log("DTLS Handshake failed\n"+ e);
}
}
return false;
}
public Certificate GetRemoteCertificate()
{
return connection.GetRemoteCertificate();
}
protected byte[] GetMasterServerKey()
{
return connection.GetSrtpMasterServerKey();
}
protected byte[] GetMasterServerSalt()
{
return connection.GetSrtpMasterServerSalt();
}
protected byte[] GetMasterClientKey()
{
return connection.GetSrtpMasterClientKey();
}
protected byte[] GetMasterClientSalt()
{
return connection.GetSrtpMasterClientSalt();
}
protected SrtpPolicy GetSrtpPolicy()
{
return connection.GetSrtpPolicy();
}
protected SrtpPolicy GetSrtcpPolicy()
{
return connection.GetSrtcpPolicy();
}
protected IPacketTransformer GenerateRtpEncoder()
{
return GenerateTransformer(connection.IsClient(), true);
}
protected IPacketTransformer GenerateRtpDecoder()
{
//Generate the reverse result of "GenerateRtpEncoder"
return GenerateTransformer(!connection.IsClient(), true);
}
protected IPacketTransformer GenerateRtcpEncoder()
{
var isClient = connection is DtlsSrtpClient;
return GenerateTransformer(connection.IsClient(), false);
}
protected IPacketTransformer GenerateRtcpDecoder()
{
//Generate the reverse result of "GenerateRctpEncoder"
return GenerateTransformer(!connection.IsClient(), false);
}
protected IPacketTransformer GenerateTransformer(bool isClient, bool isRtp)
{
SrtpTransformEngine engine = null;
if (!isClient)
{
engine = new SrtpTransformEngine(GetMasterServerKey(), GetMasterServerSalt(), GetSrtpPolicy(), GetSrtcpPolicy());
}
else
{
engine = new SrtpTransformEngine(GetMasterClientKey(), GetMasterClientSalt(), GetSrtpPolicy(), GetSrtcpPolicy());
}
if (isRtp)
{
return engine.GetRTPTransformer();
}
else
{
return engine.GetRTCPTransformer();
}
}
public byte[] UnprotectRTP(byte[] packet, int offset, int length)
{
lock (this.srtpDecoder)
{
return this.srtpDecoder.ReverseTransform(packet, offset, length);
}
}
public int UnprotectRTP(byte[] payload, int length, out int outLength)
{
var result = UnprotectRTP(payload, 0, length);
if (result == null)
{
outLength = 0;
return -1;
}
System.Buffer.BlockCopy(result, 0, payload, 0, result.Length);
outLength = result.Length;
return 0; //No Errors
}
public byte[] ProtectRTP(byte[] packet, int offset, int length)
{
lock (this.srtpEncoder)
{
return this.srtpEncoder.Transform(packet, offset, length);
}
}
public int ProtectRTP(byte[] payload, int length, out int outLength)
{
var result = ProtectRTP(payload, 0, length);
if (result == null)
{
outLength = 0;
return -1;
}
System.Buffer.BlockCopy(result, 0, payload, 0, result.Length);
outLength = result.Length;
return 0; //No Errors
}
public byte[] UnprotectRTCP(byte[] packet, int offset, int length)
{
lock (this.srtcpDecoder)
{
return this.srtcpDecoder.ReverseTransform(packet, offset, length);
}
}
public int UnprotectRTCP(byte[] payload, int length, out int outLength)
{
var result = UnprotectRTCP(payload, 0, length);
if (result == null)
{
outLength = 0;
return -1;
}
System.Buffer.BlockCopy(result, 0, payload, 0, result.Length);
outLength = result.Length;
return 0; //No Errors
}
public byte[] ProtectRTCP(byte[] packet, int offset, int length)
{
lock (this.srtcpEncoder)
{
return this.srtcpEncoder.Transform(packet, offset, length);
}
}
public int ProtectRTCP(byte[] payload, int length, out int outLength)
{
var result = ProtectRTCP(payload, 0, length);
if (result == null)
{
outLength = 0;
return -1;
}
System.Buffer.BlockCopy(result, 0, payload, 0, result.Length);
outLength = result.Length;
return 0; //No Errors
}
/// <summary>
/// Returns the number of milliseconds remaining until a timeout occurs.
/// </summary>
private int GetMillisecondsRemaining()
{
return TimeoutMilliseconds - (int)(System.DateTime.Now - this.startTime).TotalMilliseconds;
}
public int GetReceiveLimit()
{
return this.receiveLimit;
}
public int GetSendLimit()
{
return this.sendLimit;
}
public void WriteToRecvStream(byte[] buf)
{
_chunks.Add(buf);
}
public int Read(byte[] buffer, int offset, int count, int timeout)
{
try
{
if (_chunks.TryTake(out var item, timeout))
{
Buffer.BlockCopy(item, 0, buffer, 0, item.Length);
return item.Length;
}
}
catch (ObjectDisposedException) { }
catch (ArgumentNullException) { }
return DTLS_RETRANSMISSION_CODE;
}
public int Receive(byte[] buf, int off, int len, int waitMillis)
{
if (!handshakeComplete)
{
// The timeout for the handshake applies from when it started rather than
// for each individual receive..
int millisecondsRemaining = GetMillisecondsRemaining();
//Handshake reliable contains too long default backoff times
waitMillis = System.Math.Max(100, waitMillis / (random.Next(100, 1000)));
if (millisecondsRemaining <= 0)
{
logger.LogWarning($"DTLS transport timed out after {TimeoutMilliseconds}ms waiting for handshake from remote {(connection.IsClient() ? "server" : "client")}.");
throw new TimeoutException();
}
else if (!_isClosed)
{
waitMillis = (int)System.Math.Min(waitMillis, millisecondsRemaining);
return Read(buf, off, len, waitMillis);
}
else
{
return DTLS_RECEIVE_ERROR_CODE;
}
}
else if (!_isClosed)
{
return Read(buf, off, len, waitMillis);
}
else
{
return DTLS_RECEIVE_ERROR_CODE;
}
}
public void Send(byte[] buf, int off, int len)
{
if (len != buf.Length)
{
// Only create a new buffer and copy bytes if the length is different
var tempBuf = new byte[len];
Buffer.BlockCopy(buf, off, tempBuf, 0, len);
buf = tempBuf;
}
OnDataReady?.Invoke(buf);
}
public virtual void Close()
{
_isClosed = true;
this.startTime = System.DateTime.MinValue;
this._chunks?.Dispose();
}
/// <summary>
/// Close the transport if the instance is out of scope.
/// </summary>
protected void Dispose(bool disposing)
{
Close();
}
/// <summary>
/// Close the transport if the instance is out of scope.
/// </summary>
public void Dispose()
{
Close();
}
}
}
| 31.951673 | 180 | 0.51879 | [
"MIT"
] | GB28181/GB28181.Platform2016 | sipsorcery/src/net/DtlsSrtp/DtlsSrtpTransport.cs | 17,192 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DbContextModels.AdventureWorks
{
using System;
using System.Collections.Generic;
public partial class Department
{
public Department()
{
this.EmployeeDepartmentHistories = new HashSet<EmployeeDepartmentHistory>();
}
public short DepartmentID { get; set; }
public string Name { get; set; }
public string GroupName { get; set; }
public System.DateTime ModifiedDate { get; set; }
public virtual ICollection<EmployeeDepartmentHistory> EmployeeDepartmentHistories { get; set; }
}
}
| 33.966667 | 103 | 0.562316 | [
"Apache-2.0"
] | Daniel-Svensson/OpenRiaServices | src/OpenRiaServices.EntityFramework/Test/DbContextModel/AdventureWorks/Department.cs | 1,019 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\IEntityCollectionWithReferencesRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
/// <summary>
/// The interface IServicePrincipalTransitiveMemberOfCollectionWithReferencesRequestBuilder.
/// </summary>
public partial interface IServicePrincipalTransitiveMemberOfCollectionWithReferencesRequestBuilder : IBaseRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
IServicePrincipalTransitiveMemberOfCollectionWithReferencesRequest Request();
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
IServicePrincipalTransitiveMemberOfCollectionWithReferencesRequest Request(IEnumerable<Option> options);
/// <summary>
/// Gets an <see cref="IDirectoryObjectWithReferenceRequestBuilder"/> for the specified DirectoryObject.
/// </summary>
/// <param name="id">The ID for the DirectoryObject.</param>
/// <returns>The <see cref="IDirectoryObjectWithReferenceRequestBuilder"/>.</returns>
IDirectoryObjectWithReferenceRequestBuilder this[string id] { get; }
/// <summary>
/// Gets an <see cref="IServicePrincipalTransitiveMemberOfCollectionReferencesRequestBuilder"/> for the references in the collection.
/// </summary>
/// <returns>The <see cref="IServicePrincipalTransitiveMemberOfCollectionReferencesRequestBuilder"/>.</returns>
IServicePrincipalTransitiveMemberOfCollectionReferencesRequestBuilder References { get; }
}
}
| 47.574468 | 153 | 0.657871 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IServicePrincipalTransitiveMemberOfCollectionWithReferencesRequestBuilder.cs | 2,236 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace BlazorStyled.Internal
{
internal static class StringExtensions
{
private static readonly Random rnd = new Random();
public static string RemoveDuplicateSpaces(this string source)
{
return Regex.Replace(source, @"\s+", " ").Trim();
}
public static string RemoveComments(this string source)
{
return Regex.Replace(source, @"\/\*[\s\S]*?\*\/", string.Empty).Trim();
}
public static IList<ParsedClass> GetClasses(this string source)
{
return source.GetClasses(null);
}
public static IList<ParsedClass> GetClasses(this string source, string classname)
{
List<ParsedClass> classes = new List<ParsedClass>();
ParsedClass root = null, parent = null;
if (source.IndexOf('{') == -1)
{
ParsedClass parsedClass = new ParsedClass(classname, source.Trim());
classes.Add(parsedClass);
}
else
{
ReadOnlySpan<char> main = source.AsSpan().Trim();
bool first = true;
while (main.IndexOf('{') != -1)
{
int startRules = main.IndexOf('{');
int endRules = main.IndexOf('}');
ReadOnlySpan<char> classnameSpan = main.Slice(0, startRules).Trim();
ReadOnlySpan<char> rules = main.Slice(startRules + 1, endRules - startRules - 1).Trim();
if (first && classnameSpan.IndexOf(';') != -1)
{
int lastSemiColon = classnameSpan.LastIndexOf(';');
ParsedClass baseClass = new ParsedClass(classname, main.Slice(0, lastSemiColon + 1).ToString());
root = baseClass;
classes.Add(baseClass);
classnameSpan = classnameSpan.Slice(lastSemiColon + 1);
}
ParsedClass parsedClass = new ParsedClass(classnameSpan.ToString(), rules.ToString());
if (parsedClass.IsParent)
{
parent = parsedClass;
if (root == null)
{
classes.Add(parsedClass);
}
else
{
root.ChildClasses.Add(parsedClass);
}
}
else
{
if (parent == null)
{
if (root == null)
{
classes.Add(parsedClass);
}
else
{
root.ChildClasses.Add(parsedClass);
}
}
else
{
parent.ChildClasses.Add(parsedClass);
}
}
if (parsedClass.IsKeyframes || (parsedClass.IsMediaQuery && parsedClass.Declarations == null)) //|| (parsedClass.IsMediaQuery && parsedClass.Declarations != null)
{
endRules = startRules;
}
first = false;
main = main.Slice(endRules + 1);
if(main.TrimStart().IndexOf('}') == 0)
{
if(main.Length > 2)
{
main = main.Slice(2);
}
parent = null;
}
}
}
List<ParsedClass> ret = new List<ParsedClass>();
foreach (ParsedClass parsedClass in classes)
{
if (parsedClass.IsDynamic)
{
ret.Add(parsedClass);
foreach (ParsedClass child in parsedClass.ChildClasses)
{
child.Parent = parsedClass.Name;
child.Name = child.Name.Replace("&", "." + parsedClass.Name);
ret.Add(child);
}
}
else if (parsedClass.IsMediaQuery)
{
if (parsedClass.ChildClasses == null || (parsedClass.ChildClasses != null && parsedClass.ChildClasses.Count > 0))
{
foreach (ParsedClass child in parsedClass.ChildClasses)
{
child.Name = child.Name.Replace("&", "." + child.Hash);
}
ret.Add(parsedClass);
}
}
else
{
ret.Add(parsedClass);
}
}
return ret;
}
public static int GetStableHashCode(this string str)
{
if (str == null)
{
return 0;
}
unchecked
{
int hash1 = 5381;
int hash2 = hash1;
for (int i = 0; i < str.Length && str[i] != '\0'; i += 2)
{
hash1 = ((hash1 << 5) + hash1) ^ str[i];
if (i == str.Length - 1 || str[i + 1] == '\0')
{
break;
}
hash2 = ((hash2 << 5) + hash2) ^ str[i + 1];
}
return hash1 + (hash2 * 1566083941);
}
}
public static string GetStableHashCodeString(this string str)
{
uint i = (uint)str.GetStableHashCode();
return i.ConvertToBase64Arithmetic();
}
public static string GetRandomHashCodeString(this string str)
{
uint i = (uint)rnd.Next();
return i.ConvertToBase64Arithmetic();
}
public static string ConvertToBase64Arithmetic(this uint i)
{
const string alphabet = "abcdefghijklmnopqrstuvwxyz";
uint length = (uint)alphabet.Length;
StringBuilder sb = new StringBuilder();
int pos = 0;
do
{
sb.Append(alphabet[(int)(i % length)]);
i /= length;
pos++;
if (pos == 4)
{
pos = 0;
if (i != 0)
{
sb.Append('-');
}
}
} while (i != 0);
return sb.ToString();
}
}
} | 35.647959 | 182 | 0.401603 | [
"Unlicense"
] | BlazorHub/BlazorStyled | src/BlazorStyled/Internal/StringExtensions.cs | 6,989 | C# |
using GymHub.Data.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
namespace GymHub.Web.Areas.Identity.Pages.Account
{
[AllowAnonymous]
[ValidateAntiForgeryToken]
public class LogoutModel : PageModel
{
private readonly SignInManager<User> _signInManager;
private readonly ILogger<LogoutModel> _logger;
public LogoutModel(SignInManager<User> signInManager, ILogger<LogoutModel> logger)
{
_signInManager = signInManager;
_logger = logger;
}
public void OnGet()
{
}
public async Task<IActionResult> OnPost(string returnUrl = null)
{
await _signInManager.SignOutAsync();
_logger.LogInformation("User logged out.");
if (returnUrl != null)
{
return LocalRedirect(returnUrl);
}
else
{
return Redirect("/");
}
}
}
}
| 26.790698 | 90 | 0.618924 | [
"MIT"
] | rosenkolev1/GymHub-SoftUni-CSharp-WebProject | GymHub/GymHub.Web/Areas/Identity/Pages/Account/Logout.cshtml.cs | 1,154 | C# |
namespace XmlViewer.Editor.Messages
{
internal class ToEditorScreenMessage
{
public static ToEditorScreenMessage Instance => new ToEditorScreenMessage();
}
}
| 22.375 | 84 | 0.731844 | [
"Apache-2.0"
] | CVOSoftware/XmlViewer | source/XmlViewer.Editor/Messages/ToEditorScreenMessage.cs | 181 | 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 directconnect-2012-10-25.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Net;
using Amazon.DirectConnect.Model;
using Amazon.DirectConnect.Model.Internal.MarshallTransformations;
using Amazon.DirectConnect.Internal;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.DirectConnect
{
/// <summary>
/// Implementation for accessing DirectConnect
///
/// AWS Direct Connect links your internal network to an AWS Direct Connect location over
/// a standard Ethernet fiber-optic cable. One end of the cable is connected to your router,
/// the other to an AWS Direct Connect router. With this connection in place, you can
/// create virtual interfaces directly to the AWS cloud (for example, to Amazon EC2 and
/// Amazon S3) and to Amazon VPC, bypassing Internet service providers in your network
/// path. A connection provides access to all AWS Regions except the China (Beijing) and
/// (China) Ningxia Regions. AWS resources in the China Regions can only be accessed through
/// locations associated with those Regions.
/// </summary>
public partial class AmazonDirectConnectClient : AmazonServiceClient, IAmazonDirectConnect
{
private static IServiceMetadata serviceMetadata = new AmazonDirectConnectMetadata();
#region Constructors
#if NETSTANDARD
/// <summary>
/// Constructs AmazonDirectConnectClient 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>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonDirectConnectClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonDirectConnectConfig()) { }
/// <summary>
/// Constructs AmazonDirectConnectClient 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>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonDirectConnectClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonDirectConnectConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonDirectConnectClient 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>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonDirectConnectClient Configuration Object</param>
public AmazonDirectConnectClient(AmazonDirectConnectConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
#endif
/// <summary>
/// Constructs AmazonDirectConnectClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonDirectConnectClient(AWSCredentials credentials)
: this(credentials, new AmazonDirectConnectConfig())
{
}
/// <summary>
/// Constructs AmazonDirectConnectClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonDirectConnectClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonDirectConnectConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonDirectConnectClient with AWS Credentials and an
/// AmazonDirectConnectClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonDirectConnectClient Configuration Object</param>
public AmazonDirectConnectClient(AWSCredentials credentials, AmazonDirectConnectConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonDirectConnectClient 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 AmazonDirectConnectClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonDirectConnectConfig())
{
}
/// <summary>
/// Constructs AmazonDirectConnectClient 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 AmazonDirectConnectClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonDirectConnectConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonDirectConnectClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonDirectConnectClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonDirectConnectClient Configuration Object</param>
public AmazonDirectConnectClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonDirectConnectConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonDirectConnectClient 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 AmazonDirectConnectClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonDirectConnectConfig())
{
}
/// <summary>
/// Constructs AmazonDirectConnectClient 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 AmazonDirectConnectClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonDirectConnectConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonDirectConnectClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonDirectConnectClient 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 AmazonDirectConnectClient Configuration Object</param>
public AmazonDirectConnectClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonDirectConnectConfig 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 AcceptDirectConnectGatewayAssociationProposal
internal virtual AcceptDirectConnectGatewayAssociationProposalResponse AcceptDirectConnectGatewayAssociationProposal(AcceptDirectConnectGatewayAssociationProposalRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = AcceptDirectConnectGatewayAssociationProposalRequestMarshaller.Instance;
options.ResponseUnmarshaller = AcceptDirectConnectGatewayAssociationProposalResponseUnmarshaller.Instance;
return Invoke<AcceptDirectConnectGatewayAssociationProposalResponse>(request, options);
}
/// <summary>
/// Accepts a proposal request to attach a virtual private gateway or transit gateway
/// to a Direct Connect gateway.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AcceptDirectConnectGatewayAssociationProposal service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the AcceptDirectConnectGatewayAssociationProposal service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/AcceptDirectConnectGatewayAssociationProposal">REST API Reference for AcceptDirectConnectGatewayAssociationProposal Operation</seealso>
public virtual Task<AcceptDirectConnectGatewayAssociationProposalResponse> AcceptDirectConnectGatewayAssociationProposalAsync(AcceptDirectConnectGatewayAssociationProposalRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = AcceptDirectConnectGatewayAssociationProposalRequestMarshaller.Instance;
options.ResponseUnmarshaller = AcceptDirectConnectGatewayAssociationProposalResponseUnmarshaller.Instance;
return InvokeAsync<AcceptDirectConnectGatewayAssociationProposalResponse>(request, options, cancellationToken);
}
#endregion
#region AllocateConnectionOnInterconnect
[Obsolete("Deprecated in favor of AllocateHostedConnection.")]
internal virtual AllocateConnectionOnInterconnectResponse AllocateConnectionOnInterconnect(AllocateConnectionOnInterconnectRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = AllocateConnectionOnInterconnectRequestMarshaller.Instance;
options.ResponseUnmarshaller = AllocateConnectionOnInterconnectResponseUnmarshaller.Instance;
return Invoke<AllocateConnectionOnInterconnectResponse>(request, options);
}
/// <summary>
/// Deprecated. Use <a>AllocateHostedConnection</a> instead.
///
///
/// <para>
/// Creates a hosted connection on an interconnect.
/// </para>
///
/// <para>
/// Allocates a VLAN number and a specified amount of bandwidth for use by a hosted connection
/// on the specified interconnect.
/// </para>
/// <note>
/// <para>
/// Intended for use by AWS Direct Connect Partners only.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AllocateConnectionOnInterconnect service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the AllocateConnectionOnInterconnect service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/AllocateConnectionOnInterconnect">REST API Reference for AllocateConnectionOnInterconnect Operation</seealso>
[Obsolete("Deprecated in favor of AllocateHostedConnection.")]
public virtual Task<AllocateConnectionOnInterconnectResponse> AllocateConnectionOnInterconnectAsync(AllocateConnectionOnInterconnectRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = AllocateConnectionOnInterconnectRequestMarshaller.Instance;
options.ResponseUnmarshaller = AllocateConnectionOnInterconnectResponseUnmarshaller.Instance;
return InvokeAsync<AllocateConnectionOnInterconnectResponse>(request, options, cancellationToken);
}
#endregion
#region AllocateHostedConnection
internal virtual AllocateHostedConnectionResponse AllocateHostedConnection(AllocateHostedConnectionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = AllocateHostedConnectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = AllocateHostedConnectionResponseUnmarshaller.Instance;
return Invoke<AllocateHostedConnectionResponse>(request, options);
}
/// <summary>
/// Creates a hosted connection on the specified interconnect or a link aggregation group
/// (LAG) of interconnects.
///
///
/// <para>
/// Allocates a VLAN number and a specified amount of capacity (bandwidth) for use by
/// a hosted connection on the specified interconnect or LAG of interconnects. AWS polices
/// the hosted connection for the specified capacity and the AWS Direct Connect Partner
/// must also police the hosted connection for the specified capacity.
/// </para>
/// <note>
/// <para>
/// Intended for use by AWS Direct Connect Partners only.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AllocateHostedConnection service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the AllocateHostedConnection service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/AllocateHostedConnection">REST API Reference for AllocateHostedConnection Operation</seealso>
public virtual Task<AllocateHostedConnectionResponse> AllocateHostedConnectionAsync(AllocateHostedConnectionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = AllocateHostedConnectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = AllocateHostedConnectionResponseUnmarshaller.Instance;
return InvokeAsync<AllocateHostedConnectionResponse>(request, options, cancellationToken);
}
#endregion
#region AllocatePrivateVirtualInterface
internal virtual AllocatePrivateVirtualInterfaceResponse AllocatePrivateVirtualInterface(AllocatePrivateVirtualInterfaceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = AllocatePrivateVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = AllocatePrivateVirtualInterfaceResponseUnmarshaller.Instance;
return Invoke<AllocatePrivateVirtualInterfaceResponse>(request, options);
}
/// <summary>
/// Provisions a private virtual interface to be owned by the specified AWS account.
///
///
/// <para>
/// Virtual interfaces created using this action must be confirmed by the owner using
/// <a>ConfirmPrivateVirtualInterface</a>. Until then, the virtual interface is in the
/// <code>Confirming</code> state and is not available to handle traffic.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AllocatePrivateVirtualInterface service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the AllocatePrivateVirtualInterface service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/AllocatePrivateVirtualInterface">REST API Reference for AllocatePrivateVirtualInterface Operation</seealso>
public virtual Task<AllocatePrivateVirtualInterfaceResponse> AllocatePrivateVirtualInterfaceAsync(AllocatePrivateVirtualInterfaceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = AllocatePrivateVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = AllocatePrivateVirtualInterfaceResponseUnmarshaller.Instance;
return InvokeAsync<AllocatePrivateVirtualInterfaceResponse>(request, options, cancellationToken);
}
#endregion
#region AllocatePublicVirtualInterface
internal virtual AllocatePublicVirtualInterfaceResponse AllocatePublicVirtualInterface(AllocatePublicVirtualInterfaceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = AllocatePublicVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = AllocatePublicVirtualInterfaceResponseUnmarshaller.Instance;
return Invoke<AllocatePublicVirtualInterfaceResponse>(request, options);
}
/// <summary>
/// Provisions a public virtual interface to be owned by the specified AWS account.
///
///
/// <para>
/// The owner of a connection calls this function to provision a public virtual interface
/// to be owned by the specified AWS account.
/// </para>
///
/// <para>
/// Virtual interfaces created using this function must be confirmed by the owner using
/// <a>ConfirmPublicVirtualInterface</a>. Until this step has been completed, the virtual
/// interface is in the <code>confirming</code> state and is not available to handle traffic.
/// </para>
///
/// <para>
/// When creating an IPv6 public virtual interface, omit the Amazon address and customer
/// address. IPv6 addresses are automatically assigned from the Amazon pool of IPv6 addresses;
/// you cannot specify custom IPv6 addresses.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AllocatePublicVirtualInterface service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the AllocatePublicVirtualInterface service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/AllocatePublicVirtualInterface">REST API Reference for AllocatePublicVirtualInterface Operation</seealso>
public virtual Task<AllocatePublicVirtualInterfaceResponse> AllocatePublicVirtualInterfaceAsync(AllocatePublicVirtualInterfaceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = AllocatePublicVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = AllocatePublicVirtualInterfaceResponseUnmarshaller.Instance;
return InvokeAsync<AllocatePublicVirtualInterfaceResponse>(request, options, cancellationToken);
}
#endregion
#region AllocateTransitVirtualInterface
internal virtual AllocateTransitVirtualInterfaceResponse AllocateTransitVirtualInterface(AllocateTransitVirtualInterfaceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = AllocateTransitVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = AllocateTransitVirtualInterfaceResponseUnmarshaller.Instance;
return Invoke<AllocateTransitVirtualInterfaceResponse>(request, options);
}
/// <summary>
/// Provisions a transit virtual interface to be owned by the specified AWS account. Use
/// this type of interface to connect a transit gateway to your Direct Connect gateway.
///
///
/// <para>
/// The owner of a connection provisions a transit virtual interface to be owned by the
/// specified AWS account.
/// </para>
///
/// <para>
/// After you create a transit virtual interface, it must be confirmed by the owner using
/// <a>ConfirmTransitVirtualInterface</a>. Until this step has been completed, the transit
/// virtual interface is in the <code>requested</code> state and is not available to handle
/// traffic.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AllocateTransitVirtualInterface service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the AllocateTransitVirtualInterface service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/AllocateTransitVirtualInterface">REST API Reference for AllocateTransitVirtualInterface Operation</seealso>
public virtual Task<AllocateTransitVirtualInterfaceResponse> AllocateTransitVirtualInterfaceAsync(AllocateTransitVirtualInterfaceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = AllocateTransitVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = AllocateTransitVirtualInterfaceResponseUnmarshaller.Instance;
return InvokeAsync<AllocateTransitVirtualInterfaceResponse>(request, options, cancellationToken);
}
#endregion
#region AssociateConnectionWithLag
internal virtual AssociateConnectionWithLagResponse AssociateConnectionWithLag(AssociateConnectionWithLagRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = AssociateConnectionWithLagRequestMarshaller.Instance;
options.ResponseUnmarshaller = AssociateConnectionWithLagResponseUnmarshaller.Instance;
return Invoke<AssociateConnectionWithLagResponse>(request, options);
}
/// <summary>
/// Associates an existing connection with a link aggregation group (LAG). The connection
/// is interrupted and re-established as a member of the LAG (connectivity to AWS is interrupted).
/// The connection must be hosted on the same AWS Direct Connect endpoint as the LAG,
/// and its bandwidth must match the bandwidth for the LAG. You can re-associate a connection
/// that's currently associated with a different LAG; however, if removing the connection
/// would cause the original LAG to fall below its setting for minimum number of operational
/// connections, the request fails.
///
///
/// <para>
/// Any virtual interfaces that are directly associated with the connection are automatically
/// re-associated with the LAG. If the connection was originally associated with a different
/// LAG, the virtual interfaces remain associated with the original LAG.
/// </para>
///
/// <para>
/// For interconnects, any hosted connections are automatically re-associated with the
/// LAG. If the interconnect was originally associated with a different LAG, the hosted
/// connections remain associated with the original LAG.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AssociateConnectionWithLag service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the AssociateConnectionWithLag service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/AssociateConnectionWithLag">REST API Reference for AssociateConnectionWithLag Operation</seealso>
public virtual Task<AssociateConnectionWithLagResponse> AssociateConnectionWithLagAsync(AssociateConnectionWithLagRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = AssociateConnectionWithLagRequestMarshaller.Instance;
options.ResponseUnmarshaller = AssociateConnectionWithLagResponseUnmarshaller.Instance;
return InvokeAsync<AssociateConnectionWithLagResponse>(request, options, cancellationToken);
}
#endregion
#region AssociateHostedConnection
internal virtual AssociateHostedConnectionResponse AssociateHostedConnection(AssociateHostedConnectionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = AssociateHostedConnectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = AssociateHostedConnectionResponseUnmarshaller.Instance;
return Invoke<AssociateHostedConnectionResponse>(request, options);
}
/// <summary>
/// Associates a hosted connection and its virtual interfaces with a link aggregation
/// group (LAG) or interconnect. If the target interconnect or LAG has an existing hosted
/// connection with a conflicting VLAN number or IP address, the operation fails. This
/// action temporarily interrupts the hosted connection's connectivity to AWS as it is
/// being migrated.
///
/// <note>
/// <para>
/// Intended for use by AWS Direct Connect Partners only.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AssociateHostedConnection service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the AssociateHostedConnection service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/AssociateHostedConnection">REST API Reference for AssociateHostedConnection Operation</seealso>
public virtual Task<AssociateHostedConnectionResponse> AssociateHostedConnectionAsync(AssociateHostedConnectionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = AssociateHostedConnectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = AssociateHostedConnectionResponseUnmarshaller.Instance;
return InvokeAsync<AssociateHostedConnectionResponse>(request, options, cancellationToken);
}
#endregion
#region AssociateVirtualInterface
internal virtual AssociateVirtualInterfaceResponse AssociateVirtualInterface(AssociateVirtualInterfaceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = AssociateVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = AssociateVirtualInterfaceResponseUnmarshaller.Instance;
return Invoke<AssociateVirtualInterfaceResponse>(request, options);
}
/// <summary>
/// Associates a virtual interface with a specified link aggregation group (LAG) or connection.
/// Connectivity to AWS is temporarily interrupted as the virtual interface is being migrated.
/// If the target connection or LAG has an associated virtual interface with a conflicting
/// VLAN number or a conflicting IP address, the operation fails.
///
///
/// <para>
/// Virtual interfaces associated with a hosted connection cannot be associated with a
/// LAG; hosted connections must be migrated along with their virtual interfaces using
/// <a>AssociateHostedConnection</a>.
/// </para>
///
/// <para>
/// To reassociate a virtual interface to a new connection or LAG, the requester must
/// own either the virtual interface itself or the connection to which the virtual interface
/// is currently associated. Additionally, the requester must own the connection or LAG
/// for the association.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AssociateVirtualInterface service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the AssociateVirtualInterface service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/AssociateVirtualInterface">REST API Reference for AssociateVirtualInterface Operation</seealso>
public virtual Task<AssociateVirtualInterfaceResponse> AssociateVirtualInterfaceAsync(AssociateVirtualInterfaceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = AssociateVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = AssociateVirtualInterfaceResponseUnmarshaller.Instance;
return InvokeAsync<AssociateVirtualInterfaceResponse>(request, options, cancellationToken);
}
#endregion
#region ConfirmConnection
internal virtual ConfirmConnectionResponse ConfirmConnection(ConfirmConnectionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ConfirmConnectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = ConfirmConnectionResponseUnmarshaller.Instance;
return Invoke<ConfirmConnectionResponse>(request, options);
}
/// <summary>
/// Confirms the creation of the specified hosted connection on an interconnect.
///
///
/// <para>
/// Upon creation, the hosted connection is initially in the <code>Ordering</code> state,
/// and remains in this state until the owner confirms creation of the hosted connection.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ConfirmConnection service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ConfirmConnection service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/ConfirmConnection">REST API Reference for ConfirmConnection Operation</seealso>
public virtual Task<ConfirmConnectionResponse> ConfirmConnectionAsync(ConfirmConnectionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ConfirmConnectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = ConfirmConnectionResponseUnmarshaller.Instance;
return InvokeAsync<ConfirmConnectionResponse>(request, options, cancellationToken);
}
#endregion
#region ConfirmPrivateVirtualInterface
internal virtual ConfirmPrivateVirtualInterfaceResponse ConfirmPrivateVirtualInterface(ConfirmPrivateVirtualInterfaceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ConfirmPrivateVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ConfirmPrivateVirtualInterfaceResponseUnmarshaller.Instance;
return Invoke<ConfirmPrivateVirtualInterfaceResponse>(request, options);
}
/// <summary>
/// Accepts ownership of a private virtual interface created by another AWS account.
///
///
/// <para>
/// After the virtual interface owner makes this call, the virtual interface is created
/// and attached to the specified virtual private gateway or Direct Connect gateway, and
/// is made available to handle traffic.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ConfirmPrivateVirtualInterface service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ConfirmPrivateVirtualInterface service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/ConfirmPrivateVirtualInterface">REST API Reference for ConfirmPrivateVirtualInterface Operation</seealso>
public virtual Task<ConfirmPrivateVirtualInterfaceResponse> ConfirmPrivateVirtualInterfaceAsync(ConfirmPrivateVirtualInterfaceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ConfirmPrivateVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ConfirmPrivateVirtualInterfaceResponseUnmarshaller.Instance;
return InvokeAsync<ConfirmPrivateVirtualInterfaceResponse>(request, options, cancellationToken);
}
#endregion
#region ConfirmPublicVirtualInterface
internal virtual ConfirmPublicVirtualInterfaceResponse ConfirmPublicVirtualInterface(ConfirmPublicVirtualInterfaceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ConfirmPublicVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ConfirmPublicVirtualInterfaceResponseUnmarshaller.Instance;
return Invoke<ConfirmPublicVirtualInterfaceResponse>(request, options);
}
/// <summary>
/// Accepts ownership of a public virtual interface created by another AWS account.
///
///
/// <para>
/// After the virtual interface owner makes this call, the specified virtual interface
/// is created and made available to handle traffic.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ConfirmPublicVirtualInterface service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ConfirmPublicVirtualInterface service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/ConfirmPublicVirtualInterface">REST API Reference for ConfirmPublicVirtualInterface Operation</seealso>
public virtual Task<ConfirmPublicVirtualInterfaceResponse> ConfirmPublicVirtualInterfaceAsync(ConfirmPublicVirtualInterfaceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ConfirmPublicVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ConfirmPublicVirtualInterfaceResponseUnmarshaller.Instance;
return InvokeAsync<ConfirmPublicVirtualInterfaceResponse>(request, options, cancellationToken);
}
#endregion
#region ConfirmTransitVirtualInterface
internal virtual ConfirmTransitVirtualInterfaceResponse ConfirmTransitVirtualInterface(ConfirmTransitVirtualInterfaceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ConfirmTransitVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ConfirmTransitVirtualInterfaceResponseUnmarshaller.Instance;
return Invoke<ConfirmTransitVirtualInterfaceResponse>(request, options);
}
/// <summary>
/// Accepts ownership of a transit virtual interface created by another AWS account.
///
///
/// <para>
/// After the owner of the transit virtual interface makes this call, the specified transit
/// virtual interface is created and made available to handle traffic.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ConfirmTransitVirtualInterface service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ConfirmTransitVirtualInterface service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/ConfirmTransitVirtualInterface">REST API Reference for ConfirmTransitVirtualInterface Operation</seealso>
public virtual Task<ConfirmTransitVirtualInterfaceResponse> ConfirmTransitVirtualInterfaceAsync(ConfirmTransitVirtualInterfaceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ConfirmTransitVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ConfirmTransitVirtualInterfaceResponseUnmarshaller.Instance;
return InvokeAsync<ConfirmTransitVirtualInterfaceResponse>(request, options, cancellationToken);
}
#endregion
#region CreateBGPPeer
internal virtual CreateBGPPeerResponse CreateBGPPeer(CreateBGPPeerRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateBGPPeerRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateBGPPeerResponseUnmarshaller.Instance;
return Invoke<CreateBGPPeerResponse>(request, options);
}
/// <summary>
/// Creates a BGP peer on the specified virtual interface.
///
///
/// <para>
/// You must create a BGP peer for the corresponding address family (IPv4/IPv6) in order
/// to access AWS resources that also use that address family.
/// </para>
///
/// <para>
/// If logical redundancy is not supported by the connection, interconnect, or LAG, the
/// BGP peer cannot be in the same address family as an existing BGP peer on the virtual
/// interface.
/// </para>
///
/// <para>
/// When creating a IPv6 BGP peer, omit the Amazon address and customer address. IPv6
/// addresses are automatically assigned from the Amazon pool of IPv6 addresses; you cannot
/// specify custom IPv6 addresses.
/// </para>
///
/// <para>
/// For a public virtual interface, the Autonomous System Number (ASN) must be private
/// or already whitelisted for the virtual interface.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateBGPPeer service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateBGPPeer service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/CreateBGPPeer">REST API Reference for CreateBGPPeer Operation</seealso>
public virtual Task<CreateBGPPeerResponse> CreateBGPPeerAsync(CreateBGPPeerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateBGPPeerRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateBGPPeerResponseUnmarshaller.Instance;
return InvokeAsync<CreateBGPPeerResponse>(request, options, cancellationToken);
}
#endregion
#region CreateConnection
internal virtual CreateConnectionResponse CreateConnection(CreateConnectionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateConnectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateConnectionResponseUnmarshaller.Instance;
return Invoke<CreateConnectionResponse>(request, options);
}
/// <summary>
/// Creates a connection between a customer network and a specific AWS Direct Connect
/// location.
///
///
/// <para>
/// A connection links your internal network to an AWS Direct Connect location over a
/// standard Ethernet fiber-optic cable. One end of the cable is connected to your router,
/// the other to an AWS Direct Connect router.
/// </para>
///
/// <para>
/// To find the locations for your Region, use <a>DescribeLocations</a>.
/// </para>
///
/// <para>
/// You can automatically add the new connection to a link aggregation group (LAG) by
/// specifying a LAG ID in the request. This ensures that the new connection is allocated
/// on the same AWS Direct Connect endpoint that hosts the specified LAG. If there are
/// no available ports on the endpoint, the request fails and no connection is created.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateConnection service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateConnection service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/CreateConnection">REST API Reference for CreateConnection Operation</seealso>
public virtual Task<CreateConnectionResponse> CreateConnectionAsync(CreateConnectionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateConnectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateConnectionResponseUnmarshaller.Instance;
return InvokeAsync<CreateConnectionResponse>(request, options, cancellationToken);
}
#endregion
#region CreateDirectConnectGateway
internal virtual CreateDirectConnectGatewayResponse CreateDirectConnectGateway(CreateDirectConnectGatewayRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateDirectConnectGatewayRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateDirectConnectGatewayResponseUnmarshaller.Instance;
return Invoke<CreateDirectConnectGatewayResponse>(request, options);
}
/// <summary>
/// Creates a Direct Connect gateway, which is an intermediate object that enables you
/// to connect a set of virtual interfaces and virtual private gateways. A Direct Connect
/// gateway is global and visible in any AWS Region after it is created. The virtual interfaces
/// and virtual private gateways that are connected through a Direct Connect gateway can
/// be in different AWS Regions. This enables you to connect to a VPC in any Region, regardless
/// of the Region in which the virtual interfaces are located, and pass traffic between
/// them.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateDirectConnectGateway service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateDirectConnectGateway service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/CreateDirectConnectGateway">REST API Reference for CreateDirectConnectGateway Operation</seealso>
public virtual Task<CreateDirectConnectGatewayResponse> CreateDirectConnectGatewayAsync(CreateDirectConnectGatewayRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateDirectConnectGatewayRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateDirectConnectGatewayResponseUnmarshaller.Instance;
return InvokeAsync<CreateDirectConnectGatewayResponse>(request, options, cancellationToken);
}
#endregion
#region CreateDirectConnectGatewayAssociation
internal virtual CreateDirectConnectGatewayAssociationResponse CreateDirectConnectGatewayAssociation(CreateDirectConnectGatewayAssociationRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateDirectConnectGatewayAssociationRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateDirectConnectGatewayAssociationResponseUnmarshaller.Instance;
return Invoke<CreateDirectConnectGatewayAssociationResponse>(request, options);
}
/// <summary>
/// Creates an association between a Direct Connect gateway and a virtual private gateway.
/// The virtual private gateway must be attached to a VPC and must not be associated with
/// another Direct Connect gateway.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateDirectConnectGatewayAssociation service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateDirectConnectGatewayAssociation service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/CreateDirectConnectGatewayAssociation">REST API Reference for CreateDirectConnectGatewayAssociation Operation</seealso>
public virtual Task<CreateDirectConnectGatewayAssociationResponse> CreateDirectConnectGatewayAssociationAsync(CreateDirectConnectGatewayAssociationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateDirectConnectGatewayAssociationRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateDirectConnectGatewayAssociationResponseUnmarshaller.Instance;
return InvokeAsync<CreateDirectConnectGatewayAssociationResponse>(request, options, cancellationToken);
}
#endregion
#region CreateDirectConnectGatewayAssociationProposal
internal virtual CreateDirectConnectGatewayAssociationProposalResponse CreateDirectConnectGatewayAssociationProposal(CreateDirectConnectGatewayAssociationProposalRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateDirectConnectGatewayAssociationProposalRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateDirectConnectGatewayAssociationProposalResponseUnmarshaller.Instance;
return Invoke<CreateDirectConnectGatewayAssociationProposalResponse>(request, options);
}
/// <summary>
/// Creates a proposal to associate the specified virtual private gateway or transit gateway
/// with the specified Direct Connect gateway.
///
///
/// <para>
/// You can only associate a Direct Connect gateway and virtual private gateway or transit
/// gateway when the account that owns the Direct Connect gateway and the account that
/// owns the virtual private gateway or transit gateway have the same AWS Payer ID.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateDirectConnectGatewayAssociationProposal service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateDirectConnectGatewayAssociationProposal service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/CreateDirectConnectGatewayAssociationProposal">REST API Reference for CreateDirectConnectGatewayAssociationProposal Operation</seealso>
public virtual Task<CreateDirectConnectGatewayAssociationProposalResponse> CreateDirectConnectGatewayAssociationProposalAsync(CreateDirectConnectGatewayAssociationProposalRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateDirectConnectGatewayAssociationProposalRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateDirectConnectGatewayAssociationProposalResponseUnmarshaller.Instance;
return InvokeAsync<CreateDirectConnectGatewayAssociationProposalResponse>(request, options, cancellationToken);
}
#endregion
#region CreateInterconnect
internal virtual CreateInterconnectResponse CreateInterconnect(CreateInterconnectRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateInterconnectRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateInterconnectResponseUnmarshaller.Instance;
return Invoke<CreateInterconnectResponse>(request, options);
}
/// <summary>
/// Creates an interconnect between an AWS Direct Connect Partner's network and a specific
/// AWS Direct Connect location.
///
///
/// <para>
/// An interconnect is a connection that is capable of hosting other connections. The
/// AWS Direct Connect partner can use an interconnect to provide AWS Direct Connect hosted
/// connections to customers through their own network services. Like a standard connection,
/// an interconnect links the partner's network to an AWS Direct Connect location over
/// a standard Ethernet fiber-optic cable. One end is connected to the partner's router,
/// the other to an AWS Direct Connect router.
/// </para>
///
/// <para>
/// You can automatically add the new interconnect to a link aggregation group (LAG) by
/// specifying a LAG ID in the request. This ensures that the new interconnect is allocated
/// on the same AWS Direct Connect endpoint that hosts the specified LAG. If there are
/// no available ports on the endpoint, the request fails and no interconnect is created.
/// </para>
///
/// <para>
/// For each end customer, the AWS Direct Connect Partner provisions a connection on their
/// interconnect by calling <a>AllocateHostedConnection</a>. The end customer can then
/// connect to AWS resources by creating a virtual interface on their connection, using
/// the VLAN assigned to them by the AWS Direct Connect Partner.
/// </para>
/// <note>
/// <para>
/// Intended for use by AWS Direct Connect Partners only.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateInterconnect service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateInterconnect service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/CreateInterconnect">REST API Reference for CreateInterconnect Operation</seealso>
public virtual Task<CreateInterconnectResponse> CreateInterconnectAsync(CreateInterconnectRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateInterconnectRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateInterconnectResponseUnmarshaller.Instance;
return InvokeAsync<CreateInterconnectResponse>(request, options, cancellationToken);
}
#endregion
#region CreateLag
internal virtual CreateLagResponse CreateLag(CreateLagRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateLagRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateLagResponseUnmarshaller.Instance;
return Invoke<CreateLagResponse>(request, options);
}
/// <summary>
/// Creates a link aggregation group (LAG) with the specified number of bundled physical
/// connections between the customer network and a specific AWS Direct Connect location.
/// A LAG is a logical interface that uses the Link Aggregation Control Protocol (LACP)
/// to aggregate multiple interfaces, enabling you to treat them as a single interface.
///
///
/// <para>
/// All connections in a LAG must use the same bandwidth and must terminate at the same
/// AWS Direct Connect endpoint.
/// </para>
///
/// <para>
/// You can have up to 10 connections per LAG. Regardless of this limit, if you request
/// more connections for the LAG than AWS Direct Connect can allocate on a single endpoint,
/// no LAG is created.
/// </para>
///
/// <para>
/// You can specify an existing physical connection or interconnect to include in the
/// LAG (which counts towards the total number of connections). Doing so interrupts the
/// current physical connection or hosted connections, and re-establishes them as a member
/// of the LAG. The LAG will be created on the same AWS Direct Connect endpoint to which
/// the connection terminates. Any virtual interfaces associated with the connection are
/// automatically disassociated and re-associated with the LAG. The connection ID does
/// not change.
/// </para>
///
/// <para>
/// If the AWS account used to create a LAG is a registered AWS Direct Connect Partner,
/// the LAG is automatically enabled to host sub-connections. For a LAG owned by a partner,
/// any associated virtual interfaces cannot be directly configured.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateLag service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateLag service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/CreateLag">REST API Reference for CreateLag Operation</seealso>
public virtual Task<CreateLagResponse> CreateLagAsync(CreateLagRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateLagRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateLagResponseUnmarshaller.Instance;
return InvokeAsync<CreateLagResponse>(request, options, cancellationToken);
}
#endregion
#region CreatePrivateVirtualInterface
internal virtual CreatePrivateVirtualInterfaceResponse CreatePrivateVirtualInterface(CreatePrivateVirtualInterfaceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreatePrivateVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreatePrivateVirtualInterfaceResponseUnmarshaller.Instance;
return Invoke<CreatePrivateVirtualInterfaceResponse>(request, options);
}
/// <summary>
/// Creates a private virtual interface. A virtual interface is the VLAN that transports
/// AWS Direct Connect traffic. A private virtual interface can be connected to either
/// a Direct Connect gateway or a Virtual Private Gateway (VGW). Connecting the private
/// virtual interface to a Direct Connect gateway enables the possibility for connecting
/// to multiple VPCs, including VPCs in different AWS Regions. Connecting the private
/// virtual interface to a VGW only provides access to a single VPC within the same Region.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreatePrivateVirtualInterface service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreatePrivateVirtualInterface service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/CreatePrivateVirtualInterface">REST API Reference for CreatePrivateVirtualInterface Operation</seealso>
public virtual Task<CreatePrivateVirtualInterfaceResponse> CreatePrivateVirtualInterfaceAsync(CreatePrivateVirtualInterfaceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreatePrivateVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreatePrivateVirtualInterfaceResponseUnmarshaller.Instance;
return InvokeAsync<CreatePrivateVirtualInterfaceResponse>(request, options, cancellationToken);
}
#endregion
#region CreatePublicVirtualInterface
internal virtual CreatePublicVirtualInterfaceResponse CreatePublicVirtualInterface(CreatePublicVirtualInterfaceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreatePublicVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreatePublicVirtualInterfaceResponseUnmarshaller.Instance;
return Invoke<CreatePublicVirtualInterfaceResponse>(request, options);
}
/// <summary>
/// Creates a public virtual interface. A virtual interface is the VLAN that transports
/// AWS Direct Connect traffic. A public virtual interface supports sending traffic to
/// public services of AWS such as Amazon S3.
///
///
/// <para>
/// When creating an IPv6 public virtual interface (<code>addressFamily</code> is <code>ipv6</code>),
/// leave the <code>customer</code> and <code>amazon</code> address fields blank to use
/// auto-assigned IPv6 space. Custom IPv6 addresses are not supported.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreatePublicVirtualInterface service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreatePublicVirtualInterface service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/CreatePublicVirtualInterface">REST API Reference for CreatePublicVirtualInterface Operation</seealso>
public virtual Task<CreatePublicVirtualInterfaceResponse> CreatePublicVirtualInterfaceAsync(CreatePublicVirtualInterfaceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreatePublicVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreatePublicVirtualInterfaceResponseUnmarshaller.Instance;
return InvokeAsync<CreatePublicVirtualInterfaceResponse>(request, options, cancellationToken);
}
#endregion
#region CreateTransitVirtualInterface
internal virtual CreateTransitVirtualInterfaceResponse CreateTransitVirtualInterface(CreateTransitVirtualInterfaceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateTransitVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateTransitVirtualInterfaceResponseUnmarshaller.Instance;
return Invoke<CreateTransitVirtualInterfaceResponse>(request, options);
}
/// <summary>
/// Creates a transit virtual interface. A transit virtual interface is a VLAN that transports
/// traffic from a Direct Connect gateway to one or more transit gateways. A transit virtual
/// interface enables the connection of multiple VPCs attached to a transit gateway to
/// a Direct Connect gateway.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateTransitVirtualInterface service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateTransitVirtualInterface service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/CreateTransitVirtualInterface">REST API Reference for CreateTransitVirtualInterface Operation</seealso>
public virtual Task<CreateTransitVirtualInterfaceResponse> CreateTransitVirtualInterfaceAsync(CreateTransitVirtualInterfaceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateTransitVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateTransitVirtualInterfaceResponseUnmarshaller.Instance;
return InvokeAsync<CreateTransitVirtualInterfaceResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteBGPPeer
internal virtual DeleteBGPPeerResponse DeleteBGPPeer(DeleteBGPPeerRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteBGPPeerRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteBGPPeerResponseUnmarshaller.Instance;
return Invoke<DeleteBGPPeerResponse>(request, options);
}
/// <summary>
/// Deletes the specified BGP peer on the specified virtual interface with the specified
/// customer address and ASN.
///
///
/// <para>
/// You cannot delete the last BGP peer from a virtual interface.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteBGPPeer service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteBGPPeer service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DeleteBGPPeer">REST API Reference for DeleteBGPPeer Operation</seealso>
public virtual Task<DeleteBGPPeerResponse> DeleteBGPPeerAsync(DeleteBGPPeerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteBGPPeerRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteBGPPeerResponseUnmarshaller.Instance;
return InvokeAsync<DeleteBGPPeerResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteConnection
internal virtual DeleteConnectionResponse DeleteConnection(DeleteConnectionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteConnectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteConnectionResponseUnmarshaller.Instance;
return Invoke<DeleteConnectionResponse>(request, options);
}
/// <summary>
/// Deletes the specified connection.
///
///
/// <para>
/// Deleting a connection only stops the AWS Direct Connect port hour and data transfer
/// charges. If you are partnering with any third parties to connect with the AWS Direct
/// Connect location, you must cancel your service with them separately.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteConnection service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteConnection service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DeleteConnection">REST API Reference for DeleteConnection Operation</seealso>
public virtual Task<DeleteConnectionResponse> DeleteConnectionAsync(DeleteConnectionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteConnectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteConnectionResponseUnmarshaller.Instance;
return InvokeAsync<DeleteConnectionResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteDirectConnectGateway
internal virtual DeleteDirectConnectGatewayResponse DeleteDirectConnectGateway(DeleteDirectConnectGatewayRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteDirectConnectGatewayRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteDirectConnectGatewayResponseUnmarshaller.Instance;
return Invoke<DeleteDirectConnectGatewayResponse>(request, options);
}
/// <summary>
/// Deletes the specified Direct Connect gateway. You must first delete all virtual interfaces
/// that are attached to the Direct Connect gateway and disassociate all virtual private
/// gateways that are associated with the Direct Connect gateway.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteDirectConnectGateway service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteDirectConnectGateway service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DeleteDirectConnectGateway">REST API Reference for DeleteDirectConnectGateway Operation</seealso>
public virtual Task<DeleteDirectConnectGatewayResponse> DeleteDirectConnectGatewayAsync(DeleteDirectConnectGatewayRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteDirectConnectGatewayRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteDirectConnectGatewayResponseUnmarshaller.Instance;
return InvokeAsync<DeleteDirectConnectGatewayResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteDirectConnectGatewayAssociation
internal virtual DeleteDirectConnectGatewayAssociationResponse DeleteDirectConnectGatewayAssociation(DeleteDirectConnectGatewayAssociationRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteDirectConnectGatewayAssociationRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteDirectConnectGatewayAssociationResponseUnmarshaller.Instance;
return Invoke<DeleteDirectConnectGatewayAssociationResponse>(request, options);
}
/// <summary>
/// Deletes the association between the specified Direct Connect gateway and virtual private
/// gateway.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteDirectConnectGatewayAssociation service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteDirectConnectGatewayAssociation service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DeleteDirectConnectGatewayAssociation">REST API Reference for DeleteDirectConnectGatewayAssociation Operation</seealso>
public virtual Task<DeleteDirectConnectGatewayAssociationResponse> DeleteDirectConnectGatewayAssociationAsync(DeleteDirectConnectGatewayAssociationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteDirectConnectGatewayAssociationRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteDirectConnectGatewayAssociationResponseUnmarshaller.Instance;
return InvokeAsync<DeleteDirectConnectGatewayAssociationResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteDirectConnectGatewayAssociationProposal
internal virtual DeleteDirectConnectGatewayAssociationProposalResponse DeleteDirectConnectGatewayAssociationProposal(DeleteDirectConnectGatewayAssociationProposalRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteDirectConnectGatewayAssociationProposalRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteDirectConnectGatewayAssociationProposalResponseUnmarshaller.Instance;
return Invoke<DeleteDirectConnectGatewayAssociationProposalResponse>(request, options);
}
/// <summary>
/// Deletes the association proposal request between the specified Direct Connect gateway
/// and virtual private gateway or transit gateway.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteDirectConnectGatewayAssociationProposal service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteDirectConnectGatewayAssociationProposal service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DeleteDirectConnectGatewayAssociationProposal">REST API Reference for DeleteDirectConnectGatewayAssociationProposal Operation</seealso>
public virtual Task<DeleteDirectConnectGatewayAssociationProposalResponse> DeleteDirectConnectGatewayAssociationProposalAsync(DeleteDirectConnectGatewayAssociationProposalRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteDirectConnectGatewayAssociationProposalRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteDirectConnectGatewayAssociationProposalResponseUnmarshaller.Instance;
return InvokeAsync<DeleteDirectConnectGatewayAssociationProposalResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteInterconnect
internal virtual DeleteInterconnectResponse DeleteInterconnect(DeleteInterconnectRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteInterconnectRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteInterconnectResponseUnmarshaller.Instance;
return Invoke<DeleteInterconnectResponse>(request, options);
}
/// <summary>
/// Deletes the specified interconnect.
///
/// <note>
/// <para>
/// Intended for use by AWS Direct Connect Partners only.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteInterconnect service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteInterconnect service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DeleteInterconnect">REST API Reference for DeleteInterconnect Operation</seealso>
public virtual Task<DeleteInterconnectResponse> DeleteInterconnectAsync(DeleteInterconnectRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteInterconnectRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteInterconnectResponseUnmarshaller.Instance;
return InvokeAsync<DeleteInterconnectResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteLag
internal virtual DeleteLagResponse DeleteLag(DeleteLagRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteLagRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteLagResponseUnmarshaller.Instance;
return Invoke<DeleteLagResponse>(request, options);
}
/// <summary>
/// Deletes the specified link aggregation group (LAG). You cannot delete a LAG if it
/// has active virtual interfaces or hosted connections.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteLag service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteLag service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DeleteLag">REST API Reference for DeleteLag Operation</seealso>
public virtual Task<DeleteLagResponse> DeleteLagAsync(DeleteLagRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteLagRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteLagResponseUnmarshaller.Instance;
return InvokeAsync<DeleteLagResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteVirtualInterface
internal virtual DeleteVirtualInterfaceResponse DeleteVirtualInterface(DeleteVirtualInterfaceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteVirtualInterfaceResponseUnmarshaller.Instance;
return Invoke<DeleteVirtualInterfaceResponse>(request, options);
}
/// <summary>
/// Deletes a virtual interface.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteVirtualInterface service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteVirtualInterface service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DeleteVirtualInterface">REST API Reference for DeleteVirtualInterface Operation</seealso>
public virtual Task<DeleteVirtualInterfaceResponse> DeleteVirtualInterfaceAsync(DeleteVirtualInterfaceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteVirtualInterfaceRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteVirtualInterfaceResponseUnmarshaller.Instance;
return InvokeAsync<DeleteVirtualInterfaceResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeConnectionLoa
[Obsolete("Deprecated in favor of DescribeLoa.")]
internal virtual DescribeConnectionLoaResponse DescribeConnectionLoa(DescribeConnectionLoaRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeConnectionLoaRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeConnectionLoaResponseUnmarshaller.Instance;
return Invoke<DescribeConnectionLoaResponse>(request, options);
}
/// <summary>
/// Deprecated. Use <a>DescribeLoa</a> instead.
///
///
/// <para>
/// Gets the LOA-CFA for a connection.
/// </para>
///
/// <para>
/// The Letter of Authorization - Connecting Facility Assignment (LOA-CFA) is a document
/// that your APN partner or service provider uses when establishing your cross connect
/// to AWS at the colocation facility. For more information, see <a href="https://docs.aws.amazon.com/directconnect/latest/UserGuide/Colocation.html">Requesting
/// Cross Connects at AWS Direct Connect Locations</a> in the <i>AWS Direct Connect User
/// Guide</i>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeConnectionLoa service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeConnectionLoa service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeConnectionLoa">REST API Reference for DescribeConnectionLoa Operation</seealso>
[Obsolete("Deprecated in favor of DescribeLoa.")]
public virtual Task<DescribeConnectionLoaResponse> DescribeConnectionLoaAsync(DescribeConnectionLoaRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeConnectionLoaRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeConnectionLoaResponseUnmarshaller.Instance;
return InvokeAsync<DescribeConnectionLoaResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeConnections
internal virtual DescribeConnectionsResponse DescribeConnections()
{
return DescribeConnections(new DescribeConnectionsRequest());
}
internal virtual DescribeConnectionsResponse DescribeConnections(DescribeConnectionsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeConnectionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeConnectionsResponseUnmarshaller.Instance;
return Invoke<DescribeConnectionsResponse>(request, options);
}
/// <summary>
/// Displays the specified connection or all connections in this Region.
/// </summary>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeConnections service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeConnections">REST API Reference for DescribeConnections Operation</seealso>
public virtual Task<DescribeConnectionsResponse> DescribeConnectionsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
return DescribeConnectionsAsync(new DescribeConnectionsRequest(), cancellationToken);
}
/// <summary>
/// Displays the specified connection or all connections in this Region.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeConnections service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeConnections service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeConnections">REST API Reference for DescribeConnections Operation</seealso>
public virtual Task<DescribeConnectionsResponse> DescribeConnectionsAsync(DescribeConnectionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeConnectionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeConnectionsResponseUnmarshaller.Instance;
return InvokeAsync<DescribeConnectionsResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeConnectionsOnInterconnect
[Obsolete("Deprecated in favor of DescribeHostedConnections.")]
internal virtual DescribeConnectionsOnInterconnectResponse DescribeConnectionsOnInterconnect(DescribeConnectionsOnInterconnectRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeConnectionsOnInterconnectRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeConnectionsOnInterconnectResponseUnmarshaller.Instance;
return Invoke<DescribeConnectionsOnInterconnectResponse>(request, options);
}
/// <summary>
/// Deprecated. Use <a>DescribeHostedConnections</a> instead.
///
///
/// <para>
/// Lists the connections that have been provisioned on the specified interconnect.
/// </para>
/// <note>
/// <para>
/// Intended for use by AWS Direct Connect Partners only.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeConnectionsOnInterconnect service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeConnectionsOnInterconnect service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeConnectionsOnInterconnect">REST API Reference for DescribeConnectionsOnInterconnect Operation</seealso>
[Obsolete("Deprecated in favor of DescribeHostedConnections.")]
public virtual Task<DescribeConnectionsOnInterconnectResponse> DescribeConnectionsOnInterconnectAsync(DescribeConnectionsOnInterconnectRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeConnectionsOnInterconnectRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeConnectionsOnInterconnectResponseUnmarshaller.Instance;
return InvokeAsync<DescribeConnectionsOnInterconnectResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeDirectConnectGatewayAssociationProposals
internal virtual DescribeDirectConnectGatewayAssociationProposalsResponse DescribeDirectConnectGatewayAssociationProposals(DescribeDirectConnectGatewayAssociationProposalsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeDirectConnectGatewayAssociationProposalsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeDirectConnectGatewayAssociationProposalsResponseUnmarshaller.Instance;
return Invoke<DescribeDirectConnectGatewayAssociationProposalsResponse>(request, options);
}
/// <summary>
/// Describes one or more association proposals for connection between a virtual private
/// gateway or transit gateway and a Direct Connect gateway.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeDirectConnectGatewayAssociationProposals service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeDirectConnectGatewayAssociationProposals service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeDirectConnectGatewayAssociationProposals">REST API Reference for DescribeDirectConnectGatewayAssociationProposals Operation</seealso>
public virtual Task<DescribeDirectConnectGatewayAssociationProposalsResponse> DescribeDirectConnectGatewayAssociationProposalsAsync(DescribeDirectConnectGatewayAssociationProposalsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeDirectConnectGatewayAssociationProposalsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeDirectConnectGatewayAssociationProposalsResponseUnmarshaller.Instance;
return InvokeAsync<DescribeDirectConnectGatewayAssociationProposalsResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeDirectConnectGatewayAssociations
internal virtual DescribeDirectConnectGatewayAssociationsResponse DescribeDirectConnectGatewayAssociations(DescribeDirectConnectGatewayAssociationsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeDirectConnectGatewayAssociationsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeDirectConnectGatewayAssociationsResponseUnmarshaller.Instance;
return Invoke<DescribeDirectConnectGatewayAssociationsResponse>(request, options);
}
/// <summary>
/// Lists the associations between your Direct Connect gateways and virtual private gateways.
/// You must specify a Direct Connect gateway, a virtual private gateway, or both. If
/// you specify a Direct Connect gateway, the response contains all virtual private gateways
/// associated with the Direct Connect gateway. If you specify a virtual private gateway,
/// the response contains all Direct Connect gateways associated with the virtual private
/// gateway. If you specify both, the response contains the association between the Direct
/// Connect gateway and the virtual private gateway.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeDirectConnectGatewayAssociations service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeDirectConnectGatewayAssociations service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeDirectConnectGatewayAssociations">REST API Reference for DescribeDirectConnectGatewayAssociations Operation</seealso>
public virtual Task<DescribeDirectConnectGatewayAssociationsResponse> DescribeDirectConnectGatewayAssociationsAsync(DescribeDirectConnectGatewayAssociationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeDirectConnectGatewayAssociationsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeDirectConnectGatewayAssociationsResponseUnmarshaller.Instance;
return InvokeAsync<DescribeDirectConnectGatewayAssociationsResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeDirectConnectGatewayAttachments
internal virtual DescribeDirectConnectGatewayAttachmentsResponse DescribeDirectConnectGatewayAttachments(DescribeDirectConnectGatewayAttachmentsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeDirectConnectGatewayAttachmentsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeDirectConnectGatewayAttachmentsResponseUnmarshaller.Instance;
return Invoke<DescribeDirectConnectGatewayAttachmentsResponse>(request, options);
}
/// <summary>
/// Lists the attachments between your Direct Connect gateways and virtual interfaces.
/// You must specify a Direct Connect gateway, a virtual interface, or both. If you specify
/// a Direct Connect gateway, the response contains all virtual interfaces attached to
/// the Direct Connect gateway. If you specify a virtual interface, the response contains
/// all Direct Connect gateways attached to the virtual interface. If you specify both,
/// the response contains the attachment between the Direct Connect gateway and the virtual
/// interface.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeDirectConnectGatewayAttachments service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeDirectConnectGatewayAttachments service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeDirectConnectGatewayAttachments">REST API Reference for DescribeDirectConnectGatewayAttachments Operation</seealso>
public virtual Task<DescribeDirectConnectGatewayAttachmentsResponse> DescribeDirectConnectGatewayAttachmentsAsync(DescribeDirectConnectGatewayAttachmentsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeDirectConnectGatewayAttachmentsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeDirectConnectGatewayAttachmentsResponseUnmarshaller.Instance;
return InvokeAsync<DescribeDirectConnectGatewayAttachmentsResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeDirectConnectGateways
internal virtual DescribeDirectConnectGatewaysResponse DescribeDirectConnectGateways(DescribeDirectConnectGatewaysRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeDirectConnectGatewaysRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeDirectConnectGatewaysResponseUnmarshaller.Instance;
return Invoke<DescribeDirectConnectGatewaysResponse>(request, options);
}
/// <summary>
/// Lists all your Direct Connect gateways or only the specified Direct Connect gateway.
/// Deleted Direct Connect gateways are not returned.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeDirectConnectGateways service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeDirectConnectGateways service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeDirectConnectGateways">REST API Reference for DescribeDirectConnectGateways Operation</seealso>
public virtual Task<DescribeDirectConnectGatewaysResponse> DescribeDirectConnectGatewaysAsync(DescribeDirectConnectGatewaysRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeDirectConnectGatewaysRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeDirectConnectGatewaysResponseUnmarshaller.Instance;
return InvokeAsync<DescribeDirectConnectGatewaysResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeHostedConnections
internal virtual DescribeHostedConnectionsResponse DescribeHostedConnections(DescribeHostedConnectionsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeHostedConnectionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeHostedConnectionsResponseUnmarshaller.Instance;
return Invoke<DescribeHostedConnectionsResponse>(request, options);
}
/// <summary>
/// Lists the hosted connections that have been provisioned on the specified interconnect
/// or link aggregation group (LAG).
///
/// <note>
/// <para>
/// Intended for use by AWS Direct Connect Partners only.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeHostedConnections service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeHostedConnections service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeHostedConnections">REST API Reference for DescribeHostedConnections Operation</seealso>
public virtual Task<DescribeHostedConnectionsResponse> DescribeHostedConnectionsAsync(DescribeHostedConnectionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeHostedConnectionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeHostedConnectionsResponseUnmarshaller.Instance;
return InvokeAsync<DescribeHostedConnectionsResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeInterconnectLoa
[Obsolete("Deprecated in favor of DescribeLoa.")]
internal virtual DescribeInterconnectLoaResponse DescribeInterconnectLoa(DescribeInterconnectLoaRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeInterconnectLoaRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeInterconnectLoaResponseUnmarshaller.Instance;
return Invoke<DescribeInterconnectLoaResponse>(request, options);
}
/// <summary>
/// Deprecated. Use <a>DescribeLoa</a> instead.
///
///
/// <para>
/// Gets the LOA-CFA for the specified interconnect.
/// </para>
///
/// <para>
/// The Letter of Authorization - Connecting Facility Assignment (LOA-CFA) is a document
/// that is used when establishing your cross connect to AWS at the colocation facility.
/// For more information, see <a href="https://docs.aws.amazon.com/directconnect/latest/UserGuide/Colocation.html">Requesting
/// Cross Connects at AWS Direct Connect Locations</a> in the <i>AWS Direct Connect User
/// Guide</i>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeInterconnectLoa service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeInterconnectLoa service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeInterconnectLoa">REST API Reference for DescribeInterconnectLoa Operation</seealso>
[Obsolete("Deprecated in favor of DescribeLoa.")]
public virtual Task<DescribeInterconnectLoaResponse> DescribeInterconnectLoaAsync(DescribeInterconnectLoaRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeInterconnectLoaRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeInterconnectLoaResponseUnmarshaller.Instance;
return InvokeAsync<DescribeInterconnectLoaResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeInterconnects
internal virtual DescribeInterconnectsResponse DescribeInterconnects()
{
return DescribeInterconnects(new DescribeInterconnectsRequest());
}
internal virtual DescribeInterconnectsResponse DescribeInterconnects(DescribeInterconnectsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeInterconnectsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeInterconnectsResponseUnmarshaller.Instance;
return Invoke<DescribeInterconnectsResponse>(request, options);
}
/// <summary>
/// Lists the interconnects owned by the AWS account or only the specified interconnect.
/// </summary>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeInterconnects service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeInterconnects">REST API Reference for DescribeInterconnects Operation</seealso>
public virtual Task<DescribeInterconnectsResponse> DescribeInterconnectsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
return DescribeInterconnectsAsync(new DescribeInterconnectsRequest(), cancellationToken);
}
/// <summary>
/// Lists the interconnects owned by the AWS account or only the specified interconnect.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeInterconnects service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeInterconnects service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeInterconnects">REST API Reference for DescribeInterconnects Operation</seealso>
public virtual Task<DescribeInterconnectsResponse> DescribeInterconnectsAsync(DescribeInterconnectsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeInterconnectsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeInterconnectsResponseUnmarshaller.Instance;
return InvokeAsync<DescribeInterconnectsResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeLags
internal virtual DescribeLagsResponse DescribeLags(DescribeLagsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeLagsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeLagsResponseUnmarshaller.Instance;
return Invoke<DescribeLagsResponse>(request, options);
}
/// <summary>
/// Describes all your link aggregation groups (LAG) or the specified LAG.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeLags service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeLags service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeLags">REST API Reference for DescribeLags Operation</seealso>
public virtual Task<DescribeLagsResponse> DescribeLagsAsync(DescribeLagsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeLagsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeLagsResponseUnmarshaller.Instance;
return InvokeAsync<DescribeLagsResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeLoa
internal virtual DescribeLoaResponse DescribeLoa(DescribeLoaRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeLoaRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeLoaResponseUnmarshaller.Instance;
return Invoke<DescribeLoaResponse>(request, options);
}
/// <summary>
/// Gets the LOA-CFA for a connection, interconnect, or link aggregation group (LAG).
///
///
/// <para>
/// The Letter of Authorization - Connecting Facility Assignment (LOA-CFA) is a document
/// that is used when establishing your cross connect to AWS at the colocation facility.
/// For more information, see <a href="https://docs.aws.amazon.com/directconnect/latest/UserGuide/Colocation.html">Requesting
/// Cross Connects at AWS Direct Connect Locations</a> in the <i>AWS Direct Connect User
/// Guide</i>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeLoa service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeLoa service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeLoa">REST API Reference for DescribeLoa Operation</seealso>
public virtual Task<DescribeLoaResponse> DescribeLoaAsync(DescribeLoaRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeLoaRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeLoaResponseUnmarshaller.Instance;
return InvokeAsync<DescribeLoaResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeLocations
internal virtual DescribeLocationsResponse DescribeLocations()
{
return DescribeLocations(new DescribeLocationsRequest());
}
internal virtual DescribeLocationsResponse DescribeLocations(DescribeLocationsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeLocationsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeLocationsResponseUnmarshaller.Instance;
return Invoke<DescribeLocationsResponse>(request, options);
}
/// <summary>
/// Lists the AWS Direct Connect locations in the current AWS Region. These are the locations
/// that can be selected when calling <a>CreateConnection</a> or <a>CreateInterconnect</a>.
/// </summary>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeLocations service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeLocations">REST API Reference for DescribeLocations Operation</seealso>
public virtual Task<DescribeLocationsResponse> DescribeLocationsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
return DescribeLocationsAsync(new DescribeLocationsRequest(), cancellationToken);
}
/// <summary>
/// Lists the AWS Direct Connect locations in the current AWS Region. These are the locations
/// that can be selected when calling <a>CreateConnection</a> or <a>CreateInterconnect</a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeLocations service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeLocations service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeLocations">REST API Reference for DescribeLocations Operation</seealso>
public virtual Task<DescribeLocationsResponse> DescribeLocationsAsync(DescribeLocationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeLocationsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeLocationsResponseUnmarshaller.Instance;
return InvokeAsync<DescribeLocationsResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeTags
internal virtual DescribeTagsResponse DescribeTags(DescribeTagsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeTagsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeTagsResponseUnmarshaller.Instance;
return Invoke<DescribeTagsResponse>(request, options);
}
/// <summary>
/// Describes the tags associated with the specified AWS Direct Connect resources.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeTags service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeTags service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeTags">REST API Reference for DescribeTags Operation</seealso>
public virtual Task<DescribeTagsResponse> DescribeTagsAsync(DescribeTagsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeTagsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeTagsResponseUnmarshaller.Instance;
return InvokeAsync<DescribeTagsResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeVirtualGateways
internal virtual DescribeVirtualGatewaysResponse DescribeVirtualGateways()
{
return DescribeVirtualGateways(new DescribeVirtualGatewaysRequest());
}
internal virtual DescribeVirtualGatewaysResponse DescribeVirtualGateways(DescribeVirtualGatewaysRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeVirtualGatewaysRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeVirtualGatewaysResponseUnmarshaller.Instance;
return Invoke<DescribeVirtualGatewaysResponse>(request, options);
}
/// <summary>
/// Lists the virtual private gateways owned by the AWS account.
///
///
/// <para>
/// You can create one or more AWS Direct Connect private virtual interfaces linked to
/// a virtual private gateway.
/// </para>
/// </summary>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeVirtualGateways service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeVirtualGateways">REST API Reference for DescribeVirtualGateways Operation</seealso>
public virtual Task<DescribeVirtualGatewaysResponse> DescribeVirtualGatewaysAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
return DescribeVirtualGatewaysAsync(new DescribeVirtualGatewaysRequest(), cancellationToken);
}
/// <summary>
/// Lists the virtual private gateways owned by the AWS account.
///
///
/// <para>
/// You can create one or more AWS Direct Connect private virtual interfaces linked to
/// a virtual private gateway.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeVirtualGateways service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeVirtualGateways service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeVirtualGateways">REST API Reference for DescribeVirtualGateways Operation</seealso>
public virtual Task<DescribeVirtualGatewaysResponse> DescribeVirtualGatewaysAsync(DescribeVirtualGatewaysRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeVirtualGatewaysRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeVirtualGatewaysResponseUnmarshaller.Instance;
return InvokeAsync<DescribeVirtualGatewaysResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeVirtualInterfaces
internal virtual DescribeVirtualInterfacesResponse DescribeVirtualInterfaces()
{
return DescribeVirtualInterfaces(new DescribeVirtualInterfacesRequest());
}
internal virtual DescribeVirtualInterfacesResponse DescribeVirtualInterfaces(DescribeVirtualInterfacesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeVirtualInterfacesRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeVirtualInterfacesResponseUnmarshaller.Instance;
return Invoke<DescribeVirtualInterfacesResponse>(request, options);
}
/// <summary>
/// Displays all virtual interfaces for an AWS account. Virtual interfaces deleted fewer
/// than 15 minutes before you make the request are also returned. If you specify a connection
/// ID, only the virtual interfaces associated with the connection are returned. If you
/// specify a virtual interface ID, then only a single virtual interface is returned.
///
///
/// <para>
/// A virtual interface (VLAN) transmits the traffic between the AWS Direct Connect location
/// and the customer network.
/// </para>
/// </summary>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeVirtualInterfaces service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeVirtualInterfaces">REST API Reference for DescribeVirtualInterfaces Operation</seealso>
public virtual Task<DescribeVirtualInterfacesResponse> DescribeVirtualInterfacesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
return DescribeVirtualInterfacesAsync(new DescribeVirtualInterfacesRequest(), cancellationToken);
}
/// <summary>
/// Displays all virtual interfaces for an AWS account. Virtual interfaces deleted fewer
/// than 15 minutes before you make the request are also returned. If you specify a connection
/// ID, only the virtual interfaces associated with the connection are returned. If you
/// specify a virtual interface ID, then only a single virtual interface is returned.
///
///
/// <para>
/// A virtual interface (VLAN) transmits the traffic between the AWS Direct Connect location
/// and the customer network.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeVirtualInterfaces service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeVirtualInterfaces service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DescribeVirtualInterfaces">REST API Reference for DescribeVirtualInterfaces Operation</seealso>
public virtual Task<DescribeVirtualInterfacesResponse> DescribeVirtualInterfacesAsync(DescribeVirtualInterfacesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeVirtualInterfacesRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeVirtualInterfacesResponseUnmarshaller.Instance;
return InvokeAsync<DescribeVirtualInterfacesResponse>(request, options, cancellationToken);
}
#endregion
#region DisassociateConnectionFromLag
internal virtual DisassociateConnectionFromLagResponse DisassociateConnectionFromLag(DisassociateConnectionFromLagRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DisassociateConnectionFromLagRequestMarshaller.Instance;
options.ResponseUnmarshaller = DisassociateConnectionFromLagResponseUnmarshaller.Instance;
return Invoke<DisassociateConnectionFromLagResponse>(request, options);
}
/// <summary>
/// Disassociates a connection from a link aggregation group (LAG). The connection is
/// interrupted and re-established as a standalone connection (the connection is not deleted;
/// to delete the connection, use the <a>DeleteConnection</a> request). If the LAG has
/// associated virtual interfaces or hosted connections, they remain associated with the
/// LAG. A disassociated connection owned by an AWS Direct Connect Partner is automatically
/// converted to an interconnect.
///
///
/// <para>
/// If disassociating the connection would cause the LAG to fall below its setting for
/// minimum number of operational connections, the request fails, except when it's the
/// last member of the LAG. If all connections are disassociated, the LAG continues to
/// exist as an empty LAG with no physical connections.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DisassociateConnectionFromLag service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DisassociateConnectionFromLag service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DisassociateConnectionFromLag">REST API Reference for DisassociateConnectionFromLag Operation</seealso>
public virtual Task<DisassociateConnectionFromLagResponse> DisassociateConnectionFromLagAsync(DisassociateConnectionFromLagRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DisassociateConnectionFromLagRequestMarshaller.Instance;
options.ResponseUnmarshaller = DisassociateConnectionFromLagResponseUnmarshaller.Instance;
return InvokeAsync<DisassociateConnectionFromLagResponse>(request, options, cancellationToken);
}
#endregion
#region TagResource
internal virtual TagResourceResponse TagResource(TagResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = TagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance;
return Invoke<TagResourceResponse>(request, options);
}
/// <summary>
/// Adds the specified tags to the specified AWS Direct Connect resource. Each resource
/// can have a maximum of 50 tags.
///
///
/// <para>
/// Each tag consists of a key and an optional value. If a tag with the same key is already
/// associated with the resource, this action updates its value.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the TagResource service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DuplicateTagKeysException">
/// A tag key was specified more than once.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.TooManyTagsException">
/// You have reached the limit on the number of tags that can be assigned.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual Task<TagResourceResponse> TagResourceAsync(TagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = TagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance;
return InvokeAsync<TagResourceResponse>(request, options, cancellationToken);
}
#endregion
#region UntagResource
internal virtual UntagResourceResponse UntagResource(UntagResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UntagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance;
return Invoke<UntagResourceResponse>(request, options);
}
/// <summary>
/// Removes one or more tags from the specified AWS Direct Connect resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UntagResource service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual Task<UntagResourceResponse> UntagResourceAsync(UntagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UntagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance;
return InvokeAsync<UntagResourceResponse>(request, options, cancellationToken);
}
#endregion
#region UpdateDirectConnectGatewayAssociation
internal virtual UpdateDirectConnectGatewayAssociationResponse UpdateDirectConnectGatewayAssociation(UpdateDirectConnectGatewayAssociationRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateDirectConnectGatewayAssociationRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateDirectConnectGatewayAssociationResponseUnmarshaller.Instance;
return Invoke<UpdateDirectConnectGatewayAssociationResponse>(request, options);
}
/// <summary>
/// Updates the specified attributes of the Direct Connect gateway association.
///
///
/// <para>
/// Add or remove prefixes from the association.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateDirectConnectGatewayAssociation service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UpdateDirectConnectGatewayAssociation service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/UpdateDirectConnectGatewayAssociation">REST API Reference for UpdateDirectConnectGatewayAssociation Operation</seealso>
public virtual Task<UpdateDirectConnectGatewayAssociationResponse> UpdateDirectConnectGatewayAssociationAsync(UpdateDirectConnectGatewayAssociationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateDirectConnectGatewayAssociationRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateDirectConnectGatewayAssociationResponseUnmarshaller.Instance;
return InvokeAsync<UpdateDirectConnectGatewayAssociationResponse>(request, options, cancellationToken);
}
#endregion
#region UpdateLag
internal virtual UpdateLagResponse UpdateLag(UpdateLagRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateLagRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateLagResponseUnmarshaller.Instance;
return Invoke<UpdateLagResponse>(request, options);
}
/// <summary>
/// Updates the attributes of the specified link aggregation group (LAG).
///
///
/// <para>
/// You can update the following attributes:
/// </para>
/// <ul> <li>
/// <para>
/// The name of the LAG.
/// </para>
/// </li> <li>
/// <para>
/// The value for the minimum number of connections that must be operational for the LAG
/// itself to be operational.
/// </para>
/// </li> </ul>
/// <para>
/// When you create a LAG, the default value for the minimum number of operational connections
/// is zero (0). If you update this value and the number of operational connections falls
/// below the specified value, the LAG automatically goes down to avoid over-utilization
/// of the remaining connections. Adjust this value with care, as it could force the LAG
/// down if it is set higher than the current number of operational connections.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateLag service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UpdateLag service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/UpdateLag">REST API Reference for UpdateLag Operation</seealso>
public virtual Task<UpdateLagResponse> UpdateLagAsync(UpdateLagRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateLagRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateLagResponseUnmarshaller.Instance;
return InvokeAsync<UpdateLagResponse>(request, options, cancellationToken);
}
#endregion
#region UpdateVirtualInterfaceAttributes
internal virtual UpdateVirtualInterfaceAttributesResponse UpdateVirtualInterfaceAttributes(UpdateVirtualInterfaceAttributesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateVirtualInterfaceAttributesRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateVirtualInterfaceAttributesResponseUnmarshaller.Instance;
return Invoke<UpdateVirtualInterfaceAttributesResponse>(request, options);
}
/// <summary>
/// Updates the specified attributes of the specified virtual private interface.
///
///
/// <para>
/// Setting the MTU of a virtual interface to 9001 (jumbo frames) can cause an update
/// to the underlying physical connection if it wasn't updated to support jumbo frames.
/// Updating the connection disrupts network connectivity for all virtual interfaces associated
/// with the connection for up to 30 seconds. To check whether your connection supports
/// jumbo frames, call <a>DescribeConnections</a>. To check whether your virtual interface
/// supports jumbo frames, call <a>DescribeVirtualInterfaces</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateVirtualInterfaceAttributes service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UpdateVirtualInterfaceAttributes service method, as returned by DirectConnect.</returns>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectClientException">
/// One or more parameters are not valid.
/// </exception>
/// <exception cref="Amazon.DirectConnect.Model.DirectConnectServerException">
/// A server-side error occurred.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/UpdateVirtualInterfaceAttributes">REST API Reference for UpdateVirtualInterfaceAttributes Operation</seealso>
public virtual Task<UpdateVirtualInterfaceAttributesResponse> UpdateVirtualInterfaceAttributesAsync(UpdateVirtualInterfaceAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateVirtualInterfaceAttributesRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateVirtualInterfaceAttributesResponseUnmarshaller.Instance;
return InvokeAsync<UpdateVirtualInterfaceAttributesResponse>(request, options, cancellationToken);
}
#endregion
}
} | 53.857817 | 287 | 0.692831 | [
"Apache-2.0"
] | icanread/aws-sdk-net | sdk/src/Services/DirectConnect/Generated/_mobile/AmazonDirectConnectClient.cs | 159,850 | C# |
using Radical.Conversions;
using Radical.Windows.ComponentModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
namespace Radical.Windows.Regions
{
/// <summary>
/// An content region hosted by a ContentPresenter.
/// </summary>
public sealed class ContentPresenterRegion : ContentRegion<ContentPresenter>
{
/// <summary>
/// Initializes a new instance of the <see cref="ContentPresenterRegion"/> class.
/// </summary>
public ContentPresenterRegion()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ContentPresenterRegion"/> class.
/// </summary>
/// <param name="name">The name.</param>
public ContentPresenterRegion(string name )
: base( name )
{
}
/// <summary>
/// Called to get content.
/// </summary>
/// <returns></returns>
protected override DependencyObject OnGetContent()
{
return Element.Content as DependencyObject;
}
/// <summary>
/// Called to set new content.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="args">The cancel even arguments.</param>
protected override void OnSetContent( DependencyObject view, CancelEventArgs args )
{
if (Element.Content is DependencyObject previous)
{
RegionService.Conventions
.GetViewDataContext(previous, RegionService.Conventions.DefaultViewDataContextSearchBehavior)
.As<IExpectViewClosingCallback>(i => i.OnViewClosing(args));
}
if ( !args.Cancel )
{
Element.Content = view;
}
}
}
}
| 29.709677 | 113 | 0.574376 | [
"MIT"
] | RadicalFx/Radical.Windows | src/Radical.Windows/Regions/ContentPresenterRegion.cs | 1,844 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using BrightstarDB.Dto;
using BrightstarDB.Model;
#if PORTABLE
using BrightstarDB.Portable.Compatibility;
#elif WINDOWS_PHONE
using BrightstarDB.Mobile.Compatibility;
#else
using System.Collections.Concurrent;
#endif
using BrightstarDB.Query;
using BrightstarDB.Storage;
using BrightstarDB.Storage.Persistence;
using VDS.RDF.Query;
#if !SILVERLIGHT
using System.ServiceModel;
#endif
namespace BrightstarDB.Server
{
///<summary>
/// Called by the store worker after the thread has been successfully terminated.
///</summary>
internal delegate void ShutdownContinuation();
/// <summary>
/// This can be considered a logical store. A logical store is comprised of 2 physical stores. A read store and a write store.
/// Read requests coming in to the store worker are dispatched to the readStore. The readStore pulls data in from the disk as required, until
/// it reaches some predefined levels at which point the cache is flushed.
/// Update transactions coming to the logical store are put in a queue. The logical store has a worker thread that processes each transaction
/// one at time. All updates are made against the writeStore. When a transaction completes the read store instance is invalidated so that the
/// next read request to arrive forces the data to be re-read from disk.
/// </summary>
internal class StoreWorker
{
// write store
private IStore _writeStore;
// read store
private IStore _readStore;
// store name
private readonly string _storeName;
// store directory location
private readonly string _baseLocation;
// store location
private readonly string _storeLocation;
// job queue
private readonly ConcurrentQueue<Job> _jobs;
private readonly ITransactionLog _transactionLog;
private readonly IStoreStatisticsLog _storeStatisticsLog;
private StatsMonitor _statsMonitor;
// todo: might need to make this persistent or clear it out now and again.
private readonly ConcurrentDictionary<string, JobExecutionStatus> _jobExecutionStatus;
private bool _shutdownRequested;
private bool _completeRemainingJobs;
private readonly ManualResetEvent _shutdownCompleted;
/// <summary>
/// Event fired after a successful job execution but before the job status is updated to completed
/// </summary>
internal event JobCompletedDelegate JobCompleted;
/// <summary>
/// Called after we shutdown all jobs and close all file handles.
/// </summary>
private ShutdownContinuation _shutdownContinuation;
/// <summary>
/// Creates a new server core
/// </summary>
/// <param name="baseLocation">Path to the stores directory</param>
/// <param name="storeName">Name of store</param>
public StoreWorker(string baseLocation, string storeName)
{
_baseLocation = baseLocation;
_storeName = storeName;
_storeLocation = Path.Combine(baseLocation, storeName);
Logging.LogInfo("StoreWorker created with location {0}", _storeLocation);
_jobs = new ConcurrentQueue<Job>();
_jobExecutionStatus = new ConcurrentDictionary<string, JobExecutionStatus>();
_storeManager = StoreManagerFactory.GetStoreManager();
_transactionLog = _storeManager.GetTransactionLog(_storeLocation);
_storeStatisticsLog = _storeManager.GetStatisticsLog(_storeLocation);
_statsMonitor = new StatsMonitor();
InitializeStatsMonitor();
_shutdownCompleted = new ManualResetEvent(false);
}
/// <summary>
/// Starts the thread that processes the jobs queue.
/// </summary>
public void Start()
{
ThreadPool.QueueUserWorkItem(ProcessJobs);
}
public ITransactionLog TransactionLog
{
get { return _transactionLog; }
}
public IStoreStatisticsLog StoreStatistics
{
get { return _storeStatisticsLog; }
}
private void ProcessJobs(object state)
{
Logging.LogInfo("Process Jobs Started");
while (!_shutdownRequested)
{
try
{
if (_shutdownRequested && !_completeRemainingJobs) break;
Job job;
_jobs.TryDequeue(out job);
if (job != null)
{
Logging.LogInfo("Job found {0}", job.JobId);
// process job
JobExecutionStatus jobExecutionStatus;
if (_jobExecutionStatus.TryGetValue(job.JobId.ToString(), out jobExecutionStatus))
{
try
{
jobExecutionStatus.Information = "Job Started";
jobExecutionStatus.Started = DateTime.UtcNow;
jobExecutionStatus.JobStatus = JobStatus.Started;
var st = DateTime.UtcNow;
job.Run();
var et = DateTime.UtcNow;
#if SILVERLIGHT || PORTABLE
Logging.LogInfo("Job completed in {0}", et.Subtract(st).TotalMilliseconds);
#else
Logging.LogInfo("Job completed in {0} : Current memory usage : {1}",et.Subtract(st).TotalMilliseconds, System.Diagnostics.Process.GetCurrentProcess().WorkingSet64 );
#endif
jobExecutionStatus.Information = "Job Completed";
jobExecutionStatus.Ended = DateTime.UtcNow;
jobExecutionStatus.JobStatus = JobStatus.CompletedOk;
jobExecutionStatus.WaitEvent.Set();
}
catch (Exception ex)
{
Logging.LogError(BrightstarEventId.JobProcessingError,
"Error Processing Transaction {0}",
ex);
jobExecutionStatus.Information = job.ErrorMessage ?? "Job Error";
jobExecutionStatus.Ended = DateTime.UtcNow;
jobExecutionStatus.ExceptionDetail = GetExceptionDetail(ex);
jobExecutionStatus.JobStatus = JobStatus.TransactionError;
jobExecutionStatus.WaitEvent.Set();
}
finally
{
if (JobCompleted!= null)
{
JobCompleted(this, new JobCompletedEventArgs(_storeName, job));
}
}
}
}
_shutdownCompleted.WaitOne(1);
}
catch (Exception ex)
{
Logging.LogError(BrightstarEventId.JobProcessingError,
"Unexpected exception caught in ProcessJobs loop: {0}", ex);
}
}
ReleaseResources();
if (_shutdownContinuation != null)
{
try
{
_shutdownContinuation();
}
catch (Exception ex)
{
Logging.LogError(BrightstarEventId.JobProcessingError,
"Unexpected exception caught in processing Shutdown continuation: {0}", ex);
}
}
}
private static ExceptionDetailObject GetExceptionDetail(Exception ex)
{
if (ex is PreconditionFailedException)
{
var pfe = ex as PreconditionFailedException;
return pfe.AsExceptionDetailObject();
}
return new ExceptionDetailObject(ex);
}
public IEnumerable<JobExecutionStatus> GetJobs()
{
return _jobExecutionStatus.Values.OrderByDescending(x => x.Queued);
}
public JobExecutionStatus GetJobStatus(string jobId)
{
JobExecutionStatus status;
if (_jobExecutionStatus.TryGetValue(jobId, out status))
{
return status;
}
return null;
}
/// <summary>
/// This is used to ensure there is no race condition when returning
/// the readstore when commits are occurring.
/// </summary>
private readonly object _readStoreLock = new object();
private readonly IStoreManager _storeManager;
internal void InvalidateReadStore()
{
lock(_readStoreLock)
{
// KA: Don't close the read store at this point
// as export jobs or queries may still be using it
// instead the store should dispose of any resources
// when it is garbage collected.
// This fixes an issue found in ClientTests.TestExportWhileWriting
//if (_readStore != null)
//{
// _readStore.Close();
//}
_readStore = null;
}
}
internal IStore ReadStore
{
get
{
lock (_readStoreLock)
{
return _readStore ?? (_readStore = _storeManager.OpenStore(_storeLocation, true));
}
}
}
internal IStore WriteStore
{
get { return _writeStore ?? (_writeStore = _storeManager.OpenStore(_storeLocation)); }
}
public BrightstarSparqlResultsType Query(ulong commitPointId, SparqlQuery query, ISerializationFormat targetFormat, Stream resultsStream, string[] defaultGraphUris)
{
// Not supported by read/write store so no handling for ReadWriteStoreModifiedException required
Logging.LogDebug("CommitPointId={0}, Query={1}", commitPointId, query);
using (var readStore = _storeManager.OpenStore(_storeLocation, commitPointId))
{
return readStore.ExecuteSparqlQuery(query, targetFormat, resultsStream, defaultGraphUris);
}
}
public BrightstarSparqlResultsType Query(SparqlQuery query, ISerializationFormat targetFormat, Stream resultsStream, string[] defaultGraphUris )
{
Logging.LogDebug("Query {0}", query);
try
{
return ReadStore.ExecuteSparqlQuery(query, targetFormat, resultsStream, defaultGraphUris);
}
catch (ReadWriteStoreModifiedException)
{
Logging.LogDebug("Read/Write store was concurrently modified. Attempting a retry");
InvalidateReadStore();
return Query(query, targetFormat, resultsStream, defaultGraphUris);
}
}
public void QueueJob(Job job, bool incrementTransactionCount = true)
{
Logging.LogDebug("Queueing Job Id {0}", job.JobId);
bool queuedJob = false;
while (!queuedJob)
{
if (
_jobExecutionStatus.TryAdd(
job.JobId.ToString(),
new JobExecutionStatus
{
JobId = job.JobId,
JobStatus = JobStatus.Pending,
Queued = DateTime.UtcNow,
Label = job.Label,
WaitEvent = new AutoResetEvent(false)
}))
{
_jobs.Enqueue(job);
queuedJob = true;
Logging.LogDebug("Queued Job Id {0}", job.JobId);
_statsMonitor.OnJobScheduled(incrementTransactionCount);
}
}
}
/// <summary>
/// Queue a txn job.
/// </summary>
/// <param name="preconditions">The triples that must be present for txn to succeed</param>
/// <param name="notExistsPreconditions">The triples that must not be present for txn to succeed</param>
/// <param name="deletePatterns"></param>
/// <param name="insertData"></param>
/// <param name="defaultGraphUri"></param>
/// <param name="format"></param>
/// <param name="jobLabel"></param>
/// <returns></returns>
public Guid ProcessTransaction(string preconditions, string notExistsPreconditions, string deletePatterns, string insertData, string defaultGraphUri, string format, string jobLabel= null)
{
Logging.LogDebug("ProcessTransaction");
var jobId = Guid.NewGuid();
var job = new GuardedUpdateTransaction(jobId, jobLabel, this, preconditions, notExistsPreconditions,
deletePatterns, insertData, defaultGraphUri);
QueueJob(job);
return jobId;
}
public Guid Import(string contentFileName, string graphUri, string jobLabel = null)
{
Logging.LogDebug("Import {0}, {1}", contentFileName, graphUri);
var jobId = Guid.NewGuid();
var job = new ImportJob(jobId, jobLabel, this, contentFileName, graphUri);
QueueJob(job);
return jobId;
}
public Guid Export(string fileName, string graphUri, RdfFormat exportFormat, string jobLabel = null)
{
Logging.LogDebug("Export {0}, {1}, {2}", fileName, graphUri, exportFormat.DefaultExtension);
var jobId = Guid.NewGuid();
var exportJob = new ExportJob(jobId, jobLabel, this, fileName, graphUri, exportFormat);
_jobExecutionStatus.TryAdd(jobId.ToString(),
new JobExecutionStatus
{
JobId = jobId,
JobStatus = JobStatus.Started,
Queued = DateTime.UtcNow,
Started = DateTime.UtcNow,
Label = jobLabel,
WaitEvent = new AutoResetEvent(false)
});
exportJob.Run((id, ex) =>
{
JobExecutionStatus jobExecutionStatus;
if (_jobExecutionStatus.TryGetValue(id.ToString(), out jobExecutionStatus))
{
jobExecutionStatus.Information = "Export failed";
jobExecutionStatus.ExceptionDetail = GetExceptionDetail(ex);
jobExecutionStatus.JobStatus = JobStatus.TransactionError;
jobExecutionStatus.Ended = DateTime.UtcNow;
jobExecutionStatus.WaitEvent.Set();
}
},
id =>
{
JobExecutionStatus jobExecutionStatus;
if (_jobExecutionStatus.TryGetValue(id.ToString(), out jobExecutionStatus))
{
jobExecutionStatus.Information = "Export completed";
jobExecutionStatus.JobStatus = JobStatus.CompletedOk;
jobExecutionStatus.Ended = DateTime.UtcNow;
jobExecutionStatus.WaitEvent.Set();
}
});
return jobId;
}
public Guid UpdateStatistics(string jobLabel = null)
{
Logging.LogDebug("UpdateStatistics");
var jobId = Guid.NewGuid();
var job = new UpdateStatsJob(jobId, jobLabel, this);
QueueJob(job);
return jobId;
}
public Guid QueueSnapshotJob(string destinationStoreName, PersistenceType persistenceType, ulong commitPointId = StoreConstants.NullUlong, string jobLabel = null)
{
Logging.LogDebug("QueueSnapshotJob {0}, {1}", destinationStoreName, commitPointId);
var jobId = Guid.NewGuid();
var snapshotJob = new SnapshotJob(jobId, jobLabel, this, destinationStoreName, persistenceType, commitPointId);
QueueJob(snapshotJob, false);
return jobId;
}
internal void CreateSnapshot(string destinationStoreName, PersistenceType persistenceType, ulong commitPointId)
{
_storeManager.CreateSnapshot(_storeLocation, Path.Combine(_baseLocation, destinationStoreName), persistenceType, commitPointId);
}
public IEnumerable<Triple> GetResourceStatements(string resourceUri)
{
Logging.LogDebug("GetResourceStatements {0}", resourceUri);
try
{
return ReadStore.GetResourceStatements(resourceUri);
}
catch (ReadWriteStoreModifiedException)
{
Logging.LogDebug("Read/Write store was concurrently modified. Attempting retry.");
InvalidateReadStore();
return GetResourceStatements(resourceUri);
}
}
private void ReleaseResources()
{
lock (this)
{
// close read and write stores
if (_readStore != null)
{
_readStore.Close();
_readStore.Dispose();
_readStore = null;
}
if (_writeStore != null)
{
_writeStore.Close();
_writeStore.Dispose();
_writeStore = null;
}
}
}
public void Shutdown(bool completeJobs, ShutdownContinuation c = null)
{
_shutdownContinuation = c;
_shutdownRequested = true;
_completeRemainingJobs = completeJobs;
ReleaseResources();
}
public void Consolidate(Guid jobId)
{
ReleaseResources();
_writeStore = null;
_readStore = null;
WriteStore.Consolidate(jobId);
ReleaseResources();
_writeStore = null;
_readStore = null;
}
private void InitializeStatsMonitor()
{
if (Configuration.StatsUpdateTimespan > 0 || Configuration.StatsUpdateTransactionCount > 0)
{
var lastStats = _storeStatisticsLog.GetStatistics().FirstOrDefault();
CommitPoint lastCommitPoint;
using (var readStore = _storeManager.OpenStore(_storeLocation, true))
{
lastCommitPoint = readStore.GetCommitPoints().FirstOrDefault();
}
_statsMonitor.Initialize(lastStats, lastCommitPoint == null ? 0 : lastCommitPoint.CommitNumber,
() => UpdateStatistics());
}
}
/// <summary>
/// Preload index and resource pages for this store
/// </summary>
/// <param name="pageCacheRatio">The fractional amount of the number of available cache pages to use in the preload</param>
public void WarmupStore(decimal pageCacheRatio)
{
if (pageCacheRatio > 1.0m) pageCacheRatio = 1.0m;
#if PORTABLE || WINDOWS_PHONE
var pagesToPreload = (int)Math.Floor(PageCache.Instance.FreePages * (float)pageCacheRatio);
#else
var pagesToPreload = (int)Math.Floor(PageCache.Instance.FreePages*pageCacheRatio);
#endif
ReadStore.WarmupPageCache(pagesToPreload);
}
}
}
| 41.200397 | 197 | 0.536528 | [
"MIT"
] | rajcybage/BrightstarDB | src/core/BrightstarDB/Server/StoreWorker.cs | 20,767 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: IMethodRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The interface IWorkbookFunctionsImSinRequest.
/// </summary>
public partial interface IWorkbookFunctionsImSinRequest : IBaseRequest
{
/// <summary>
/// Gets the request body.
/// </summary>
WorkbookFunctionsImSinRequestBody RequestBody { get; }
/// <summary>
/// Issues the POST request.
/// </summary>
System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync();
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(
CancellationToken cancellationToken);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IWorkbookFunctionsImSinRequest Expand(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IWorkbookFunctionsImSinRequest Select(string value);
}
}
| 35.344828 | 153 | 0.585366 | [
"MIT"
] | DamienTehDemon/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/IWorkbookFunctionsImSinRequest.cs | 2,050 | C# |
#if NET6_0_OR_GREATER
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using VerifyTests;
class DateConverter :
WriteOnlyJsonConverter<DateOnly>
{
SharedScrubber scrubber;
public DateConverter(SharedScrubber scrubber)
{
this.scrubber = scrubber;
}
public override void WriteJson(
JsonWriter writer,
DateOnly value,
JsonSerializer serializer,
IReadOnlyDictionary<string, object> context)
{
if (scrubber.TryConvert(value, out var result))
{
writer.WriteValue(result);
return;
}
writer.WriteValue(value);
}
}
#endif | 21.212121 | 56 | 0.62 | [
"MIT"
] | CyberFlameGO/Verify | src/Verify/Serialization/Converters/DateConverter.cs | 670 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/d3d12.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public partial struct D3D12_QUERY_DATA_PIPELINE_STATISTICS
{
[NativeTypeName("UINT64")]
public ulong IAVertices;
[NativeTypeName("UINT64")]
public ulong IAPrimitives;
[NativeTypeName("UINT64")]
public ulong VSInvocations;
[NativeTypeName("UINT64")]
public ulong GSInvocations;
[NativeTypeName("UINT64")]
public ulong GSPrimitives;
[NativeTypeName("UINT64")]
public ulong CInvocations;
[NativeTypeName("UINT64")]
public ulong CPrimitives;
[NativeTypeName("UINT64")]
public ulong PSInvocations;
[NativeTypeName("UINT64")]
public ulong HSInvocations;
[NativeTypeName("UINT64")]
public ulong DSInvocations;
[NativeTypeName("UINT64")]
public ulong CSInvocations;
}
}
| 26.636364 | 145 | 0.658703 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/d3d12/D3D12_QUERY_DATA_PIPELINE_STATISTICS.cs | 1,174 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace ConvertPowerpointToPDF4dots
{
public class StringRange
{
private string Range = "";
public StringRange(string stringrange)
{
Range = stringrange;
}
public bool IsInRange(int k)
{
if (Range == string.Empty) return true;
string[] ranges = Range.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
string kk = k.ToString();
for (int m = 0; m < ranges.Length; m++)
{
if (ranges[m] == kk) return true;
if (ranges[m].IndexOf("-") > 0)
{
string st = ranges[m].Substring(0, ranges[m].IndexOf("-"));
int ist = -1;
ist = int.Parse(st);
string en = ranges[m].Substring(ranges[m].IndexOf("-") + 1);
int ien = -1;
ien = int.Parse(en);
if (k >= ist && k <= ien)
{
return true;
}
}
else
{
return false;
}
}
return false;
}
}
}
| 23.963636 | 103 | 0.409712 | [
"MIT"
] | fourDotsSoftware/ConvertPowerpointToPDF4dots | ConvertPowerpointToPDF4dots/StringRange.cs | 1,320 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
using IL2CPU.API;
namespace Cosmos.IL2CPU
{
internal class MemberInfoComparer : IEqualityComparer<MemberInfo>
{
public static MemberInfoComparer Instance { get; } = new MemberInfoComparer();
public bool Equals(MemberInfo x, MemberInfo y)
{
if (x == null)
{
return y == null;
}
if (y == null)
{
return false;
}
if (x.GetType() == y.GetType())
{
if (x.MetadataToken == y.MetadataToken && x.Module == y.Module)
{
if (x is MethodBase xMethod && y is MethodBase yMethod)
{
return LabelName.GetFullName(xMethod) == LabelName.GetFullName(yMethod);
}
else if (x is Type xType && y is Type yType)
{
return LabelName.GetFullName(xType) == LabelName.GetFullName(yType);
}
else
{
return true;
}
}
}
return false;
}
public int GetHashCode(MemberInfo aItem)
{
return (aItem.ToString() + GetDeclareTypeString(aItem)).GetHashCode();
}
private static string GetDeclareTypeString(MemberInfo item)
{
var xName = item.DeclaringType;
return xName == null ? String.Empty : xName.ToString();
}
}
}
| 27.745763 | 96 | 0.471594 | [
"BSD-3-Clause"
] | CosmosOS/IL2CPU | source/Cosmos.IL2CPU/MemberInfoComparer.cs | 1,639 | 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>
/// WfmUserNotificationTopicWfmUserNotification
/// </summary>
[DataContract]
public partial class WfmUserNotificationTopicWfmUserNotification : IEquatable<WfmUserNotificationTopicWfmUserNotification>
{
/// <summary>
/// Gets or Sets Type
/// </summary>
[JsonConverter(typeof(UpgradeSdkEnumConverter))]
public enum TypeEnum
{
/// <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 Shifttrade for "ShiftTrade"
/// </summary>
[EnumMember(Value = "ShiftTrade")]
Shifttrade,
/// <summary>
/// Enum Timeoffrequest for "TimeOffRequest"
/// </summary>
[EnumMember(Value = "TimeOffRequest")]
Timeoffrequest
}
/// <summary>
/// Gets or Sets Type
/// </summary>
[DataMember(Name="type", EmitDefaultValue=false)]
public TypeEnum? Type { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="WfmUserNotificationTopicWfmUserNotification" /> class.
/// </summary>
/// <param name="Id">Id.</param>
/// <param name="MutableGroupId">MutableGroupId.</param>
/// <param name="Timestamp">Timestamp.</param>
/// <param name="Type">Type.</param>
/// <param name="ShiftTrade">ShiftTrade.</param>
/// <param name="TimeOffRequest">TimeOffRequest.</param>
/// <param name="AgentNotification">AgentNotification.</param>
/// <param name="OtherNotificationIdsInGroup">OtherNotificationIdsInGroup.</param>
/// <param name="MarkedAsRead">MarkedAsRead.</param>
public WfmUserNotificationTopicWfmUserNotification(string Id = null, string MutableGroupId = null, DateTime? Timestamp = null, TypeEnum? Type = null, WfmUserNotificationTopicShiftTradeNotification ShiftTrade = null, WfmUserNotificationTopicTimeOffRequestNotification TimeOffRequest = null, bool? AgentNotification = null, List<string> OtherNotificationIdsInGroup = null, bool? MarkedAsRead = null)
{
this.Id = Id;
this.MutableGroupId = MutableGroupId;
this.Timestamp = Timestamp;
this.Type = Type;
this.ShiftTrade = ShiftTrade;
this.TimeOffRequest = TimeOffRequest;
this.AgentNotification = AgentNotification;
this.OtherNotificationIdsInGroup = OtherNotificationIdsInGroup;
this.MarkedAsRead = MarkedAsRead;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets MutableGroupId
/// </summary>
[DataMember(Name="mutableGroupId", EmitDefaultValue=false)]
public string MutableGroupId { get; set; }
/// <summary>
/// Gets or Sets Timestamp
/// </summary>
[DataMember(Name="timestamp", EmitDefaultValue=false)]
public DateTime? Timestamp { get; set; }
/// <summary>
/// Gets or Sets ShiftTrade
/// </summary>
[DataMember(Name="shiftTrade", EmitDefaultValue=false)]
public WfmUserNotificationTopicShiftTradeNotification ShiftTrade { get; set; }
/// <summary>
/// Gets or Sets TimeOffRequest
/// </summary>
[DataMember(Name="timeOffRequest", EmitDefaultValue=false)]
public WfmUserNotificationTopicTimeOffRequestNotification TimeOffRequest { get; set; }
/// <summary>
/// Gets or Sets AgentNotification
/// </summary>
[DataMember(Name="agentNotification", EmitDefaultValue=false)]
public bool? AgentNotification { get; set; }
/// <summary>
/// Gets or Sets OtherNotificationIdsInGroup
/// </summary>
[DataMember(Name="otherNotificationIdsInGroup", EmitDefaultValue=false)]
public List<string> OtherNotificationIdsInGroup { get; set; }
/// <summary>
/// Gets or Sets MarkedAsRead
/// </summary>
[DataMember(Name="markedAsRead", EmitDefaultValue=false)]
public bool? MarkedAsRead { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class WfmUserNotificationTopicWfmUserNotification {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" MutableGroupId: ").Append(MutableGroupId).Append("\n");
sb.Append(" Timestamp: ").Append(Timestamp).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" ShiftTrade: ").Append(ShiftTrade).Append("\n");
sb.Append(" TimeOffRequest: ").Append(TimeOffRequest).Append("\n");
sb.Append(" AgentNotification: ").Append(AgentNotification).Append("\n");
sb.Append(" OtherNotificationIdsInGroup: ").Append(OtherNotificationIdsInGroup).Append("\n");
sb.Append(" MarkedAsRead: ").Append(MarkedAsRead).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 WfmUserNotificationTopicWfmUserNotification);
}
/// <summary>
/// Returns true if WfmUserNotificationTopicWfmUserNotification instances are equal
/// </summary>
/// <param name="other">Instance of WfmUserNotificationTopicWfmUserNotification to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(WfmUserNotificationTopicWfmUserNotification 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.MutableGroupId == other.MutableGroupId ||
this.MutableGroupId != null &&
this.MutableGroupId.Equals(other.MutableGroupId)
) &&
(
this.Timestamp == other.Timestamp ||
this.Timestamp != null &&
this.Timestamp.Equals(other.Timestamp)
) &&
(
this.Type == other.Type ||
this.Type != null &&
this.Type.Equals(other.Type)
) &&
(
this.ShiftTrade == other.ShiftTrade ||
this.ShiftTrade != null &&
this.ShiftTrade.Equals(other.ShiftTrade)
) &&
(
this.TimeOffRequest == other.TimeOffRequest ||
this.TimeOffRequest != null &&
this.TimeOffRequest.Equals(other.TimeOffRequest)
) &&
(
this.AgentNotification == other.AgentNotification ||
this.AgentNotification != null &&
this.AgentNotification.Equals(other.AgentNotification)
) &&
(
this.OtherNotificationIdsInGroup == other.OtherNotificationIdsInGroup ||
this.OtherNotificationIdsInGroup != null &&
this.OtherNotificationIdsInGroup.SequenceEqual(other.OtherNotificationIdsInGroup)
) &&
(
this.MarkedAsRead == other.MarkedAsRead ||
this.MarkedAsRead != null &&
this.MarkedAsRead.Equals(other.MarkedAsRead)
);
}
/// <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.MutableGroupId != null)
hash = hash * 59 + this.MutableGroupId.GetHashCode();
if (this.Timestamp != null)
hash = hash * 59 + this.Timestamp.GetHashCode();
if (this.Type != null)
hash = hash * 59 + this.Type.GetHashCode();
if (this.ShiftTrade != null)
hash = hash * 59 + this.ShiftTrade.GetHashCode();
if (this.TimeOffRequest != null)
hash = hash * 59 + this.TimeOffRequest.GetHashCode();
if (this.AgentNotification != null)
hash = hash * 59 + this.AgentNotification.GetHashCode();
if (this.OtherNotificationIdsInGroup != null)
hash = hash * 59 + this.OtherNotificationIdsInGroup.GetHashCode();
if (this.MarkedAsRead != null)
hash = hash * 59 + this.MarkedAsRead.GetHashCode();
return hash;
}
}
}
}
| 34.391304 | 405 | 0.516056 | [
"MIT"
] | F-V-L/platform-client-sdk-dotnet | build/src/PureCloudPlatform.Client.V2/Model/WfmUserNotificationTopicWfmUserNotification.cs | 11,865 | C# |
// Copyright (c) Jerry Lee. All rights reserved. Licensed under the MIT License. See LICENSE in the
// project root for license information.
using System.Linq;
namespace System.Collections.Generic
{
/// <summary>
/// Extension methods for interface <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
public static class IDictionaryExtensions
{
#region Methods
/// <summary>
/// Adds the value with unique key.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="source">The source Dictionary object.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="canReplace">
/// if set to <c>true</c>, the value will be replaced when find same key.
/// </param>
public static void AddUnique<TKey, TValue>(this IDictionary<TKey, TValue> source, TKey key, TValue value, bool canReplace = true)
{
try
{
source.Add(key, value);
}
catch (ArgumentException)
{
if (canReplace)
{
source[key] = value;
}
}
}
/// <summary>
/// Gets the key by value.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="source">The source Dictionary object.</param>
/// <param name="value">The value.</param>
/// <returns>The value object.</returns>
public static TKey GetKey<TKey, TValue>(this IDictionary<TKey, TValue> source, TValue value)
{
return source.FirstOrDefault(q => q.Value.Equals(value)).Key;
}
/// <summary>
/// Merges dictionaries.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="source">The source dictionary.</param>
/// <param name="others">The other dictionaries.</param>
/// <returns>The dictionary contains all values of source dictionary and others.</returns>
public static TResult MergeLeft<TResult, TKey, TValue>(this TResult source, params IDictionary<TKey, TValue>[] others)
where TResult : IDictionary<TKey, TValue>, new()
{
TResult newMap = new TResult();
foreach (IDictionary<TKey, TValue> src in
(new List<IDictionary<TKey, TValue>> { source }).Concat(others))
{
foreach (KeyValuePair<TKey, TValue> p in src)
{
newMap[p.Key] = p.Value;
}
}
return newMap;
}
#endregion Methods
}
} | 38.5125 | 137 | 0.553716 | [
"MIT"
] | cosmos53076/ReSharp.Core | src/ReSharp.Core/Assets/Scripts/System/Collections/Generic/IDictionaryExtensions.cs | 3,083 | C# |
using System.Collections.Generic;
using System.Collections;
using UnityEngine;
using DG.Tweening;
public class Mover : MonoBehaviour
{
[HideInInspector] public Vector3 goalPosition;
public List<Tile> tiles = new List<Tile>();
[HideInInspector] public bool isFalling = false;
public bool isPlayer { get { return CompareTag("Player"); }}
void Start()
{
CreateTiles();
}
void CreateTiles()
{
tiles.Clear();
foreach (Transform child in transform)
{
if (child.gameObject.CompareTag("Tile"))
{
Tile tile = new Tile();
tile.t = child;
tiles.Add(tile);
}
}
}
public void Reset()
{
isFalling = false;
}
public virtual bool CanMove(Vector3 dir)
{
foreach (Tile tile in tiles)
{
Vector3Int posToCheck = Vector3Int.RoundToInt(tile.pos + dir);
if (PositionBuffer.WallIsAtPos(posToCheck))
{
return false;
}
Mover m = PositionBuffer.GetMoverAtPos(posToCheck);
if (m != null && m != this)
{
if (!isPlayer && !Game.isPolyban)
return false;
if (m.CanMove(dir))
m.MoveIt(dir);
else
return false;
}
}
return true;
}
public void MoveIt(Vector3 dir)
{
if (!Game.moversToMove.Contains(this))
{
goalPosition = transform.position + dir;
Game.moversToMove.Add(this);
}
}
public virtual bool ShouldFall()
{
if (GroundBelow())
return false;
return true;
}
public virtual void FallStart()
{
if (ShouldFall())
{
if (!isFalling)
{
isFalling = true;
Game.Get().movingCount++;
}
goalPosition = transform.position + Game.Get().fallDirection;
transform.DOMove(goalPosition, Game.Get().fallTime).OnComplete(FallAgain).SetEase(Ease.Linear);
} else
FallEnd();
}
void FallAgain()
{
StartCoroutine(DoFallAgain());
}
IEnumerator DoFallAgain()
{
yield return WaitFor.EndOfFrame;
FallStart();
}
public void FallEnd()
{
if (isFalling)
{
isFalling = false;
Game.Get().movingCount--;
Game.Get().FallEnd();
}
}
public bool GroundBelow()
{
foreach (Tile tile in tiles)
{
// Disabling this for now
// if (Utils.Roughly(tile.pos.y, 0))
// return true;
if (GroundBelowTile(tile))
return true;
}
return false;
}
bool GroundBelowTile(Tile tile)
{
Vector3Int posToCheck = Vector3Int.RoundToInt(tile.pos + Game.Get().fallDirection);
if (PositionBuffer.WallIsAtPos(posToCheck))
return true;
Mover m = PositionBuffer.GetMoverAtPos(posToCheck);
if (m != null && m != this && !m.isFalling)
return true;
return false;
}
void OnDrawGizmosSelected()
{
if (!Application.isPlaying)
CreateTiles();
Gizmos.color = Color.blue;
foreach (Tile tile in tiles)
Gizmos.DrawWireCube(tile.pos, Vector3.one);
}
}
| 18.019868 | 98 | 0.656744 | [
"MIT"
] | goldenxp/blocks | Assets/Scripts/Mover.cs | 2,723 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VMS.TPS.Common.Model.Types;
using static VMS.TPS.Common.Model.Types.DoseValue;
namespace ESAPIX.Helpers.DVH
{
public class DVHParams
{
public DoseValuePresentation DosePresentation { get; set; } = DoseValuePresentation.Absolute;
public VolumePresentation VolumePresentation { get; set; } = VolumePresentation.Relative;
public double BinWidth { get; set; } = 1;
public DoseUnit DoseUnits { get; set; } = DoseUnit.Gy;
}
}
| 30.947368 | 101 | 0.72619 | [
"MIT"
] | avalgoma/ESAPIX | ESAPIX/Helpers/DVH/DVHParams.cs | 590 | C# |
using System;
using ViceCity.IO.Contracts;
namespace ViceCity.IO.Models
{
public class Writer : IWriter
{
public void Write(string line)
{
Console.Write(line);
}
public void WriteLine(string line)
{
Console.WriteLine(line);
}
}
}
| 16.684211 | 42 | 0.548896 | [
"MIT"
] | PetroslavGochev/CSharpAdvancedModule | OOP Module C#/09.ExamPreparation/2019August11/ViceCity/ViceCity/IO/Models/Writer.cs | 319 | C# |
using System;
using System.Xml.Serialization;
namespace NPOI.OpenXmlFormats.Wordprocessing
{
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IncludeInSchema = false)]
public enum ItemsChoiceType26
{
[XmlEnum("http://schemas.openxmlformats.org/officeDocument/2006/math:oMath")]
oMath,
[XmlEnum("http://schemas.openxmlformats.org/officeDocument/2006/math:oMathPara")]
oMathPara,
bookmarkEnd,
bookmarkStart,
commentRangeEnd,
commentRangeStart,
customXml,
customXmlDelRangeEnd,
customXmlDelRangeStart,
customXmlInsRangeEnd,
customXmlInsRangeStart,
customXmlMoveFromRangeEnd,
customXmlMoveFromRangeStart,
customXmlMoveToRangeEnd,
customXmlMoveToRangeStart,
del,
ins,
moveFrom,
moveFromRangeEnd,
moveFromRangeStart,
moveTo,
moveToRangeEnd,
moveToRangeStart,
p,
permEnd,
permStart,
proofErr,
sdt,
tbl
}
}
| 21.348837 | 111 | 0.775599 | [
"MIT"
] | iNeverSleeeeep/NPOI-For-Unity | NPOI.OpenXmlFormats.Wordprocessing/ItemsChoiceType26.cs | 918 | C# |
namespace Clean.Architecture.Web.Endpoints.ProjectEndpoints;
public class DeleteProjectRequest
{
public const string Route = "/Projects/{ProjectId:int}";
public static string BuildRoute(int projectId) => Route.Replace("{ProjectId:int}", projectId.ToString());
public int ProjectId { get; set; }
}
| 31.2 | 109 | 0.74359 | [
"MIT"
] | RichardHowells/CleanArchitecture | src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/Delete.DeleteProjectRequest.cs | 314 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** 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.Ovh.Inputs
{
public sealed class IpServicePlanConfigurationGetArgs : Pulumi.ResourceArgs
{
[Input("label", required: true)]
public Input<string> Label { get; set; } = null!;
[Input("value", required: true)]
public Input<string> Value { get; set; } = null!;
public IpServicePlanConfigurationGetArgs()
{
}
}
}
| 27.346154 | 88 | 0.66948 | [
"ECL-2.0",
"Apache-2.0"
] | legitbee/pulumi-ovh | sdk/dotnet/Inputs/IpServicePlanConfigurationGetArgs.cs | 711 | C# |
// PawnColumnWorker_Handler.cs
// Copyright Karel Kroeze, 2019-2019
using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using UnityEngine;
using Verse;
namespace AnimalTab {
public class PawnColumnWorker_Handler: PawnColumnWorker {
public override int GetMinWidth(PawnTable table) {
return 100;
}
public override int GetMaxWidth(PawnTable table) {
return 100;
}
public override void DoCell(Rect rect, Pawn target, PawnTable table) {
CompHandlerSettings settings = target.HandlerSettings();
if (settings.Mode == HandlerMode.Level) {
if (Mouse.IsOver(rect) && Input.GetMouseButtonDown(1)) {
DoHandlerFloatMenu(target);
}
Rect sliderRect = new Rect(
rect.xMin,
rect.yMin,
rect.width,
rect.height * 2f / 3f )
.CenteredOnYIn( rect );
IntRange level = settings.Level;
Widgets.IntRange(sliderRect, target.GetHashCode(), ref level, 0, 20);
if (level != settings.Level) {
settings.Level = level.Clamp(target);
}
TooltipHandler.TipRegion(rect, "Fluffy.AnimalTab.RightClickToChangeHandler".Translate());
} else {
string label = settings.Handler?.LabelShort ??
$"({"Fluffy.AnimalTab.HandlerMode.Any".Translate().RawText.ToLowerInvariant()})";
if (Widgets.ButtonText(rect.ContractedBy(2f), label)) {
DoHandlerFloatMenu(target);
}
}
}
private void DoHandlerFloatMenu(Pawn target) {
CompHandlerSettings settings = target.HandlerSettings();
int minSkill = TrainableUtility.MinimumHandlingSkill( target );
List<FloatMenuOption> options = new List<FloatMenuOption> {
new FloatMenuOption(HandlerMode.Any.Label(), () => settings.Mode = HandlerMode.Any),
new FloatMenuOption(HandlerMode.Level.Label(), () => settings.Mode = HandlerMode.Level)
};
foreach (Pawn handler in HandlerUtility.HandlersOrdered(target.Map)) {
options.Add(new FloatMenuOption(HandlerUtility.HandlerLabel(handler, minSkill),
() => settings.Handler = handler));
}
Find.WindowStack.Add(new FloatMenu(options));
}
private void DoMassHandlerFloatMenu(List<Pawn> targets, Map map) {
List<FloatMenuOption> options = new List<FloatMenuOption> {
new FloatMenuOption(HandlerMode.Any.Label(), () => targets.ForEach(t => t.HandlerSettings().Mode = HandlerMode.Any)),
new FloatMenuOption(HandlerMode.Level.Label(), () => targets.ForEach(t => t.HandlerSettings().Mode = HandlerMode.Level))
};
foreach (Pawn handler in HandlerUtility.HandlersOrdered(map)) {
options.Add(new FloatMenuOption(HandlerUtility.HandlerLabel(handler), () => targets.ForEach(t => t.HandlerSettings().Handler = handler)));
}
Find.WindowStack.Add(new FloatMenu(options));
}
public override int Compare(Pawn a, Pawn b) {
CompHandlerSettings settingsA = a.HandlerSettings();
CompHandlerSettings settingsB = b.HandlerSettings();
if (settingsA.Mode != settingsB.Mode) {
return settingsA.Mode.CompareTo(settingsB.Mode);
}
if (settingsA.Mode == HandlerMode.Specific) {
return string.Compare(settingsA.Handler.LabelShort, settingsB.Handler.LabelShort, StringComparison.Ordinal);
}
if (settingsA.Mode == HandlerMode.Level) {
if (settingsA.Level.min != settingsB.Level.min) {
return settingsA.Level.min.CompareTo(settingsB.Level.min);
}
if (settingsA.Level.max != settingsB.Level.max) {
return settingsA.Level.min.CompareTo(settingsB.Level.max);
}
}
return 0;
}
public override void DoHeader(Rect rect, PawnTable table) {
List<Pawn> targets = table.PawnsListForReading;
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) {
if (targets.Any() && targets.All(p => p.HandlerSettings()?.Mode == HandlerMode.Level)) {
if (Mouse.IsOver(rect) && Input.GetMouseButtonDown(1)) {
DoMassHandlerFloatMenu(targets, Find.CurrentMap);
}
Rect sliderRect = new Rect(
rect.xMin,
rect.yMin,
rect.width,
rect.height * 2f / 3f )
.CenteredOnYIn( rect );
IntRange level = targets.First().HandlerSettings().Level;
IntRange _level = level;
Widgets.IntRange(sliderRect, 24, ref level, 0, 20);
if (level != _level) {
foreach (Pawn target in targets) {
target.HandlerSettings().Level = level.Clamp(target);
}
}
TooltipHandler.TipRegion(rect, "Fluffy.AnimalTab.HandlerHeaderTip_RightClick".Translate());
} else {
if (Widgets.ButtonInvisible(rect)) {
DoMassHandlerFloatMenu(targets, Find.CurrentMap);
}
base.DoHeader(rect, table);
}
} else {
base.DoHeader(rect, table);
}
}
protected override string GetHeaderTip(PawnTable table) {
return base.GetHeaderTip(table) + "\n" + "Fluffy.AnimalTab.HandlerHeaderTip".Translate();
}
}
}
| 41.653061 | 154 | 0.544341 | [
"MIT"
] | FluffierThanThou/AnimalTab | Source/AnimalTab/PawnColumns/PawnColumnWorker_Handler.cs | 6,123 | C# |
using UnityEngine;
using System.Collections;
using System;
using wuxingogo.Runtime;
using System.Collections.Generic;
using wuxingogo.Code;
namespace wuxingogo.Code
{
[System.Reflection.Obfuscation]
[System.Serializable]
public class XCodeType
{
[SerializeField] string typeName = string.Empty;
public XCodeType(string typeName)
{
this.typeName = typeName;
}
public XCodeType(Type type)
{
this.typeName = type.AssemblyQualifiedName;
this.type = type;
}
private Type type;
public Type Target {
get
{
if( type != null )
return type;
return Type.GetType( typeName);
}
}
public override string ToString()
{
return string.Format("[XCodeType: Target={0}]", Target.Name.ToString());
}
}
public enum XTypeEnum
{
Integer,
Float,
String,
Double,
Vector,
GameObject
}
}
| 14.35 | 75 | 0.675958 | [
"MIT"
] | ClassWarhammer/Base1 | WuxingogoEditor/CodeEditor/XCodeType.cs | 861 | C# |
namespace AngleSharp.Html.Dom
{
using AngleSharp.Attributes;
using System;
/// <summary>
/// Represents the time HTML element.
/// </summary>
[DomName("HTMLTimeElement")]
public interface IHtmlTimeElement : IHtmlElement
{
/// <summary>
/// Gets or sets the time.
/// </summary>
[DomName("datetime")]
String? DateTime { get; set; }
}
}
| 21.684211 | 52 | 0.570388 | [
"MIT"
] | Aizeren/AngleSharp | src/AngleSharp/Html/Dom/IHtmlTimeElement.cs | 412 | C# |
namespace IMM.Web.Controllers
{
using System;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using IMM.Models;
using IMM.Web.ViewModels.ManageViewModels;
using IMM.Data.Services;
using IMM.Web.Common.Infrastructure.Extensions;
[Authorize]
[Route("[controller]/[action]")]
public class ManageController : Controller
{
private readonly UserManager<User> _userManager;
private readonly SignInManager<User> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ILogger _logger;
private readonly UrlEncoder _urlEncoder;
private const string AuthenticatorUriFormat = "otpauth://totp/{0}:{1}?secret={2}&issuer={0}&digits=6";
private const string RecoveryCodesKey = nameof(RecoveryCodesKey);
public ManageController(
UserManager<User> userManager,
SignInManager<User> signInManager,
IEmailSender emailSender,
ILogger<ManageController> logger,
UrlEncoder urlEncoder)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_logger = logger;
_urlEncoder = urlEncoder;
}
[TempData]
public string StatusMessage { get; set; }
[HttpGet]
public async Task<IActionResult> Index()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var model = new IndexViewModel
{
Username = user.UserName,
Email = user.Email,
PhoneNumber = user.PhoneNumber,
IsEmailConfirmed = user.EmailConfirmed,
StatusMessage = StatusMessage
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(IndexViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var email = user.Email;
if (model.Email != email)
{
var setEmailResult = await _userManager.SetEmailAsync(user, model.Email);
if (!setEmailResult.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred setting email for user with ID '{user.Id}'.");
}
}
var phoneNumber = user.PhoneNumber;
if (model.PhoneNumber != phoneNumber)
{
var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, model.PhoneNumber);
if (!setPhoneResult.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred setting phone number for user with ID '{user.Id}'.");
}
}
StatusMessage = "Your profile has been updated";
return RedirectToAction(nameof(Index));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendVerificationEmail(IndexViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
var email = user.Email;
await _emailSender.SendEmailConfirmationAsync(email, callbackUrl);
StatusMessage = "Verification email sent. Please check your email.";
return RedirectToAction(nameof(Index));
}
[HttpGet]
public async Task<IActionResult> ChangePassword()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var hasPassword = await _userManager.HasPasswordAsync(user);
if (!hasPassword)
{
return RedirectToAction(nameof(SetPassword));
}
var model = new ChangePasswordViewModel { StatusMessage = StatusMessage };
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var changePasswordResult = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (!changePasswordResult.Succeeded)
{
AddErrors(changePasswordResult);
return View(model);
}
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation("User changed their password successfully.");
StatusMessage = "Your password has been changed.";
return RedirectToAction(nameof(ChangePassword));
}
[HttpGet]
public async Task<IActionResult> SetPassword()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var hasPassword = await _userManager.HasPasswordAsync(user);
if (hasPassword)
{
return RedirectToAction(nameof(ChangePassword));
}
var model = new SetPasswordViewModel { StatusMessage = StatusMessage };
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var addPasswordResult = await _userManager.AddPasswordAsync(user, model.NewPassword);
if (!addPasswordResult.Succeeded)
{
AddErrors(addPasswordResult);
return View(model);
}
await _signInManager.SignInAsync(user, isPersistent: false);
StatusMessage = "Your password has been set.";
return RedirectToAction(nameof(SetPassword));
}
[HttpGet]
public async Task<IActionResult> ExternalLogins()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var model = new ExternalLoginsViewModel { CurrentLogins = await _userManager.GetLoginsAsync(user) };
model.OtherLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync())
.Where(auth => model.CurrentLogins.All(ul => auth.Name != ul.LoginProvider))
.ToList();
model.ShowRemoveButton = await _userManager.HasPasswordAsync(user) || model.CurrentLogins.Count > 1;
model.StatusMessage = StatusMessage;
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LinkLogin(string provider)
{
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action(nameof(LinkLoginCallback));
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
return new ChallengeResult(provider, properties);
}
[HttpGet]
public async Task<IActionResult> LinkLoginCallback()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var info = await _signInManager.GetExternalLoginInfoAsync(user.Id);
if (info == null)
{
throw new ApplicationException($"Unexpected error occurred loading external login info for user with ID '{user.Id}'.");
}
var result = await _userManager.AddLoginAsync(user, info);
if (!result.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred adding external login for user with ID '{user.Id}'.");
}
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
StatusMessage = "The external login was added.";
return RedirectToAction(nameof(ExternalLogins));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel model)
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var result = await _userManager.RemoveLoginAsync(user, model.LoginProvider, model.ProviderKey);
if (!result.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred removing external login for user with ID '{user.Id}'.");
}
await _signInManager.SignInAsync(user, isPersistent: false);
StatusMessage = "The external login was removed.";
return RedirectToAction(nameof(ExternalLogins));
}
[HttpGet]
public async Task<IActionResult> TwoFactorAuthentication()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var model = new TwoFactorAuthenticationViewModel
{
HasAuthenticator = await _userManager.GetAuthenticatorKeyAsync(user) != null,
Is2faEnabled = user.TwoFactorEnabled,
RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user),
};
return View(model);
}
[HttpGet]
public async Task<IActionResult> Disable2faWarning()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!user.TwoFactorEnabled)
{
throw new ApplicationException($"Unexpected error occured disabling 2FA for user with ID '{user.Id}'.");
}
return View(nameof(Disable2fa));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Disable2fa()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var disable2faResult = await _userManager.SetTwoFactorEnabledAsync(user, false);
if (!disable2faResult.Succeeded)
{
throw new ApplicationException($"Unexpected error occured disabling 2FA for user with ID '{user.Id}'.");
}
_logger.LogInformation("User with ID {UserId} has disabled 2fa.", user.Id);
return RedirectToAction(nameof(TwoFactorAuthentication));
}
[HttpGet]
public async Task<IActionResult> EnableAuthenticator()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var model = new EnableAuthenticatorViewModel();
await LoadSharedKeyAndQrCodeUriAsync(user, model);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableAuthenticator(EnableAuthenticatorViewModel model)
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!ModelState.IsValid)
{
await LoadSharedKeyAndQrCodeUriAsync(user, model);
return View(model);
}
// Strip spaces and hypens
var verificationCode = model.Code.Replace(" ", string.Empty).Replace("-", string.Empty);
var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync(
user, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode);
if (!is2faTokenValid)
{
ModelState.AddModelError("Code", "Verification code is invalid.");
await LoadSharedKeyAndQrCodeUriAsync(user, model);
return View(model);
}
await _userManager.SetTwoFactorEnabledAsync(user, true);
_logger.LogInformation("User with ID {UserId} has enabled 2FA with an authenticator app.", user.Id);
var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
TempData[RecoveryCodesKey] = recoveryCodes.ToArray();
return RedirectToAction(nameof(ShowRecoveryCodes));
}
[HttpGet]
public IActionResult ShowRecoveryCodes()
{
var recoveryCodes = (string[])TempData[RecoveryCodesKey];
if (recoveryCodes == null)
{
return RedirectToAction(nameof(TwoFactorAuthentication));
}
var model = new ShowRecoveryCodesViewModel { RecoveryCodes = recoveryCodes };
return View(model);
}
[HttpGet]
public IActionResult ResetAuthenticatorWarning()
{
return View(nameof(ResetAuthenticator));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetAuthenticator()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _userManager.ResetAuthenticatorKeyAsync(user);
_logger.LogInformation("User with id '{UserId}' has reset their authentication app key.", user.Id);
return RedirectToAction(nameof(EnableAuthenticator));
}
[HttpGet]
public async Task<IActionResult> GenerateRecoveryCodesWarning()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!user.TwoFactorEnabled)
{
throw new ApplicationException($"Cannot generate recovery codes for user with ID '{user.Id}' because they do not have 2FA enabled.");
}
return View(nameof(GenerateRecoveryCodes));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> GenerateRecoveryCodes()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!user.TwoFactorEnabled)
{
throw new ApplicationException($"Cannot generate recovery codes for user with ID '{user.Id}' as they do not have 2FA enabled.");
}
var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
_logger.LogInformation("User with ID {UserId} has generated new 2FA recovery codes.", user.Id);
var model = new ShowRecoveryCodesViewModel { RecoveryCodes = recoveryCodes.ToArray() };
return View(nameof(ShowRecoveryCodes), model);
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private string FormatKey(string unformattedKey)
{
var result = new StringBuilder();
int currentPosition = 0;
while (currentPosition + 4 < unformattedKey.Length)
{
result.Append(unformattedKey.Substring(currentPosition, 4)).Append(" ");
currentPosition += 4;
}
if (currentPosition < unformattedKey.Length)
{
result.Append(unformattedKey.Substring(currentPosition));
}
return result.ToString().ToLowerInvariant();
}
private string GenerateQrCodeUri(string email, string unformattedKey)
{
return string.Format(
AuthenticatorUriFormat,
_urlEncoder.Encode("IMM.Web"),
_urlEncoder.Encode(email),
unformattedKey);
}
private async Task LoadSharedKeyAndQrCodeUriAsync(User user, EnableAuthenticatorViewModel model)
{
var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
if (string.IsNullOrEmpty(unformattedKey))
{
await _userManager.ResetAuthenticatorKeyAsync(user);
unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
}
model.SharedKey = FormatKey(unformattedKey);
model.AuthenticatorUri = GenerateQrCodeUri(user.Email, unformattedKey);
}
#endregion
}
}
| 37.082569 | 149 | 0.587531 | [
"Apache-2.0"
] | OzoneBG/InfinityMotivationMovement | IMM.Web/Controllers/ManageController.cs | 20,212 | C# |
using System.Reflection;
namespace Blun.MQ.Messages.Strategies
{
internal interface IParameterMapperStrategy : IMapperStrategy
{
bool IsMappable(ParameterInfo parameterInfo);
object Mapping(int index, ParameterInfo parameterInfo, IMQRequest request);
}
} | 26 | 84 | 0.748252 | [
"MIT"
] | BLun78/Blun.MQ | Blun.MQ/Messages/Strategies/IParameterMapperStrategy.cs | 288 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Core.IPC;
namespace Core.Interface
{
/// <summary>
/// Used to signal to <see cref="Loader"/> that this function contains a buffer that needs to be mapped
/// across from client to server and visa versa
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public class BufferAttribute : Attribute
{
// Index of the buffer
public int Index { get; set; }
// Where the new buffer pointer should be placed
public int NewPointerIndex { get; set; }
// Where the new buffer size should be placed
public int NewSizeIndex { get; set; }
}
}
| 27.185185 | 107 | 0.659401 | [
"MIT"
] | emily33901/Argon | src/Core/Interface/BufferAttribute.cs | 734 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Storage.Streams;
using static LegoTrainProject.Port;
namespace LegoTrainProject
{
[Serializable]
public class SbrickHub : Hub
{
[NonSerialized]
Timer pingTimer = new Timer();
[NonSerialized]
GattCharacteristic CharacteristicCommands;
[NonSerialized]
private int LastCalibrationTick;
[NonSerialized]
private bool CalibrationIsDown;
[NonSerialized]
int MaxCurrent = 0;
public SbrickHub(BluetoothLEDevice device, Types type) : base (device, type)
{
}
internal override async Task RenewCharacteristic()
{
if (Device != null)
{
Device = await BluetoothLEDevice.FromBluetoothAddressAsync(Device.BluetoothAddress);
Gatt = await Device.GetGattServicesAsync(BluetoothCacheMode.Uncached);
AllCharacteristic = await Gatt.Services.Single(s => s.Uuid == Guid.Parse("4dc591b0-857c-41de-b5f1-15abda665b0c")).GetCharacteristicsAsync(BluetoothCacheMode.Uncached);
Characteristic = AllCharacteristic.Characteristics.Single(c => c.Uuid == Guid.Parse("489a6ae0-c1ab-4c9c-bdb2-11d373c1b7fb"));
CharacteristicCommands = AllCharacteristic.Characteristics.Single(c => c.Uuid == Guid.Parse("02b8cbcc-0e25-4bda-8790-a15f53e6010f"));
MainBoard.WriteLine("New Hub Found of type " + Enum.GetName(typeof(Hub.Types), Type), Color.Green);
}
// If we reconnect, let's recalibrate sensors
CalibrationIsDown = false;
LastCalibrationTick = Environment.TickCount;
// If we come back, we stop and start over.
if (pingTimer != null)
{
pingTimer.Stop();
pingTimer.Elapsed -= PingTimer_Elapsed;
}
else
pingTimer = new Timer();
pingTimer.Interval = 150;
pingTimer.Elapsed += PingTimer_Elapsed;
pingTimer.Start();
}
public override void InitPorts()
{
// Clear any previous port
RegistredPorts.Clear();
Port portA = new Port("A", 0, true);
Port portB = new Port("B", 2, true);
Port portC = new Port("C", 1, true);
Port portD = new Port("D", 3, true);
RegistredPorts.Add(portA);
RegistredPorts.Add(portB);
RegistredPorts.Add(portC);
RegistredPorts.Add(portD);
portA.Function = Port.Functions.MOTOR;
portB.Function = Port.Functions.MOTOR;
portC.Function = Port.Functions.MOTOR;
portD.Function = Port.Functions.MOTOR;
}
private void PingTimer_Elapsed(object sender, ElapsedEventArgs e)
{
WriteMessage(new byte[] { 0x02 }, CharacteristicCommands);
if (!CalibrationIsDown && Environment.TickCount - LastCalibrationTick > 5000)
{
foreach (Port p in RegistredPorts)
{
p.MaxDistance = 0;
p.MinDistance = 0;
}
CalibrationIsDown = true;
LastCalibrationTick = Environment.TickCount;
}
}
internal override void InitializeNotifications()
{
WriteMessage(new byte[] { 0x2C, 0x01, 0x03, 0x05, 0x07, 0x08}, CharacteristicCommands);
WriteMessage(new byte[] { 0x2E, 0x01, 0x03, 0x05, 0x07, 0x08}, CharacteristicCommands);
foreach (Port p in RegistredPorts)
Stop(p.Id, true);
CalibrationIsDown = false;
LastCalibrationTick = Environment.TickCount;
}
/// <summary>
/// Treat Incoming Data from the train
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
internal override void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
try
{
int numberOfMessage = 0;
// An Indicate or Notify reported that the value has changed.
var reader = DataReader.FromBuffer(args.CharacteristicValue);
while (reader.UnconsumedBufferLength > 0)
{
numberOfMessage++;
// We read the length and the rest of the body
byte len = reader.ReadByte();
byte[] message = new byte[len];
reader.ReadBytes(message);
//MainBoard.WriteLine(message[0] + " - " + message[1]);
switch (message[0])
{
case 0x04:
{
ParseStatus(message);
break;
};
case 0x06:
{
int portId = 0;
for (int i = 0; i < message.Length - 1; i += 2 )
{
var val = (short)(((message[i + 1] & 0xF0) >> 4) | (message[i + 2] << 4));
int channel = message[i + 1] & 0x0F;
if (channel == 8)
{
MaxCurrent = (int)(val / 2.85f);
double battery = (val / 4092f * 100f) * 2.6f;
BatteryLevel = (int)battery;
OnDataUpdated();
}
else
{
portId = (channel == 1) ? 0 : (channel == 3) ? 2 : (channel == 5) ? 1 : 3;
Port port = RegistredPorts[portId];
if (port.Function == Port.Functions.SENSOR)
{
int distance = 0;
port.MaxDistance = MaxCurrent; // (val > port.MaxDistance) ? val : port.MaxDistance;
port.MinDistance = (port.MinDistance == 0) ? port.MaxDistance - 50 : (val < port.MinDistance) ? val : port.MinDistance;
float distRatio = (float)(val - port.MinDistance) / (float)(port.MaxDistance - port.MinDistance);
distance = (int)(distRatio * 10f);
if (MainBoard.showColorDebug)
MainBoard.WriteLine($"{Name} (Port {port.Id} - Distance: " + distance + $" (Val: {val} Min: {port.MinDistance} Max: {port.MaxDistance} - last triggers was " + (Environment.TickCount - port.LastDistanceTick));
if (Environment.TickCount - port.LastDistanceTick > port.DistanceColorCooldownMs)
{
port.LatestDistance = (int)distance;
OnDistanceTriggered(this, port, (int)distance);
OnDataUpdated();
}
}
portId++;
}
}
break;
}
}
}
}
catch (Exception ex)
{
MainBoard.WriteLine("FATAL SBRICK: Something went wrong while reading messages!" + ex.Message, Color.DarkRed);
}
}
private static void ParseStatus(byte[] message)
{
switch (message[1])
{
case 0x00:
{
//MainBoard.WriteLine("SBRICK - ACK - ");
break;
}
case 0x01:
{
MainBoard.WriteLine("SBRICK - Invalid Data Length - ");
break;
}
case 0x02:
{
MainBoard.WriteLine("SBRICK - Invalid Parameter - ");
break;
}
case 0x03:
{
MainBoard.WriteLine("SBRICK - No Such Command - ");
break;
}
case 0x04:
{
MainBoard.WriteLine("SBRICK - No authentication needed - ");
break;
}
case 0x05:
{
MainBoard.WriteLine("SBRICK - Authentication error - ");
break;
}
case 0x06:
{
MainBoard.WriteLine("SBRICK - Authentication needed - ");
break;
}
case 0x08:
{
MainBoard.WriteLine("SBRICK - Thermal protection is active - ");
break;
}
case 0x09:
{
MainBoard.WriteLine("SBRICK - The system is in a state where the command does not make sense - ");
break;
}
}
}
protected override void WriteMessage(byte[] message, bool addLength)
{
WriteMessage(message, Characteristic);
}
protected async void WriteMessage(byte[] message, GattCharacteristic characteristic)
{
try
{
if (characteristic != null)
{
using (DataWriter writer = new DataWriter())
{
writer.WriteBytes(message);
await characteristic.WriteValueAsync(writer.DetachBuffer(), GattWriteOption.WriteWithoutResponse);
}
}
}
catch
{
MainBoard.WriteLine($"{Name} just lost bluetooth connection. Attempting to reconnect.", Color.Red);
pingTimer.Stop();
Dispose();
}
}
public override void SetLEDColor(Colors color)
{
// Nothing to do
}
public override void SetMotorSpeed(string port, int speed)
{
Port portObj = GetPortFromPortId(port);
// If we can't find the port, we can't do anything!
if (portObj == null)
{
MainBoard.WriteLine("Could not set Motor Speed to " + speed + " for " + Name + " because no default port are setup", Color.Red);
return;
}
portObj.Speed = speed;
IsBusy = (speed != 0);
OnDataUpdated();
WriteMessage(new byte[] { 0x01, (byte)portObj.Value, (byte)((speed > 0) ? 0 : 1), (byte)Math.Abs(portObj.Speed * 2.5) }, CharacteristicCommands);
}
public override void SetLightBrightness(string port, int brightness)
{
Port portObj = GetPortFromPortId(port);
// If we can't find the port, we can't do anything!
if (portObj == null)
{
MainBoard.WriteLine("Could not set Light Brightness for " + Name + " because no default port are setup", Color.Red);
return;
}
portObj.Speed = brightness;
WriteMessage(new byte[] { 0x01, (byte)portObj.Value, 1, (byte)(portObj.Speed * 2.5) }, CharacteristicCommands);
}
}
}
| 27.097561 | 220 | 0.635239 | [
"MIT"
] | Cosmik42/BAP | LTP.Core/Devices/SbrickHub.cs | 8,890 | C# |
using Aspose.Note.Live.Demos.UI.Models;
using Aspose.Note.Live.Demos.UI.Services;
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Web.Mvc;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
namespace Aspose.Note.Live.Demos.UI.Controllers
{
/// <summary>
/// Common API controller.
/// </summary>
public class CommonController : BaseController
{
public override string Product => (string)RouteData.Values["product"];
/// <summary>
/// Sends back specified file from specified folder inside OutputDirectory.
/// </summary>
/// <param name="folder">Folder inside OutputDirectory.</param>
/// <param name="file">File.</param>
/// <returns>HTTP response with file.</returns>
public FileResult DownloadFile(string file, string folder)
{
var pathProcessor = new PathProcessor(folder, file: file);
return File(pathProcessor.DefaultOutFile, "application/octet-stream", file);
}
[HttpPost]
public FileUploadResult UploadFile()
{
FileUploadResult uploadResult = null;
string fn = "";
try
{
string _folderID = Guid.NewGuid().ToString();
var pathProcessor = new PathProcessor(_folderID);
if (Request.Files.Count > 0)
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase postedFile = Request.Files[fileName];
fn = System.IO.Path.GetFileName(postedFile.FileName);
if (postedFile != null)
{
// Check if File is available.
if (postedFile != null && postedFile.ContentLength > 0)
{
postedFile.SaveAs(Path.Combine(pathProcessor.SourceFolder, fn));
}
}
}
}
return new FileUploadResult
{
FileName = fn,
FolderId = _folderID
};
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return uploadResult;
}
}
}
| 22.926829 | 79 | 0.667553 | [
"MIT"
] | alexeiso/Aspose.Note-for-.NET | Demos/src/Aspose.Note.Live.Demos.UI/Controllers/CommonController.cs | 1,880 | C# |
public class Solution {
public IList<IList<int>> LargeGroupPositions(string S) {
//two pointers
int s = 0;
var ans = new List<IList<int>>();
for(var e = 0; e < S.Length; ++e){
if(e == S.Length - 1 || S[e] != S[e+1]){
if(e-s > 1)
ans.Add(new List<int>(){s, e});
s = e+1;
}
}
return ans;
}
} | 28.066667 | 60 | 0.401425 | [
"MIT"
] | webigboss/Leetcode | 830. Positions of Large Groups/830_Original_Two_Pointers.cs | 421 | C# |
using Multiplayer;
using RAGE.Elements;
using RPServerClient.Client;
using RPServerClient.Util;
using Events = RAGE.Events;
namespace RPServerClient.Character
{
internal class CharCreator : Events.Script
{
private readonly Quaternion _displayPos = new Quaternion(-169.3321f, 482.2647f, 133.8789f, 282.6658f);
private readonly Quaternion _hiddenPos = new Quaternion(-163.4660f, 483.5910f, 134.5571f, 282.6658f);
private static CamHandler _camera;
public CharCreator()
{
_camera = new CamHandler();
// TEMP commands
Events.Add("createchar", OnInitCharCreation);
// Server Events
Events.Add(Shared.Events.ServerToClient.Character.StartCustomization, OnStartCustomization);
Events.Add(Shared.Events.ServerToClient.Character.ResetCharCreation, ResetCharCreation);
Events.Add(Shared.Events.ServerToClient.Character.DisplayCharError, DisplayError);
Events.Add(Shared.Events.ServerToClient.Character.SuccessCharCreation, OnSuccessCharCreation);
// CEF
Events.Add("SubmitInitialCharData", SubmitInitialCharData); // Step 1
Events.Add("UpdateHeadOverlay", OnUpdateHeadOverlay); // Step 2
Events.Add("UpdateFaceFeature", OnUpdateFaceFeature); // Step 3
Events.Add("UpdateExtras", OnUpdateExtras); // Step 4
Events.Add("UpdateHeadBlend", OnUpdateHeadBlend); // Step 5
Events.Add("SubmitNewCharacter", OnSubmitNewCharacter); // Step 5
Events.Add("SubmitCancel", OnQuitCharCreation);
}
private void OnSuccessCharCreation(object[] args)
{
BrowserHandler.ExecuteFunction(new object[] { "ShowStep", "7" });
}
private void ResetCharCreation(object[] args)
{
ResetAppearance(Player.LocalPlayer);
BrowserHandler.ExecuteFunction(new object[] { "ShowStep", "1" });
if (args != null && args.Length > 0) DisplayError(new object[] { args[0].ToString() });
}
#region InitilationDestruction
private void OnInitCharCreation(object[] args)
{
UnStageModel(Player.LocalPlayer);
ResetAppearance(Player.LocalPlayer);
BrowserHandler.CreateBrowser("package://CEF/char/charcreator.html");
_camera.SetPos(Helper.GetPosInFrontOfVector3(_displayPos.GetVector3Part(), _displayPos.W, 1.5f), _displayPos.GetVector3Part(), true);
}
private void OnQuitCharCreation(object[] args)
{
BrowserHandler.DestroyBrowser(null);
_camera.SetActive(false);
Events.CallRemote(Shared.Events.ClientToServer.Character.TriggerCharSelection);
}
private void OnSubmitNewCharacter(object[] args)
{
var dataAsJson = args[0].ToString();
Events.CallRemote(Shared.Events.ClientToServer.Character.SubmitNewCharacter, dataAsJson);
}
#endregion
#region LocalDisplayCustomization
private void SubmitInitialCharData(object[] args)
{
if (args == null || args.Length < 3)
return;
var firstname = args[0].ToString();
var lastname = args[1].ToString();
var isMale = (bool)args[2];
Player.LocalPlayer.Model = isMale ? (uint)1885233650 : 2627665880;
Events.CallRemote(Shared.Events.ClientToServer.Character.SubmitInitialCharData, firstname, lastname);
}
private void OnStartCustomization(object[] args)
{
StageModel(Player.LocalPlayer);
Events.CallRemote(Shared.Events.ClientToServer.Character.ApplyCharacterEditAnimation);
BrowserHandler.ExecuteFunction("ShowNextStep");
_camera.PointAtBone(Player.LocalPlayer, Shared.Enums.Bone.IK_Head, Player.LocalPlayer.GetHeading(), 0.35f, true);
// Set naked
if (Player.LocalPlayer.Model == 1885233650)
{ // male
Player.LocalPlayer.SetComponentVariation(1, 0, 0, 0);
Player.LocalPlayer.SetComponentVariation(3, 15, 0, 0);
Player.LocalPlayer.SetComponentVariation(4, 61, 0, 0);
Player.LocalPlayer.SetComponentVariation(6, 34, 0, 0);
Player.LocalPlayer.SetComponentVariation(8, 42, 4, 0);
Player.LocalPlayer.SetComponentVariation(11, 14, 20, 0);
}
else
{ // female
Player.LocalPlayer.SetComponentVariation(3, 15, 0, 0);
Player.LocalPlayer.SetComponentVariation(4, 17, 0, 0);
Player.LocalPlayer.SetComponentVariation(6, 35, 0, 0);
Player.LocalPlayer.SetComponentVariation(8, 2, 0, 0);
Player.LocalPlayer.SetComponentVariation(11, 5, 4, 0);
}
}
private void OnUpdateHeadBlend(object[] args)
{
if (args == null || args.Length < 6) return;
var shapeFirst = (int)args[0];
var shapeSecond = (int)args[1];
var skinFirst = (int)args[2];
var skinSecond = (int)args[3];
var shapeMix = (float)args[4];
var skinMix = (float)args[5];
Player.LocalPlayer.SetHeadBlendData(shapeFirst, shapeSecond, skinFirst, skinSecond, 0, 0, shapeMix, skinMix, 0, false);
}
private void OnUpdateFaceFeature(object[] args)
{
if (args == null || args.Length < 2) return;
var indx = int.Parse(args[0].ToString());
var value = float.Parse(args[1].ToString());
Player.LocalPlayer.SetFaceFeature(indx, value);
}
private void OnUpdateExtras(object[] args)
{
var Hairstyle = (int)args[0];
var HairColor = (int)args[1];
var HairHighlightColor = (int)args[2];
var HairStyleTexture = (int)args[3];
var EyeColor = (int)args[4];
Player.LocalPlayer.SetComponentVariation(2, Hairstyle, HairStyleTexture, 0);
Player.LocalPlayer.SetHairColor(HairColor, HairHighlightColor);
Player.LocalPlayer.SetEyeColor(EyeColor);
}
private void OnUpdateHeadOverlay(object[] args)
{
var indx = int.Parse(args[0].ToString());
var variation = int.Parse(args[1].ToString());
var opacity = float.Parse(args[2].ToString());
var color = int.Parse(args[3].ToString());
var secColor = int.Parse(args[4].ToString());
Player.LocalPlayer.SetHeadOverlay(indx, variation, opacity);
if (indx == 1 || indx == 2 || indx == 10)
Player.LocalPlayer.SetHeadOverlayColor(indx, 1, color, secColor);
else if (indx == 5 || indx == 8) Player.LocalPlayer.SetHeadOverlayColor(indx, 2, color, secColor);
}
#endregion
#region HelperMethods
private void ResetAppearance(Player player)
{
player.SetHeadBlendData(0, 0, 0, 0, 0, 0, 0, 0, 0, false);
for (var i = 0; i <= 12; i++) player.SetHeadOverlay(i, 0, 0);
for (var i = 0; i <= 19; i++) player.SetFaceFeature(i, 0);
player.SetDefaultComponentVariation();
player.SetHairColor(0, 0);
}
private void StageModel(Player p)
{
p.Position = _displayPos.GetVector3Part();
p.SetHeading(_displayPos.W);
}
private void UnStageModel(Player p)
{
p.Position = _hiddenPos.GetVector3Part();
}
private void DisplayError(object[] args)
{
if (args?[0] == null) return;
var msg = args[0] as string;
BrowserHandler.ExecuteFunction(new object[] { "showError", msg.Replace("'", @"\'") });
}
#endregion
}
}
| 39.068966 | 145 | 0.599546 | [
"MIT"
] | TryStatic/RPServer | RPServerClient/Character/CharCreator.cs | 7,931 | C# |
using RPGCore.Utility;
using System;
using UnityEngine;
namespace RPGCore.UI
{
[Serializable] public class UIPopupButtonPool : UIPool<UIPopupButton> { }
public class PopupMenu : MonoBehaviour
{
public static PopupMenu Instance;
public CanvasGroup Background;
public FadeBool BackgroundFade = new FadeBool ();
[Header ("Buttons")]
public GameObject Dialogue;
public RectTransform ButtonsHolder;
public UIPopupButtonPool ButtonPool;
private void Awake ()
{
Close ();
Instance = this;
}
private void Update ()
{
BackgroundFade.Update ();
Background.alpha = BackgroundFade.Value;
Background.blocksRaycasts = BackgroundFade.Target;
if (Input.GetKeyDown (KeyCode.Escape))
{
Close ();
}
}
public void Display (string header, params PopupButton[] buttons)
{
ButtonPool.Flush ();
BackgroundFade.Target = true;
for (int i = 0; i < buttons.Length; i++)
{
PopupButton button = buttons[i];
UIPopupButton uiButton = ButtonPool.Grab (ButtonsHolder);
uiButton.Setup (this, button);
}
Dialogue.SetActive (true);
}
public void Close ()
{
BackgroundFade.Target = false;
Dialogue.SetActive (false);
}
}
}
| 18.84375 | 74 | 0.688226 | [
"Apache-2.0"
] | li5414/RPGCore | RPGCore/Assets/RPGCore/Scripts/UI/Popup Menu/PopupMenu.cs | 1,208 | C# |
using System;
using Baseline.Conversion;
namespace Baseline
{
public class Date
{
public const string TimeFormat = "ddMMyyyy";
// This *has* to be here for serialization
public Date()
{
}
public Date(DateTime date)
: this(date.ToString(TimeFormat))
{
}
public Date(int month, int day, int year)
{
Day = new DateTime(year, month, day);
}
public Date(string ddmmyyyy)
{
Day = DateTime.ParseExact(ddmmyyyy, TimeFormat, null);
}
public DateTime Day { get; set; }
public Date NextDay()
{
return new Date(Day.AddDays(1));
}
public bool Equals(Date? other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other.Day.Equals(Day);
}
public override bool Equals(object? obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(Date)) return false;
return Equals((Date) obj);
}
public static bool operator ==(Date left, Date right)
{
return Equals(left, right);
}
public static bool operator !=(Date left, Date right)
{
return !Equals(left, right);
}
public override int GetHashCode()
{
return Day.GetHashCode();
}
public override string ToString()
{
return Day.ToString(TimeFormat);
}
public Date AddDays(int daysFromNow)
{
return new Date(Day.AddDays(daysFromNow));
}
public DateTime AtTime(TimeSpan time)
{
return Day.Date.Add(time);
}
public DateTime AtTime(string mmhh)
{
return Day.Date.Add(TimeSpanConverter.GetTimeSpan(mmhh));
}
public static Date Today()
{
return new Date(DateTime.Today);
}
}
} | 23.456522 | 69 | 0.519926 | [
"Apache-2.0"
] | JasperFx/Baseline | src/Baseline/Date.cs | 2,158 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using ILRuntime.CLR.TypeSystem;
using ILRuntime.CLR.Method;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.Runtime.Intepreter;
using ILRuntime.Runtime.Stack;
using ILRuntime.Reflection;
using ILRuntime.CLR.Utils;
namespace ILRuntime.Runtime.Generated
{
unsafe class System_Enum_Binding
{
public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)
{
BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodBase method;
Type[] args;
Type type = typeof(System.Enum);
args = new Type[]{typeof(System.Type)};
method = type.GetMethod("GetValues", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetValues_0);
args = new Type[]{typeof(System.Type)};
method = type.GetMethod("GetNames", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetNames_1);
args = new Type[]{typeof(System.Enum)};
method = type.GetMethod("HasFlag", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, HasFlag_2);
}
static StackObject* GetValues_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Type @enumType = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = System.Enum.GetValues(@enumType);
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* GetNames_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Type @enumType = (System.Type)typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = System.Enum.GetNames(@enumType);
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* HasFlag_2(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Enum @flag = (System.Enum)typeof(System.Enum).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Enum instance_of_this_method = (System.Enum)typeof(System.Enum).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.HasFlag(@flag);
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method ? 1 : 0;
return __ret + 1;
}
}
}
| 41.3125 | 159 | 0.682552 | [
"MIT"
] | 172672672/Confused_ILRuntime | ILRuntimeTest/AutoGenerate/System_Enum_Binding.cs | 3,966 | C# |
using System;
using Server;
namespace Server.Items
{
public class LyricalGlasses : ElvenGlasses
{
public override int LabelNumber{ get{ return 1073382; } } //Lyrical Reading Glasses
public override int BasePhysicalResistance{ get{ return 10; } }
public override int BaseFireResistance{ get{ return 10; } }
public override int BaseColdResistance{ get{ return 10; } }
public override int BasePoisonResistance{ get{ return 10; } }
public override int BaseEnergyResistance{ get{ return 10; } }
public override int InitMinHits{ get{ return 255; } }
public override int InitMaxHits{ get{ return 255; } }
[Constructable]
public LyricalGlasses()
{
WeaponAttributes.HitLowerDefend = 20;
Attributes.NightSight = 1;
Attributes.ReflectPhysical = 15;
Hue = 0x47F;
}
public LyricalGlasses( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 1 );
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize( reader );
int version = reader.ReadInt();
if ( version == 0 && Hue == 0 )
Hue = 0x47F;
}
}
}
| 24.5625 | 85 | 0.694656 | [
"BSD-2-Clause"
] | greeduomacro/vivre-uo | Scripts/Items/Armor/Glasses/LyricalGlasses.cs | 1,179 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.UI.Xaml.Controls.Maps
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
#endif
public partial class MapTileUriRequestedEventArgs
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public global::Windows.UI.Xaml.Controls.Maps.MapTileUriRequest Request
{
get
{
throw new global::System.NotImplementedException("The member MapTileUriRequest MapTileUriRequestedEventArgs.Request is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public int X
{
get
{
throw new global::System.NotImplementedException("The member int MapTileUriRequestedEventArgs.X is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public int Y
{
get
{
throw new global::System.NotImplementedException("The member int MapTileUriRequestedEventArgs.Y is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public int ZoomLevel
{
get
{
throw new global::System.NotImplementedException("The member int MapTileUriRequestedEventArgs.ZoomLevel is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public MapTileUriRequestedEventArgs()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Controls.Maps.MapTileUriRequestedEventArgs", "MapTileUriRequestedEventArgs.MapTileUriRequestedEventArgs()");
}
#endif
// Forced skipping of method Windows.UI.Xaml.Controls.Maps.MapTileUriRequestedEventArgs.MapTileUriRequestedEventArgs()
// Forced skipping of method Windows.UI.Xaml.Controls.Maps.MapTileUriRequestedEventArgs.X.get
// Forced skipping of method Windows.UI.Xaml.Controls.Maps.MapTileUriRequestedEventArgs.Y.get
// Forced skipping of method Windows.UI.Xaml.Controls.Maps.MapTileUriRequestedEventArgs.ZoomLevel.get
// Forced skipping of method Windows.UI.Xaml.Controls.Maps.MapTileUriRequestedEventArgs.Request.get
}
}
| 35.765625 | 202 | 0.754041 | [
"Apache-2.0"
] | nv-ksavaria/Uno | src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml.Controls.Maps/MapTileUriRequestedEventArgs.cs | 2,289 | C# |
//=============================================================================
//D ResourceHelper.cs
//
// ----------------------------------------------------------------------------
// Copyright 2019 Autodesk, Inc. All rights reserved.
//
// Use of this software is subject to the terms of the Autodesk license
// agreement provided at the time of installation or download, or which
// otherwise accompanies this software in either electronic or hard copy form.
// ----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
using System;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Drawing;
namespace Autodesk.PowerInspect.AddIns.SPC
{
/// <summary>
/// Helper class to retrieve information from .NET resources
/// </summary>
[ComVisible(false)]
public class ResourceHelper
{
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
//Used to delete HBITMAP object created in CreateHbitmapFromResource
//Deletion is essential
/// <summary>
/// Extracts an embedded resource as memory chunk
/// </summary>
/// <param name="path">Fully quilified resource path</param>
/// <param name="assembly">Assembly that holds the embeded resource</param>
/// <returns>Memory chunk or null if no resource found</returns>
public static Byte[] ExtractResource(string path, Assembly assembly)
{
try {
Stream res_stream = assembly.GetManifestResourceStream(path);
if (null == res_stream) {
return null;
}
BufferedStream reader = new BufferedStream(res_stream);
int buf_length = (int)reader.Length;
Byte[] image = new Byte[buf_length];
reader.Read(image, 0, buf_length);
reader.Close();
return image;
} catch (System.Exception e) {
Debug.Fail("Error occurred while extracting icons. " + e.Message);
return null;
}
}
///<summary>Loads a bitmap from .NET resource, creates and returns the handle of
///the bitmap, which must be destroyed by DeleteObject</summary>
///<param name="assembly">An assembly with a resource</param>
///<param name="resourceName">A full name of a resource</param>
public static IntPtr CreateHbitmapFromResource(string resourceName, Assembly assembly)
{
//Create HBITMAP from resources of .NET assembly
//It will be freed by IAddInManager.SetAddInInfo
Byte[] image = ExtractResource(resourceName, assembly);
if (image == null) {
return IntPtr.Zero;
}
MemoryStream stream = new MemoryStream(image);
Bitmap bmp = new Bitmap(stream);
return bmp.GetHbitmap();
}
}
}
| 36.922078 | 90 | 0.60394 | [
"Apache-2.0"
] | Autodesk/powerinspect-api-examples | SPCAddIn/SPC/Addin/ResourceHelper.cs | 2,845 | C# |
using System;
using OmniSharp.Extensions.JsonRpc;
// ReSharper disable once CheckNamespace
namespace OmniSharp.Extensions.LanguageServer.Protocol.Server
{
public interface ILanguageServerRegistry : IJsonRpcHandlerRegistry
{
IDisposable AddTextDocumentIdentifier(params ITextDocumentIdentifier[] handlers);
IDisposable AddTextDocumentIdentifier<T>() where T : ITextDocumentIdentifier;
}
}
| 32.076923 | 89 | 0.796163 | [
"MIT"
] | ToddGrun/csharp-language-server-protocol | src/Protocol/ILanguageServerRegistry.cs | 417 | C# |
using System;
using System.ComponentModel;
using CASCLib;
using WoWFormatLib.Utils;
namespace ADTH20Test
{
class Program
{
private static BackgroundWorkerEx cascworker = new BackgroundWorkerEx();
static void Main(string[] args)
{
cascworker.RunWorkerCompleted += CASCworker_RunWorkerCompleted;
cascworker.ProgressChanged += CASC_ProgressChanged;
cascworker.WorkerReportsProgress = true;
CASC.InitCasc(cascworker, "C:\\Program Files (x86)\\World of Warcraft", "wow");
ADTExporter.ExportADT(775971, 33, 32);
}
private static void CASC_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine((string)e.UserState);
}
private static void CASCworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine("Done initializing CASC!");
}
}
}
| 28.5 | 103 | 0.658411 | [
"MIT"
] | Marlamin/WoWFormatTest | ADTH20Test/Program.cs | 971 | C# |
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Alpaca.Markets
{
internal static partial class HttpClientExtensions
{
public static Task<TApi> PostAsync<TApi, TJson, TRequest>(
this HttpClient httpClient,
String endpointUri,
TRequest request,
CancellationToken cancellationToken)
where TJson : TApi =>
callAndDeserializeAsync<TApi, TJson, TRequest>(
httpClient, HttpMethod.Post, asUri(endpointUri), request, cancellationToken);
public static Task<TApi> PostAsync<TApi, TJson, TRequest>(
this HttpClient httpClient,
Uri endpointUri,
TRequest request,
CancellationToken cancellationToken)
where TJson : TApi =>
callAndDeserializeAsync<TApi, TJson, TRequest>(
httpClient, HttpMethod.Post, endpointUri, request, cancellationToken);
public static Task<TApi> PutAsync<TApi, TJson, TRequest>(
this HttpClient httpClient,
String endpointUri,
TRequest request,
CancellationToken cancellationToken)
where TJson : TApi =>
callAndDeserializeAsync<TApi, TJson, TRequest>(
httpClient, HttpMethod.Put, asUri(endpointUri), request, cancellationToken);
}
}
| 35.846154 | 93 | 0.639485 | [
"Apache-2.0"
] | gjtorikian/alpaca-trade-api-csharp | Alpaca.Markets/Helpers/HttpClientExtensions.Post.cs | 1,400 | C# |
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
namespace ConoHaNet.Objects.Networks
{
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
[JsonObject(MemberSerialization.OptIn)]
public class ListPortsResponse
{
[JsonProperty("ports", DefaultValueHandling = DefaultValueHandling.Include)]
public Port[] Ports { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class Port : ExtensibleJsonObject
{
[JsonProperty("id", DefaultValueHandling = DefaultValueHandling.Include)]
public string Id { get; set; }
[JsonProperty("name", DefaultValueHandling = DefaultValueHandling.Include)]
public string Name { get; set; }
[JsonProperty("status", DefaultValueHandling = DefaultValueHandling.Include)]
public string Status { get; set; }
[JsonProperty("bindinghost_id", DefaultValueHandling = DefaultValueHandling.Include)]
public string BindinghostId { get; set; }
[JsonProperty("allowed_address_pairs", DefaultValueHandling = DefaultValueHandling.Include)]
public AllowedAddressPair[] AllowedAddressPairs { get; set; }
[JsonProperty("extra_dhcp_opts", DefaultValueHandling = DefaultValueHandling.Include)]
public object[] ExtraDhcpOpts { get; set; }
[JsonProperty("device_owner", DefaultValueHandling = DefaultValueHandling.Include)]
public string DeviceOwner { get; set; }
[JsonProperty("bindingprofile", DefaultValueHandling = DefaultValueHandling.Include)]
public object[] BindingProfile { get; set; }
[JsonProperty("fixed_ips", DefaultValueHandling = DefaultValueHandling.Include)]
public FixedIp[] FixedIPs { get; set; }
[JsonProperty("security_groups", DefaultValueHandling = DefaultValueHandling.Include)]
public string[] SecurityGroups { get; set; }
[JsonProperty("device_id", DefaultValueHandling = DefaultValueHandling.Include)]
public string DeviceId { get; set; }
[JsonProperty("admin_state_up", DefaultValueHandling = DefaultValueHandling.Include)]
public bool? AdminStateUp { get; set; }
[JsonProperty("network_id", DefaultValueHandling = DefaultValueHandling.Include)]
public string NetworkId { get; set; }
[JsonProperty("tenant_id", DefaultValueHandling = DefaultValueHandling.Include)]
public string TenantId { get; set; }
[JsonProperty("bindingvif_details", DefaultValueHandling = DefaultValueHandling.Include)]
public BindingVIFDetails BindingVIFDetails { get; set; }
[JsonProperty("bindingvnic_type", DefaultValueHandling = DefaultValueHandling.Include)]
public string BindingVINCType { get; set; }
[JsonProperty("bindingvif_type", DefaultValueHandling = DefaultValueHandling.Include)]
public string BindingVIFType { get; set; }
[JsonProperty("mac_address", DefaultValueHandling = DefaultValueHandling.Include)]
public string MacAddress { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class BindingVIFDetails
{
[JsonProperty("port_filter", DefaultValueHandling = DefaultValueHandling.Include)]
public bool PortFilter { get; set; }
[JsonProperty("ovs_hybrid_plug", DefaultValueHandling = DefaultValueHandling.Include)]
public bool OvsHybridPlug { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class AllowedAddressPair : ExtensibleJsonObject
{
[JsonProperty("ip_address", DefaultValueHandling = DefaultValueHandling.Include)]
public string IpAddress { get; set; }
[JsonProperty("mac_address", DefaultValueHandling = DefaultValueHandling.Include)]
public string MacAddress { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class FixedIp : ExtensibleJsonObject
{
[JsonProperty("subnet_id", DefaultValueHandling = DefaultValueHandling.Include)]
public string SubnetId { get; set; }
[JsonProperty("ip_address", DefaultValueHandling = DefaultValueHandling.Include)]
public string IpAddress { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class CreatePortRequest
{
[JsonProperty("port", DefaultValueHandling = DefaultValueHandling.Include)]
public NewPort Port { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class NewPort : ExtensibleJsonObject
{
[JsonProperty("network_id", DefaultValueHandling = DefaultValueHandling.Include)]
public string NetworkId { get; set; }
[JsonProperty("fixed_ips", DefaultValueHandling = DefaultValueHandling.Include)]
public FixedIp[] FixedIPs { get; set; }
[JsonProperty("allowed_address_pairs", DefaultValueHandling = DefaultValueHandling.Include)]
public Dictionary<string, string> AllowedAddressPairs { get; set; }
[JsonProperty("tenant_id", DefaultValueHandling = DefaultValueHandling.Include)]
public string TenantId { get; set; }
[JsonProperty("security_groups", DefaultValueHandling = DefaultValueHandling.Include)]
public string[] SecurityGroups { get; set; }
[JsonProperty("status", DefaultValueHandling = DefaultValueHandling.Include)]
public string Status { get; set; }
public NewPort(string networkId, FixedIp[] fixedIps = null, Dictionary<string, string> allowedAddressPairs = null, string tenantId = null, string[] securityGroups = null, string status = null)
{
this.NetworkId = networkId;
this.FixedIPs = fixedIps;
this.AllowedAddressPairs = allowedAddressPairs;
this.TenantId = tenantId;
this.SecurityGroups = securityGroups;
this.Status = status;
}
}
[JsonObject(MemberSerialization.OptIn)]
public class UpdatePortRequest
{
[JsonProperty("port", DefaultValueHandling = DefaultValueHandling.Include)]
public Port Port { get; set; }
public UpdatePortRequest(string portId, bool? adminStateUp = null, string[] securityGroups = null, FixedIp[] fixedIps = null, AllowedAddressPair[] allowedAddressPairs = null)
{
this.Port = new Port()
{
AdminStateUp = adminStateUp,
SecurityGroups = securityGroups,
FixedIPs = fixedIps,
AllowedAddressPairs = allowedAddressPairs
};
}
}
[JsonObject(MemberSerialization.OptIn)]
public class GetPortResponse
{
[JsonProperty("port", DefaultValueHandling = DefaultValueHandling.Include)]
public Port Port { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class CreatePortResponse
{
[JsonProperty("port", DefaultValueHandling = DefaultValueHandling.Include)]
public Port Port { get; set; }
}
}
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member | 40.369318 | 200 | 0.689937 | [
"MIT"
] | crowdy/OpenStack-ConoHa | ConoHaNet/Objects/Networks/Ports.cs | 7,107 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801
{
using Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.PowerShell;
/// <summary>User credentials used for publishing activity.</summary>
[System.ComponentModel.TypeConverter(typeof(DeploymentTypeConverter))]
public partial class Deployment
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the 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="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the 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="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the 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="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the 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="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.Deployment"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal Deployment(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
if (content.Contains("Property"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.DeploymentPropertiesTypeConverter.ConvertFrom);
}
if (content.Contains("Id"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Id, global::System.Convert.ToString);
}
if (content.Contains("Name"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Name, global::System.Convert.ToString);
}
if (content.Contains("Kind"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Kind = (string) content.GetValueForProperty("Kind",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Kind, global::System.Convert.ToString);
}
if (content.Contains("Type"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Type, global::System.Convert.ToString);
}
if (content.Contains("Status"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Status = (int?) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Status, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int)));
}
if (content.Contains("Message"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Message, global::System.Convert.ToString);
}
if (content.Contains("Author"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Author = (string) content.GetValueForProperty("Author",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Author, global::System.Convert.ToString);
}
if (content.Contains("Deployer"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Deployer = (string) content.GetValueForProperty("Deployer",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Deployer, global::System.Convert.ToString);
}
if (content.Contains("AuthorEmail"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).AuthorEmail = (string) content.GetValueForProperty("AuthorEmail",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).AuthorEmail, global::System.Convert.ToString);
}
if (content.Contains("StartTime"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
}
if (content.Contains("EndTime"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).EndTime = (global::System.DateTime?) content.GetValueForProperty("EndTime",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).EndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
}
if (content.Contains("Active"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Active = (bool?) content.GetValueForProperty("Active",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Active, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("Detail"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Detail = (string) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Detail, global::System.Convert.ToString);
}
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.Deployment"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal Deployment(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
if (content.Contains("Property"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.DeploymentPropertiesTypeConverter.ConvertFrom);
}
if (content.Contains("Id"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Id, global::System.Convert.ToString);
}
if (content.Contains("Name"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Name, global::System.Convert.ToString);
}
if (content.Contains("Kind"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Kind = (string) content.GetValueForProperty("Kind",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Kind, global::System.Convert.ToString);
}
if (content.Contains("Type"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Type, global::System.Convert.ToString);
}
if (content.Contains("Status"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Status = (int?) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Status, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int)));
}
if (content.Contains("Message"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Message, global::System.Convert.ToString);
}
if (content.Contains("Author"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Author = (string) content.GetValueForProperty("Author",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Author, global::System.Convert.ToString);
}
if (content.Contains("Deployer"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Deployer = (string) content.GetValueForProperty("Deployer",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Deployer, global::System.Convert.ToString);
}
if (content.Contains("AuthorEmail"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).AuthorEmail = (string) content.GetValueForProperty("AuthorEmail",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).AuthorEmail, global::System.Convert.ToString);
}
if (content.Contains("StartTime"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
}
if (content.Contains("EndTime"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).EndTime = (global::System.DateTime?) content.GetValueForProperty("EndTime",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).EndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
}
if (content.Contains("Active"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Active = (bool?) content.GetValueForProperty("Active",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Active, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("Detail"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Detail = (string) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeploymentInternal)this).Detail, global::System.Convert.ToString);
}
AfterDeserializePSObject(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.Deployment"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeployment" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeployment DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new Deployment(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.Deployment"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeployment" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeployment DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new Deployment(content);
}
/// <summary>
/// Creates a new instance of <see cref="Deployment" />, deserializing the content from a json string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="className" /> model class.</returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDeployment FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// User credentials used for publishing activity.
[System.ComponentModel.TypeConverter(typeof(DeploymentTypeConverter))]
public partial interface IDeployment
{
}
} | 78.219512 | 460 | 0.693535 | [
"MIT"
] | Agazoth/azure-powershell | src/Functions/generated/api/Models/Api20190801/Deployment.PowerShell.cs | 18,997 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.