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 |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Runtime.InteropServices;
#if NET4
namespace System.Runtime.CompilerServices
{
[StructLayout(LayoutKind.Sequential, Size = 1)]
internal struct VoidTaskResult
{
}
}
#endif | 16.75 | 48 | 0.78607 | [
"MIT"
] | 19900623/X | NewLife.Core/Threading/VoidTaskResult.cs | 201 | C# |
using System.Drawing;
using ArtrointelPlugin.Utils;
namespace ArtrointelPlugin.SDGraphics.Renderer.AnimatedEffects
{
/// <summary>
/// Flashes with input color with animated alpha value.
/// </summary>
class FlashRenderer : CanvasRendererBase, IAnimatableRenderer
{
// input data
private readonly Color mInputColor;
private readonly double mDelayInSecond;
private readonly int mInputDurationInMillisecond;
// for internal logic
private ValueAnimator mFlashStartAnimator;
private ValueAnimator mFlashEndAnimator;
private Color mAnimFlashColor;
private DelayedTask mDelayedTask;
/// <summary>
/// Flash with the color. alpha value will be used for brightest moment.
/// </summary>
/// <param name="color"></param>
public FlashRenderer(Color color, double delayInSecond, double durationInSecond)
{
mInputColor = color;
mDelayInSecond = delayInSecond;
mInputDurationInMillisecond = (int)(durationInSecond * 1000);
initialize();
}
private void initialize()
{
int flashStartDuration = (int)(mInputDurationInMillisecond * 0.25);
int flashEndDuration = (int)(mInputDurationInMillisecond * 0.75);
mFlashStartAnimator = new ValueAnimator(0, 1, flashStartDuration, ValueAnimator.INTERVAL_60_PER_SEC);
mFlashEndAnimator = new ValueAnimator(1, 0, flashEndDuration, ValueAnimator.INTERVAL_60_PER_SEC);
mFlashStartAnimator.setAnimationListeners((value, duration) => {
mAnimFlashColor = Color.FromArgb((int)(mInputColor.A * value), mInputColor);
invalidate();
},
() =>
{
mFlashEndAnimator.start();
});
mFlashEndAnimator.setAnimationListeners((value, duration) =>
{
mAnimFlashColor = Color.FromArgb((int)(mInputColor.A * value), mInputColor);
invalidate();
});
}
public override void onRender(Graphics graphics)
{
graphics.Clear(mAnimFlashColor);
base.onRender(graphics);
}
public void animate(bool restart)
{
if (mDelayInSecond > 0)
{
if (mDelayedTask != null)
{
mDelayedTask.cancel();
}
mDelayedTask = new DelayedTask((int)(mDelayInSecond * 1000), () =>
{
mFlashEndAnimator.stop();
mFlashStartAnimator.start(restart);
});
}
else
{
mFlashEndAnimator.stop();
mFlashStartAnimator.start(restart);
}
}
public void pause()
{
// do nothing. it is more natural that not pausing the flash animation.
}
public override void onDestroy()
{
if (mDelayedTask != null)
{
mDelayedTask.cancel();
}
mFlashEndAnimator.destroy();
mFlashStartAnimator.destroy();
base.onDestroy();
}
}
}
| 32.564356 | 113 | 0.555488 | [
"MIT"
] | artrointel/streamdeck-avengers | ArtrointelPlugin/SDGraphics/Renderer/AnimatedEffects/FlashRenderer.cs | 3,291 | C# |
using System;
using Exiled.API.Features;
using Exiled.API.Enums;
using ServerHandler = Exiled.Events.Handlers.Server;
using PlayerHandler = Exiled.Events.Handlers.Player;
namespace MegaUtils
{
public class MegaUtils : Plugin<Config>
{
public static MegaUtils instance;
private EventHandler ev { get; set; }
public override string Name => "MegaUtils";
public override string Author { get; } = "AtomSnow";
public override Version RequiredExiledVersion { get; } = new Version(3, 0, 0);
public override string Prefix { get; } = "MegaUtils";
public override Version Version { get; } = new Version(0, 1, 2);
public override PluginPriority Priority { get; } = PluginPriority.First;
public override void OnEnabled()
{
instance = this;
ev = new EventHandler();
ServerHandler.WaitingForPlayers += ev.OnWaitingForPlayers;
ServerHandler.RoundEnded += ev.OnRoundEnded;
base.OnEnabled();
}
public override void OnDisabled()
{
ServerHandler.WaitingForPlayers -= ev.OnWaitingForPlayers;
ServerHandler.RoundEnded -= ev.OnRoundEnded;
ev = null;
base.OnDisabled();
}
}
}
| 23.979167 | 86 | 0.701129 | [
"MIT"
] | AtomSnow/MegaUtils | MegaUtils/Plugin.cs | 1,151 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** 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.AzureNative.Network.V20160601
{
/// <summary>
/// ExpressRouteCircuit resource
/// </summary>
[AzureNativeResourceType("azure-native:network/v20160601:ExpressRouteCircuit")]
public partial class ExpressRouteCircuit : Pulumi.CustomResource
{
/// <summary>
/// allow classic operations
/// </summary>
[Output("allowClassicOperations")]
public Output<bool?> AllowClassicOperations { get; private set; } = null!;
/// <summary>
/// Gets or sets list of authorizations
/// </summary>
[Output("authorizations")]
public Output<ImmutableArray<Outputs.ExpressRouteCircuitAuthorizationResponse>> Authorizations { get; private set; } = null!;
/// <summary>
/// Gets or sets CircuitProvisioningState state of the resource
/// </summary>
[Output("circuitProvisioningState")]
public Output<string?> CircuitProvisioningState { get; private set; } = null!;
/// <summary>
/// Gets a unique read-only string that changes whenever the resource is updated
/// </summary>
[Output("etag")]
public Output<string?> Etag { get; private set; } = null!;
/// <summary>
/// Gets or sets the GatewayManager Etag
/// </summary>
[Output("gatewayManagerEtag")]
public Output<string?> GatewayManagerEtag { get; private set; } = null!;
/// <summary>
/// Resource location
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// Resource name
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Gets or sets list of peerings
/// </summary>
[Output("peerings")]
public Output<ImmutableArray<Outputs.ExpressRouteCircuitPeeringResponse>> Peerings { get; private set; } = null!;
/// <summary>
/// Gets provisioning state of the PublicIP resource Updating/Deleting/Failed
/// </summary>
[Output("provisioningState")]
public Output<string?> ProvisioningState { get; private set; } = null!;
/// <summary>
/// Gets or sets ServiceKey
/// </summary>
[Output("serviceKey")]
public Output<string?> ServiceKey { get; private set; } = null!;
/// <summary>
/// Gets or sets ServiceProviderNotes
/// </summary>
[Output("serviceProviderNotes")]
public Output<string?> ServiceProviderNotes { get; private set; } = null!;
/// <summary>
/// Gets or sets ServiceProviderProperties
/// </summary>
[Output("serviceProviderProperties")]
public Output<Outputs.ExpressRouteCircuitServiceProviderPropertiesResponse?> ServiceProviderProperties { get; private set; } = null!;
/// <summary>
/// Gets or sets ServiceProviderProvisioningState state of the resource
/// </summary>
[Output("serviceProviderProvisioningState")]
public Output<string?> ServiceProviderProvisioningState { get; private set; } = null!;
/// <summary>
/// Gets or sets sku
/// </summary>
[Output("sku")]
public Output<Outputs.ExpressRouteCircuitSkuResponse?> Sku { get; private set; } = null!;
/// <summary>
/// Resource tags
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Resource type
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a ExpressRouteCircuit resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public ExpressRouteCircuit(string name, ExpressRouteCircuitArgs args, CustomResourceOptions? options = null)
: base("azure-native:network/v20160601:ExpressRouteCircuit", name, args ?? new ExpressRouteCircuitArgs(), MakeResourceOptions(options, ""))
{
}
private ExpressRouteCircuit(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:network/v20160601:ExpressRouteCircuit", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:network/v20160601:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20150501preview:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20150501preview:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20150615:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20150615:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20160330:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20160330:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20160901:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20160901:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20161201:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20161201:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20170301:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170301:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20170601:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170601:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20170801:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170801:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20170901:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170901:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20171001:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20171001:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20171101:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20171101:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20180101:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180101:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20180201:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180201:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20180401:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180401:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20180601:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180601:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20180701:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180701:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20180801:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20181001:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20181101:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20181201:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20190201:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20190401:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20190601:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20190701:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20190801:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20190901:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20191101:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20191201:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20200301:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20200401:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20200501:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20200601:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20200701:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20200801:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20201101:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20201101:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20210201:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20210201:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-native:network/v20210301:ExpressRouteCircuit"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20210301:ExpressRouteCircuit"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing ExpressRouteCircuit resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static ExpressRouteCircuit Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new ExpressRouteCircuit(name, id, options);
}
}
public sealed class ExpressRouteCircuitArgs : Pulumi.ResourceArgs
{
/// <summary>
/// allow classic operations
/// </summary>
[Input("allowClassicOperations")]
public Input<bool>? AllowClassicOperations { get; set; }
[Input("authorizations")]
private InputList<Inputs.ExpressRouteCircuitAuthorizationArgs>? _authorizations;
/// <summary>
/// Gets or sets list of authorizations
/// </summary>
public InputList<Inputs.ExpressRouteCircuitAuthorizationArgs> Authorizations
{
get => _authorizations ?? (_authorizations = new InputList<Inputs.ExpressRouteCircuitAuthorizationArgs>());
set => _authorizations = value;
}
/// <summary>
/// The name of the circuit.
/// </summary>
[Input("circuitName")]
public Input<string>? CircuitName { get; set; }
/// <summary>
/// Gets or sets CircuitProvisioningState state of the resource
/// </summary>
[Input("circuitProvisioningState")]
public Input<string>? CircuitProvisioningState { get; set; }
/// <summary>
/// Gets a unique read-only string that changes whenever the resource is updated
/// </summary>
[Input("etag")]
public Input<string>? Etag { get; set; }
/// <summary>
/// Gets or sets the GatewayManager Etag
/// </summary>
[Input("gatewayManagerEtag")]
public Input<string>? GatewayManagerEtag { get; set; }
/// <summary>
/// Resource Id
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// Resource location
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
[Input("peerings")]
private InputList<Inputs.ExpressRouteCircuitPeeringArgs>? _peerings;
/// <summary>
/// Gets or sets list of peerings
/// </summary>
public InputList<Inputs.ExpressRouteCircuitPeeringArgs> Peerings
{
get => _peerings ?? (_peerings = new InputList<Inputs.ExpressRouteCircuitPeeringArgs>());
set => _peerings = value;
}
/// <summary>
/// Gets provisioning state of the PublicIP resource Updating/Deleting/Failed
/// </summary>
[Input("provisioningState")]
public Input<string>? ProvisioningState { get; set; }
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// Gets or sets ServiceKey
/// </summary>
[Input("serviceKey")]
public Input<string>? ServiceKey { get; set; }
/// <summary>
/// Gets or sets ServiceProviderNotes
/// </summary>
[Input("serviceProviderNotes")]
public Input<string>? ServiceProviderNotes { get; set; }
/// <summary>
/// Gets or sets ServiceProviderProperties
/// </summary>
[Input("serviceProviderProperties")]
public Input<Inputs.ExpressRouteCircuitServiceProviderPropertiesArgs>? ServiceProviderProperties { get; set; }
/// <summary>
/// Gets or sets ServiceProviderProvisioningState state of the resource
/// </summary>
[Input("serviceProviderProvisioningState")]
public InputUnion<string, Pulumi.AzureNative.Network.V20160601.ServiceProviderProvisioningState>? ServiceProviderProvisioningState { get; set; }
/// <summary>
/// Gets or sets sku
/// </summary>
[Input("sku")]
public Input<Inputs.ExpressRouteCircuitSkuArgs>? Sku { get; set; }
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Resource tags
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public ExpressRouteCircuitArgs()
{
}
}
}
| 50.379121 | 152 | 0.612117 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/V20160601/ExpressRouteCircuit.cs | 18,338 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Codice.Client.BaseCommands;
using Codice.Client.BaseCommands.EventTracking;
using Codice.CM.Common;
using GluonGui.WorkspaceWindow.Views.Checkin.Operations;
using PlasticGui;
using Unity.PlasticSCM.Editor.AssetUtils;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.Views.PendingChanges.Dialogs;
namespace Unity.PlasticSCM.Editor.Views.PendingChanges
{
internal partial class PendingChangesTab
{
void CheckinForMode(WorkspaceInfo wkInfo, bool isGluonMode, bool keepItemsLocked)
{
TrackFeatureUseEvent.For(
PlasticGui.Plastic.API.GetRepositorySpec(wkInfo),
isGluonMode ?
TrackFeatureUseEvent.Features.PartialCheckin :
TrackFeatureUseEvent.Features.Checkin);
if (isGluonMode)
{
PartialCheckin(keepItemsLocked);
return;
}
Checkin();
}
internal void UndoForMode(WorkspaceInfo wkInfo, bool isGluonMode)
{
TrackFeatureUseEvent.For(
PlasticGui.Plastic.API.GetRepositorySpec(wkInfo),
isGluonMode ?
TrackFeatureUseEvent.Features.PartialUndo :
TrackFeatureUseEvent.Features.Undo);
if (isGluonMode)
{
PartialUndo();
return;
}
Undo();
}
void UndoChangesForMode(
bool isGluonMode,
List<ChangeInfo> changesToUndo,
List<ChangeInfo> dependenciesCandidates)
{
if (isGluonMode)
{
PartialUndoChanges(changesToUndo, dependenciesCandidates);
return;
}
UndoChanges(changesToUndo, dependenciesCandidates);
}
void PartialCheckin(bool keepItemsLocked)
{
List<ChangeInfo> changesToCheckin;
List<ChangeInfo> dependenciesCandidates;
mPendingChangesTreeView.GetCheckedChanges(
false,
out changesToCheckin,
out dependenciesCandidates);
if (CheckEmptyOperation(changesToCheckin))
{
((IProgressControls)mProgressControls).ShowWarning(
PlasticLocalization.GetString(PlasticLocalization.Name.NoItemsAreSelected));
return;
}
bool isCancelled;
SaveAssets.ForChangesWithConfirmation(changesToCheckin, out isCancelled);
if (isCancelled)
return;
CheckinUIOperation ciOperation = new CheckinUIOperation(
mWkInfo, mViewHost, mProgressControls, mGuiMessage,
new LaunchCheckinConflictsDialog(mParentWindow),
new LaunchDependenciesDialog(
PlasticLocalization.GetString(PlasticLocalization.Name.CheckinButton),
mParentWindow),
this, mWorkspaceWindow.GluonProgressOperationHandler);
ciOperation.Checkin(
changesToCheckin,
dependenciesCandidates,
CommentText,
keepItemsLocked,
EndCheckin);
}
void Checkin()
{
List<ChangeInfo> changesToCheckin;
List<ChangeInfo> dependenciesCandidates;
mPendingChangesTreeView.GetCheckedChanges(
false, out changesToCheckin, out dependenciesCandidates);
if (CheckEmptyOperation(changesToCheckin, HasPendingMergeLinks()))
{
((IProgressControls)mProgressControls).ShowWarning(
PlasticLocalization.GetString(PlasticLocalization.Name.NoItemsAreSelected));
return;
}
bool isCancelled;
SaveAssets.ForChangesWithConfirmation(changesToCheckin, out isCancelled);
if (isCancelled)
return;
mPendingChangesOperations.Checkin(
changesToCheckin,
dependenciesCandidates,
CommentText,
null,
EndCheckin,
null);
}
void PartialUndo()
{
List<ChangeInfo> changesToUndo;
List<ChangeInfo> dependenciesCandidates;
mPendingChangesTreeView.GetCheckedChanges(
true, out changesToUndo, out dependenciesCandidates);
PartialUndoChanges(changesToUndo, dependenciesCandidates);
}
void Undo()
{
List<ChangeInfo> changesToUndo;
List<ChangeInfo> dependenciesCandidates;
mPendingChangesTreeView.GetCheckedChanges(
true, out changesToUndo, out dependenciesCandidates);
UndoChanges(changesToUndo, dependenciesCandidates);
}
void PartialUndoChanges(
List<ChangeInfo> changesToUndo,
List<ChangeInfo> dependenciesCandidates)
{
if (CheckEmptyOperation(changesToUndo))
{
((IProgressControls)mProgressControls).ShowWarning(
PlasticLocalization.GetString(PlasticLocalization.Name.NoItemsToUndo));
return;
}
SaveAssets.ForChangesWithoutConfirmation(changesToUndo);
UndoUIOperation undoOperation = new UndoUIOperation(
mWkInfo, mViewHost,
new LaunchDependenciesDialog(
PlasticLocalization.GetString(PlasticLocalization.Name.UndoButton),
mParentWindow),
mProgressControls, mGuiMessage);
undoOperation.Undo(
changesToUndo,
dependenciesCandidates,
RefreshAsset.UnityAssetDatabase);
}
void UndoChanges(
List<ChangeInfo> changesToUndo,
List<ChangeInfo> dependenciesCandidates)
{
if (CheckEmptyOperation(changesToUndo, HasPendingMergeLinks()))
{
((IProgressControls)mProgressControls).ShowWarning(
PlasticLocalization.GetString(PlasticLocalization.Name.NoItemsToUndo));
return;
}
SaveAssets.ForChangesWithoutConfirmation(changesToUndo);
mPendingChangesOperations.Undo(
changesToUndo,
dependenciesCandidates,
mPendingMergeLinks.Count,
RefreshAsset.UnityAssetDatabase,
null);
}
void EndCheckin()
{
ShowCheckinSuccess();
RefreshAsset.UnityAssetDatabase();
}
void ShowCheckinSuccess()
{
bool isTreeViewEmpty = mPendingChangesTreeView.GetCheckedItemCount() ==
mPendingChangesTreeView.GetTotalItemCount();
if (isTreeViewEmpty)
{
mIsCheckedInSuccessful = true;
mCooldownClearCheckinSuccessAction.Ping();
return;
}
mStatusBar.Notify(
PlasticLocalization.GetString(PlasticLocalization.Name.CheckinCompleted),
UnityEditor.MessageType.None,
Images.Name.StepOk);
}
void DelayedClearCheckinSuccess()
{
mIsCheckedInSuccessful = false;
}
static bool CheckEmptyOperation(List<ChangeInfo> elements)
{
return elements == null || elements.Count == 0;
}
static bool CheckEmptyOperation(List<ChangeInfo> elements, bool bHasPendingMergeLinks)
{
if (bHasPendingMergeLinks)
return false;
if (elements != null && elements.Count > 0)
return false;
return true;
}
}
}
| 31.8 | 96 | 0.580503 | [
"Apache-2.0"
] | ASlugin/Homework-2sem | SCP-087/Library/PackageCache/com.unity.collab-proxy@1.15.16/Editor/PlasticSCM/Views/PendingChanges/PendingChangesTab_Operations.cs | 7,952 | C# |
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace SyncTrayzor.Services
{
public interface IUserActivityMonitor
{
bool IsWindowFullscreen();
}
// Taken from http://www.richard-banks.org/2007/09/how-to-detect-if-another-application-is.html
public class UserActivityMonitor : IUserActivityMonitor
{
private readonly IntPtr desktopHandle;
private readonly IntPtr shellHandle;
public UserActivityMonitor()
{
this.desktopHandle = NativeMethods.GetDesktopWindow();
this.shellHandle = NativeMethods.GetShellWindow();
}
public bool IsWindowFullscreen()
{
bool runningFullScreen = false;
//get the dimensions of the active window
var hWnd = NativeMethods.GetForegroundWindow();
if (hWnd != null && !hWnd.Equals(IntPtr.Zero))
{
//Check we haven't picked up the desktop or the shell
if (!(hWnd.Equals(desktopHandle) || hWnd.Equals(shellHandle)))
{
NativeMethods.GetWindowRect(hWnd, out RECT appBounds);
//determine if window is fullscreen
// TODO: Not sure if there's a nice non-winforms way of doing this
var screenBounds = Screen.FromHandle(hWnd).Bounds;
if ((appBounds.Bottom - appBounds.Top) == screenBounds.Height && (appBounds.Right - appBounds.Left) == screenBounds.Width)
{
runningFullScreen = true;
}
}
}
return runningFullScreen;
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
private class NativeMethods
{
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetShellWindow();
[DllImport("user32.dll", SetLastError = true)]
public static extern int GetWindowRect(IntPtr hwnd, out RECT rc);
}
}
}
| 35.056338 | 143 | 0.557654 | [
"MIT"
] | Bararie/SyncTrayzor | src/SyncTrayzor/Services/UserActivityMonitor.cs | 2,421 | C# |
using ProtoBuf;
namespace ThreeKingdoms
{
[ProtoContract]
public class CTS_L_LotteryConfigMsg
{
/// <summary>
///
/// </summary>
[ProtoMember(1)]
public long userId { get; set; }
}
}
| 15.125 | 40 | 0.533058 | [
"MIT"
] | liuruoyu1981/IukerTech | IukerTech_ThreeKingdoms/CSharp/.BackProtobuf/CTS_L_LotteryConfigMsg.cs | 242 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Innofactor.EfCoreJsonValueConverter;
using our.orders.Helpers;
namespace our.orders.Models
{
public class ProductOption
{
public string Title { get; set; }
public string Id { get; set; }
public string SKU { get; set; }
public string Src { get; set; }
[JsonField]
public IEnumerable<Price> BasePrice
{ get; set; }
}
} | 21.73913 | 51 | 0.658 | [
"MIT"
] | Our-Company-Ltd/our.orders | core/lib/Models/ProductOption.cs | 500 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace AutoRest.Java.Azure.Fluent.Model
{
public interface IFluentModel
{
ISegmentFluentMethodGroup FluentMethodGroup { get; }
ModelLocalProperties ModelLocalProperties { get; }
string JavaClassName { get; }
string JavaInterfaceName { get; }
string InnerModelName { get; }
WrapExistingModelFunc WrapExistingModelFunc { get; }
}
}
| 34.5 | 95 | 0.708333 | [
"MIT"
] | MariusVolkhart/autorest.java | src/azurefluent/Model/FluentCommon/Model/IFluentModel.cs | 554 | C# |
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using HandyControl.Data;
using HandyControl.Interactivity;
using HandyControl.Properties.Langs;
namespace HandyControl.Controls
{
[TemplatePart(Name = ElementPasswordBox, Type = typeof(System.Windows.Controls.PasswordBox))]
[TemplatePart(Name = ElementTextBox, Type = typeof(System.Windows.Controls.TextBox))]
public class PasswordBox : Control, IDataInput
{
private const string ElementPasswordBox = "PART_PasswordBox";
private const string ElementTextBox = "PART_TextBox";
private SecureString _password;
private System.Windows.Controls.TextBox _textBox;
/// <summary>
/// 掩码字符
/// </summary>
public static readonly DependencyProperty PasswordCharProperty =
System.Windows.Controls.PasswordBox.PasswordCharProperty.AddOwner(typeof(PasswordBox),
new FrameworkPropertyMetadata('●'));
public char PasswordChar
{
get => (char) GetValue(PasswordCharProperty);
set => SetValue(PasswordCharProperty, value);
}
/// <summary>
/// 数据是否错误
/// </summary>
public static readonly DependencyProperty IsErrorProperty = DependencyProperty.Register(
"IsError", typeof(bool), typeof(PasswordBox), new PropertyMetadata(ValueBoxes.FalseBox));
public bool IsError
{
get => (bool) GetValue(IsErrorProperty);
set => SetValue(IsErrorProperty, ValueBoxes.BooleanBox(value));
}
/// <summary>
/// 错误提示
/// </summary>
public static readonly DependencyProperty ErrorStrProperty = DependencyProperty.Register(
"ErrorStr", typeof(string), typeof(PasswordBox), new PropertyMetadata(default(string)));
public string ErrorStr
{
get => (string) GetValue(ErrorStrProperty);
set => SetValue(ErrorStrProperty, value);
}
/// <summary>
/// 文本类型
/// </summary>
public static readonly DependencyProperty TextTypeProperty = DependencyProperty.Register(
"TextType", typeof(TextType), typeof(PasswordBox), new PropertyMetadata(default(TextType)));
public TextType TextType
{
get => (TextType) GetValue(TextTypeProperty);
set => SetValue(TextTypeProperty, value);
}
/// <summary>
/// 是否显示清除按钮
/// </summary>
public static readonly DependencyProperty ShowClearButtonProperty = DependencyProperty.Register(
"ShowClearButton", typeof(bool), typeof(PasswordBox), new PropertyMetadata(ValueBoxes.FalseBox));
public bool ShowClearButton
{
get => (bool) GetValue(ShowClearButtonProperty);
set => SetValue(ShowClearButtonProperty, ValueBoxes.BooleanBox(value));
}
public static readonly DependencyProperty ShowEyeButtonProperty = DependencyProperty.Register(
"ShowEyeButton", typeof(bool), typeof(PasswordBox), new PropertyMetadata(ValueBoxes.FalseBox));
public bool ShowEyeButton
{
get => (bool) GetValue(ShowEyeButtonProperty);
set => SetValue(ShowEyeButtonProperty, ValueBoxes.BooleanBox(value));
}
public static readonly DependencyProperty ShowPasswordProperty = DependencyProperty.Register(
"ShowPassword", typeof(bool), typeof(PasswordBox),
new PropertyMetadata(ValueBoxes.FalseBox, OnShowPasswordChanged));
public bool ShowPassword
{
get => (bool) GetValue(ShowPasswordProperty);
set => SetValue(ShowPasswordProperty, ValueBoxes.BooleanBox(value));
}
public static readonly DependencyProperty IsSafeEnabledProperty = DependencyProperty.Register(
"IsSafeEnabled", typeof(bool), typeof(PasswordBox), new PropertyMetadata(ValueBoxes.TrueBox, OnIsSafeEnabledChanged));
private static void OnIsSafeEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var p = (PasswordBox) d;
p.SetCurrentValue(UnsafePasswordProperty, !(bool) e.NewValue ? p.Password : string.Empty);
}
public bool IsSafeEnabled
{
get => (bool) GetValue(IsSafeEnabledProperty);
set => SetValue(IsSafeEnabledProperty, ValueBoxes.BooleanBox(value));
}
public static readonly DependencyProperty UnsafePasswordProperty = DependencyProperty.Register(
"UnsafePassword", typeof(string), typeof(PasswordBox), new FrameworkPropertyMetadata(default(string),
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnUnsafePasswordChanged));
private static void OnUnsafePasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var p = (PasswordBox) d;
if (!p.IsSafeEnabled)
{
p.Password = e.NewValue != null ? e.NewValue.ToString() : string.Empty;
}
}
public string UnsafePassword
{
get => (string) GetValue(UnsafePasswordProperty);
set => SetValue(UnsafePasswordProperty, value);
}
public static readonly DependencyProperty MaxLengthProperty =
System.Windows.Controls.TextBox.MaxLengthProperty.AddOwner(typeof(PasswordBox));
public int MaxLength
{
get => (int) GetValue(MaxLengthProperty);
set => SetValue(MaxLengthProperty, value);
}
public static readonly DependencyProperty SelectionBrushProperty =
TextBoxBase.SelectionBrushProperty.AddOwner(typeof(PasswordBox));
public Brush SelectionBrush
{
get => (Brush) GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
#if !(NET40 || NET45 || NET451 || NET452 || NET46 || NET461 || NET462 || NET47 || NET471 || NET472)
public static readonly DependencyProperty SelectionTextBrushProperty =
TextBoxBase.SelectionTextBrushProperty.AddOwner(typeof(PasswordBox));
public Brush SelectionTextBrush
{
get => (Brush) GetValue(SelectionTextBrushProperty);
set => SetValue(SelectionTextBrushProperty, value);
}
#endif
public static readonly DependencyProperty SelectionOpacityProperty =
TextBoxBase.SelectionOpacityProperty.AddOwner(typeof(PasswordBox));
public double SelectionOpacity
{
get => (double) GetValue(SelectionOpacityProperty);
set => SetValue(SelectionOpacityProperty, value);
}
public static readonly DependencyProperty CaretBrushProperty =
TextBoxBase.CaretBrushProperty.AddOwner(typeof(PasswordBox));
public Brush CaretBrush
{
get => (Brush) GetValue(CaretBrushProperty);
set => SetValue(CaretBrushProperty, value);
}
#if !NET40
public static readonly DependencyProperty IsSelectionActiveProperty =
TextBoxBase.IsSelectionActiveProperty.AddOwner(typeof(PasswordBox));
public bool IsSelectionActive => ActualPasswordBox != null && (bool) ActualPasswordBox.GetValue(IsSelectionActiveProperty);
#endif
public PasswordBox() => CommandBindings.Add(new CommandBinding(ControlCommands.Clear, (s, e) => Clear()));
public System.Windows.Controls.PasswordBox ActualPasswordBox { get; set; }
[DefaultValue("")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Password
{
get
{
if (ShowEyeButton && ShowPassword)
{
return _textBox.Text;
}
return ActualPasswordBox?.Password;
}
set
{
if (ActualPasswordBox == null)
{
_password = new SecureString();
value ??= string.Empty;
foreach (var item in value)
_password.AppendChar(item);
return;
}
if (Equals(ActualPasswordBox.Password, value)) return;
ActualPasswordBox.Password = value;
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public SecureString SecurePassword => ActualPasswordBox?.SecurePassword;
public Func<string, OperationResult<bool>> VerifyFunc { get; set; }
public virtual bool VerifyData()
{
OperationResult<bool> result;
if (VerifyFunc != null)
{
result = VerifyFunc.Invoke(ShowEyeButton && ShowPassword
? _textBox.Text
: ActualPasswordBox.Password);
}
else
{
if (!string.IsNullOrEmpty(ShowEyeButton && ShowPassword
? _textBox.Text
: ActualPasswordBox.Password))
result = OperationResult.Success();
else if (InfoElement.GetNecessary(this))
result = OperationResult.Failed(Lang.IsNecessary);
else
result = OperationResult.Success();
}
var isError = !result.Data;
if (isError)
{
SetCurrentValue(IsErrorProperty, ValueBoxes.TrueBox);
SetCurrentValue(ErrorStrProperty, result.Message);
}
else
{
isError = Validation.GetHasError(this);
if (isError)
{
SetCurrentValue(ErrorStrProperty, Validation.GetErrors(this)[0].ErrorContent);
}
else
{
SetCurrentValue(IsErrorProperty, ValueBoxes.FalseBox);
SetCurrentValue(ErrorStrProperty, default(string));
}
}
return !isError;
}
private static void OnShowPasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ctl = (PasswordBox) d;
if (!ctl.ShowEyeButton) return;
if ((bool) e.NewValue)
{
ctl._textBox.Text = ctl.ActualPasswordBox.Password;
ctl._textBox.Select(string.IsNullOrEmpty(ctl._textBox.Text) ? 0 : ctl._textBox.Text.Length, 0);
}
else
{
ctl.ActualPasswordBox.Password = ctl._textBox.Text;
ctl._textBox.Clear();
}
}
public override void OnApplyTemplate()
{
if (ActualPasswordBox != null)
ActualPasswordBox.PasswordChanged -= PasswordBox_PasswordChanged;
if (_textBox != null)
_textBox.TextChanged -= TextBox_TextChanged;
base.OnApplyTemplate();
ActualPasswordBox = GetTemplateChild(ElementPasswordBox) as System.Windows.Controls.PasswordBox;
_textBox = GetTemplateChild(ElementTextBox) as System.Windows.Controls.TextBox;
if (ActualPasswordBox != null)
{
ActualPasswordBox.PasswordChanged += PasswordBox_PasswordChanged;
ActualPasswordBox.SetBinding(System.Windows.Controls.PasswordBox.MaxLengthProperty, new Binding(MaxLengthProperty.Name) { Source = this });
ActualPasswordBox.SetBinding(System.Windows.Controls.PasswordBox.SelectionBrushProperty, new Binding(SelectionBrushProperty.Name) { Source = this });
#if !(NET40 || NET45 || NET451 || NET452 || NET46 || NET461 || NET462 || NET47 || NET471 || NET472)
ActualPasswordBox.SetBinding(System.Windows.Controls.PasswordBox.SelectionTextBrushProperty, new Binding(SelectionTextBrushProperty.Name) { Source = this });
#endif
ActualPasswordBox.SetBinding(System.Windows.Controls.PasswordBox.SelectionOpacityProperty, new Binding(SelectionOpacityProperty.Name) { Source = this });
ActualPasswordBox.SetBinding(System.Windows.Controls.PasswordBox.CaretBrushProperty, new Binding(CaretBrushProperty.Name) { Source = this });
if (_password is { Length: > 0 })
{
var valuePtr = IntPtr.Zero;
try
{
valuePtr = Marshal.SecureStringToGlobalAllocUnicode(_password);
ActualPasswordBox.Password = Marshal.PtrToStringUni(valuePtr) ?? throw new InvalidOperationException();
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
_password.Clear();
}
}
}
if (_textBox != null)
{
_textBox.TextChanged += TextBox_TextChanged;
}
}
public void Paste()
{
ActualPasswordBox.Paste();
if (ShowEyeButton && ShowPassword)
{
_textBox.Text = ActualPasswordBox.Password;
}
}
public void SelectAll()
{
ActualPasswordBox.SelectAll();
if (ShowEyeButton && ShowPassword)
{
_textBox.SelectAll();
}
}
public void Clear()
{
ActualPasswordBox.Clear();
_textBox.Clear();
}
private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
{
if (!IsSafeEnabled)
{
SetCurrentValue(UnsafePasswordProperty, ActualPasswordBox.Password);
if (ShowPassword)
{
_textBox.Text = ActualPasswordBox.Password;
}
}
VerifyData();
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (!IsSafeEnabled && ShowPassword)
{
Password = _textBox.Text;
SetCurrentValue(UnsafePasswordProperty, Password);
}
VerifyData();
}
}
}
| 37.096203 | 173 | 0.599536 | [
"MIT"
] | GF-Huang/HandyControls | src/Shared/HandyControl_Shared/Controls/Input/PasswordBox.cs | 14,709 | C# |
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Links;
using Sitecore.MediaFramework;
using Sitecore.MediaFramework.Diagnostics;
using Sitecore.Shell.Framework;
using Sitecore.Shell.Framework.Commands;
using Sitecore.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using Sitecore.MediaFramework.Account;
namespace Brightcove.MediaFramework.Brightcove.Commands
{
[Serializable]
public class CustomFields : Command
{
public override void Execute(CommandContext context)
{
Item application = Database.GetDatabase("core").GetItem(new ID("{F2375A5D-B094-4A9C-8F7C-C7699178D603}"));
UrlString urlString = new UrlString(LinkManager.GetItemUrl(application));
Item obj = Enumerable.FirstOrDefault<Item>((IEnumerable<Item>)context.Items);
if (obj != null)
{
urlString.Parameters.Add("videoId", obj.Fields[FieldIDs.MediaElement.Id].Value);
urlString.Parameters.Add("accountItemId", AccountManager.GetAccountItemForDescendant(Database.GetDatabase(obj.Database.Name).GetItem(obj.ID.ToString())).ID.ToString().Replace("{", "").Replace("}", ""));
urlString.Parameters.Add("type", "norm");
}
try
{
Sitecore.Shell.Framework.Windows.RunApplication(application, application.Appearance.Icon, application.DisplayName, urlString.ToString());
}
catch (Exception ex)
{
LogHelper.Error("Opening Custom Fields failed.", (object)this, ex);
}
}
protected virtual Item GetItem(CommandContext context)
{
if (context.Items.Length > 0 && context.Items[0] != null)
return context.Items[0];
string path = context.Parameters["id"];
if (!string.IsNullOrEmpty(path))
return (Sitecore.Context.ContentDatabase ?? Sitecore.Context.Database).GetItem(path);
return (Item)null;
}
public override CommandState QueryState(CommandContext context)
{
Item obj = this.GetItem(context);
return obj != null && obj.TemplateID.Equals(TemplateIDs.Video) ? CommandState.Enabled : CommandState.Hidden;
}
}
}
| 41.54386 | 219 | 0.629645 | [
"Apache-2.0"
] | BrightcoveOS/Sitecore-8.x-Media-Framework-2.x-Connector | src/Brightcove.MediaFramework.Brightcove/Commands/CustomFields.cs | 2,370 | 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 System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.dataworks_public;
using Aliyun.Acs.dataworks_public.Transform;
using Aliyun.Acs.dataworks_public.Transform.V20200518;
namespace Aliyun.Acs.dataworks_public.Model.V20200518
{
public class GetQualityEntityRequest : RpcAcsRequest<GetQualityEntityResponse>
{
public GetQualityEntityRequest()
: base("dataworks-public", "2020-05-18", "GetQualityEntity")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.dataworks_public.Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.dataworks_public.Endpoint.endpointRegionalType, null);
}
Protocol = ProtocolType.HTTPS;
Method = MethodType.POST;
}
private string projectName;
private string matchExpression;
private string envType;
private string tableName;
public string ProjectName
{
get
{
return projectName;
}
set
{
projectName = value;
DictionaryUtil.Add(BodyParameters, "ProjectName", value);
}
}
public string MatchExpression
{
get
{
return matchExpression;
}
set
{
matchExpression = value;
DictionaryUtil.Add(BodyParameters, "MatchExpression", value);
}
}
public string EnvType
{
get
{
return envType;
}
set
{
envType = value;
DictionaryUtil.Add(BodyParameters, "EnvType", value);
}
}
public string TableName
{
get
{
return tableName;
}
set
{
tableName = value;
DictionaryUtil.Add(BodyParameters, "TableName", value);
}
}
public override bool CheckShowJsonItemName()
{
return false;
}
public override GetQualityEntityResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return GetQualityEntityResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 26.62931 | 146 | 0.683069 | [
"Apache-2.0"
] | awei1688/aliyun-openapi-net-sdk | aliyun-net-sdk-dataworks-public/Dataworks_public/Model/V20200518/GetQualityEntityRequest.cs | 3,089 | C# |
using System;
using Server.Mobiles;
using Server.Items;
using Server.Spells;
using Server.Engines.VeteranRewards;
namespace Server.Items
{
public class RideableBoura : EtherealMount
{
public override int LabelNumber { get { return 1150006; } }
[Constructable]
public RideableBoura()
: base(0x46F9, 0x3EC6)
{
}
public override int EtherealHue { get { return 0; } }
public RideableBoura(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} | 21.625 | 67 | 0.579191 | [
"BSD-2-Clause"
] | greeduomacro/vivre-uo | Scripts/Vivre/Mobiles/Misc/RidableBoura.cs | 865 | C# |
//------------------------------------------------------------------------------
// <自动生成>
// 此代码由工具生成。
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </自动生成>
//------------------------------------------------------------------------------
namespace Studio.JZY.WorkAsp.RelationTree {
public partial class RelationDeptTree {
/// <summary>
/// Head1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlHead Head1;
/// <summary>
/// form1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
/// <summary>
/// HiddenField1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField HiddenField1;
/// <summary>
/// HiddenField2 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField HiddenField2;
}
}
| 27.057692 | 81 | 0.448472 | [
"MIT"
] | chen1993nian/CPMPlatform | Dev/WorkAsp/RelationTree/RelationDeptTree.aspx.designer.cs | 1,833 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Management.CosmosDB.Models;
using System.Collections.Generic;
namespace Microsoft.Azure.Commands.CosmosDB.Models
{
public class PSMongoIndexKeys
{
public PSMongoIndexKeys()
{
}
public PSMongoIndexKeys(MongoIndexKeys mongoIndexKeys)
{
if (mongoIndexKeys == null)
return;
Keys = mongoIndexKeys.Keys;
}
static public MongoIndexKeys ToSDKModel(PSMongoIndexKeys psMongoIndexKeys)
{
if (psMongoIndexKeys == null)
return null;
return new MongoIndexKeys{ Keys = psMongoIndexKeys.Keys };
}
//
// Summary:
// Gets or sets list of keys for each MongoDB collection in the Azure Cosmos DB
// service
public IList<string> Keys { get; set; }
}
} | 34.875 | 92 | 0.572879 | [
"MIT"
] | 3quanfeng/azure-powershell | src/CosmosDB/CosmosDB/Models/MongoDB/PSMongoIndexKeys.cs | 1,629 | C# |
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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 MassTransit.Subscriptions.Coordinator
{
using System;
using Logging;
using Magnum.Caching;
using Magnum.Extensions;
using Messages;
using Stact;
using Util;
public class PeerCache :
Actor
{
static readonly ILog _log = Logger.Get(typeof (PeerCache));
readonly Fiber _fiber;
readonly ActorFactory<PeerHandler> _peerHandlerFactory;
readonly Cache<Guid, Uri> _peerIds;
readonly Uri _peerUri;
readonly Cache<Uri, ActorRef> _peers;
readonly Scheduler _scheduler;
public PeerCache(Fiber fiber, Scheduler scheduler, SubscriptionObserver observer, Guid clientId,
Uri controlUri)
{
_peers = new DictionaryCache<Uri, ActorRef>();
_peerUri = controlUri;
_fiber = fiber;
_scheduler = scheduler;
_peerIds = new DictionaryCache<Guid, Uri>();
_peerHandlerFactory = ActorFactory.Create((f, s, i) => new PeerHandler(f, s, i, observer));
// create a peer for our local client
WithPeer(clientId, controlUri, x => { }, true);
}
[UsedImplicitly]
public void Handle(Message<Stop> message)
{
try
{
_peers.Each(x => x.ExitOnDispose(30.Seconds()).Dispose());
}
catch (Exception ex)
{
_log.Error("Message<Stop> Exception", ex);
}
}
[UsedImplicitly]
public void Handle(Message<AddPeer> message)
{
try
{
WithPeer(message.Body.PeerId, message.Body.PeerUri, x =>
{
if (_log.IsInfoEnabled)
_log.InfoFormat("AddPeer: {0}, {1}", message.Body.PeerId, message.Body.PeerUri);
x.Send(message);
}, true);
}
catch (Exception ex)
{
_log.Error("Message<AddPeer> Exception", ex);
}
}
[UsedImplicitly]
public void Handle(Message<RemovePeer> message)
{
try
{
WithPeer(message.Body.PeerId, message.Body.PeerUri, x =>
{
if (_log.IsInfoEnabled)
_log.InfoFormat("RemovePeer: {0}, {1}", message.Body.PeerId, message.Body.PeerUri);
x.Send(message);
}, false);
}
catch (Exception ex)
{
_log.Error("Message<RemovePeer> Exception", ex);
}
}
[UsedImplicitly]
public void Handle(Message<AddPeerSubscription> message)
{
try
{
WithPeer(message.Body.PeerId, x =>
{
if (_log.IsInfoEnabled)
_log.InfoFormat("AddPeerSubscription: {0}, {1} - {2}", message.Body.MessageName,
message.Body.SubscriptionId,
message.Body.PeerId);
x.Send(message);
});
}
catch (Exception ex)
{
_log.Error("Message<AddPeerSubscription> Exception", ex);
}
}
[UsedImplicitly]
public void Handle(Message<RemovePeerSubscription> message)
{
try
{
WithPeer(message.Body.PeerId, x =>
{
if (_log.IsInfoEnabled)
_log.InfoFormat("RemovePeerSubscription: {0}, {1} - {2}", message.Body.MessageName,
message.Body.SubscriptionId,
message.Body.PeerId);
x.Send(message);
});
}
catch (Exception ex)
{
_log.Error("Message<RemovePeerSubscription> Exception", ex);
}
}
void WithPeer(Guid peerId, Action<ActorRef> callback)
{
_peerIds.WithValue(peerId, peerUri => { WithPeer(peerId, peerUri, callback, false); });
}
void WithPeer(Guid peerId, Uri controlUri, Action<ActorRef> callback, bool createIfMissing)
{
bool found = _peers.Has(controlUri);
if (!found)
{
if (!createIfMissing)
{
return;
}
ActorRef peer = _peerHandlerFactory.GetActor();
peer.Send(new InitializePeerHandler(peerId, controlUri));
_peers.Add(controlUri, peer);
_peerIds[peerId] = controlUri;
}
else
{
if (!_peerIds.Has(peerId))
_peerIds[peerId] = controlUri;
}
callback(_peers[controlUri]);
}
}
} | 34.157895 | 112 | 0.487417 | [
"Apache-2.0"
] | doowb/MassTransit | src/MassTransit/Subscriptions/Coordinator/PeerCache.cs | 5,841 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** 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.GoogleNative.Dataproc.V1.Inputs
{
/// <summary>
/// Validation based on regular expressions.
/// </summary>
public sealed class RegexValidationArgs : Pulumi.ResourceArgs
{
[Input("regexes", required: true)]
private InputList<string>? _regexes;
/// <summary>
/// RE2 regular expressions used to validate the parameter's value. The value must match the regex in its entirety (substring matches are not sufficient).
/// </summary>
public InputList<string> Regexes
{
get => _regexes ?? (_regexes = new InputList<string>());
set => _regexes = value;
}
public RegexValidationArgs()
{
}
}
}
| 29.685714 | 162 | 0.642926 | [
"Apache-2.0"
] | AaronFriel/pulumi-google-native | sdk/dotnet/Dataproc/V1/Inputs/RegexValidationArgs.cs | 1,039 | C# |
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using SimpleIdentityServer.Scim.Host.Controllers;
using SimpleIdentityServer.Scim.Host.Extensions;
using SimpleIdentityServer.Module;
using System;
using System.Collections.Generic;
namespace SimpleIdentityServer.Scim.Host
{
public class ScimHostModule : IModule
{
public void Init(IDictionary<string, string> properties)
{
AspPipelineContext.Instance().ConfigureServiceContext.Initialized += HandleServiceContextInitialized;
AspPipelineContext.Instance().ConfigureServiceContext.MvcAdded += HandleMvcAdded;
AspPipelineContext.Instance().ConfigureServiceContext.AuthorizationAdded += HandleAuthorizationAdded;
}
private void HandleServiceContextInitialized(object sender, EventArgs e)
{
AspPipelineContext.Instance().ConfigureServiceContext.Services.AddScimHost(new ScimServerOptions());
}
private void HandleMvcAdded(object sender, EventArgs e)
{
var services = AspPipelineContext.Instance().ConfigureServiceContext.Services;
var mvcBuilder = AspPipelineContext.Instance().ConfigureServiceContext.MvcBuilder;
var assembly = typeof(SchemasController).Assembly;
var embeddedFileProvider = new EmbeddedFileProvider(assembly);
services.Configure<RazorViewEngineOptions>(options =>
{
options.FileProviders.Add(embeddedFileProvider);
});
mvcBuilder.AddApplicationPart(assembly);
}
private void HandleAuthorizationAdded(object sender, EventArgs e)
{
AspPipelineContext.Instance().ConfigureServiceContext.AuthorizationOptions.AddScimAuthPolicy();
}
}
} | 41.847826 | 114 | 0.720519 | [
"Apache-2.0"
] | appkins/SimpleIdentityServer | SimpleIdentityServer/src/Apis/Scim/SimpleIdentityServer.Scim.Host/ScimHostModule.cs | 1,927 | C# |
using System.Collections.Generic;
using SamplePrism.Domain.Models.Menus;
using SamplePrism.Domain.Models.Tickets;
namespace SamplePrism.Domain.Builders
{
public class OrderBuilderFor<T> : ILinkableToMenuItemBuilder<OrderBuilderFor<T>> where T : ILinkableToOrderBuilder<T>
{
private readonly T _parent;
private readonly OrderBuilder _orderBuilder;
private OrderBuilderFor(T parent)
{
_parent = parent;
_orderBuilder = OrderBuilder.Create();
}
public static OrderBuilderFor<T> Create(T parent)
{
return new OrderBuilderFor<T>(parent);
}
public OrderBuilderFor<T> ForMenuItem(MenuItem menuItem)
{
_orderBuilder.ForMenuItem(menuItem);
return this;
}
public OrderBuilderFor<T> WithQuantity(decimal quantity)
{
_orderBuilder.WithQuantity(quantity);
return this;
}
public OrderBuilderFor<T> WithTaxTemplates(IList<TaxTemplate> taxTemplates)
{
_orderBuilder.WithTaxTemplates(taxTemplates);
return this;
}
public OrderBuilderFor<T> WithTaxTemplate(TaxTemplate taxTemplate)
{
_orderBuilder.AddTaxTemplate(taxTemplate);
return this;
}
public OrderBuilderFor<T> CalculatePrice(bool calculatePrice)
{
_orderBuilder.CalculatePrice(calculatePrice);
return this;
}
public OrderBuilderFor<T> WithPrice(decimal price)
{
_orderBuilder.WithPrice(price);
return this;
}
public OrderBuilderFor<T> ToggleOrderTag(OrderTagGroup orderTagGroup, OrderTag orderTag)
{
_orderBuilder.ToggleOrderTag(orderTagGroup, orderTag);
return this;
}
public void Link(MenuItem menuItem)
{
_orderBuilder.ForMenuItem(menuItem);
}
public MenuItemBuilderFor<OrderBuilderFor<T>> CreateMenuItem(string menuItemName)
{
return MenuItemBuilderFor<OrderBuilderFor<T>>.Create(menuItemName, this);
}
public T Do(int times = 1)
{
for (int i = 0; i < times; i++)
{
_parent.Link(_orderBuilder);
}
return _parent;
}
}
} | 28.47619 | 121 | 0.598662 | [
"Apache-2.0"
] | XYRYTeam/SimplePrism | SamplePrism.Domain/Builders/OrderBuilderFor.cs | 2,394 | C# |
/*
* Copyright 2010-2013 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.
*/
using System;
using Amazon.ElasticLoadBalancing;
using Amazon.ElasticLoadBalancing.Model;
namespace Amazon.ElasticLoadBalancing
{
/// <summary>
/// Interface for accessing AmazonElasticLoadBalancing.
///
/// Elastic Load Balancing <para> Elastic Load Balancing is a cost-effective and easy to use web service to help you improve the availability
/// and scalability of your application running on Amazon Elastic Cloud Compute (Amazon EC2). It makes it easy for you to distribute application
/// loads between two or more EC2 instances. Elastic Load Balancing supports the growth in traffic of your application by enabling availability
/// through redundancy. </para> <para>This guide provides detailed information about Elastic Load Balancing actions, data types, and parameters
/// that can be used for sending a query request. Query requests are HTTP or HTTPS requests that use the HTTP verb GET or POST and a query
/// parameter named Action or Operation. Action is used throughout this documentation, although Operation is supported for backward
/// compatibility with other AWS Query APIs.</para> <para>For detailed information on constructing a query request using the actions, data
/// types, and parameters mentioned in this guide, go to Using the Query API in the <i>Elastic Load Balancing Developer Guide</i> .</para>
/// <para>For detailed information about Elastic Load Balancing features and their associated actions, go to Using Elastic Load Balancing in the
/// <i>Elastic Load Balancing Developer Guide</i> .</para> <para>This reference guide is based on the current WSDL, which is available at:
/// </para>
/// </summary>
public interface AmazonElasticLoadBalancing : IDisposable
{
#region DescribeLoadBalancerPolicyTypes
/// <summary>
/// <para> Returns meta-information on the specified LoadBalancer policies defined by the Elastic Load Balancing service. The policy types that
/// are returned from this action can be used in a CreateLoadBalancerPolicy action to instantiate specific policy configurations that will be
/// applied to an Elastic LoadBalancer. </para>
/// </summary>
///
/// <param name="describeLoadBalancerPolicyTypesRequest">Container for the necessary parameters to execute the DescribeLoadBalancerPolicyTypes
/// service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DescribeLoadBalancerPolicyTypes service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="PolicyTypeNotFoundException"/>
DescribeLoadBalancerPolicyTypesResponse DescribeLoadBalancerPolicyTypes(DescribeLoadBalancerPolicyTypesRequest describeLoadBalancerPolicyTypesRequest);
/// <summary>
/// Initiates the asynchronous execution of the DescribeLoadBalancerPolicyTypes operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeLoadBalancerPolicyTypes"/>
/// </summary>
///
/// <param name="describeLoadBalancerPolicyTypesRequest">Container for the necessary parameters to execute the DescribeLoadBalancerPolicyTypes
/// operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDescribeLoadBalancerPolicyTypes operation.</returns>
IAsyncResult BeginDescribeLoadBalancerPolicyTypes(DescribeLoadBalancerPolicyTypesRequest describeLoadBalancerPolicyTypesRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DescribeLoadBalancerPolicyTypes operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeLoadBalancerPolicyTypes"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeLoadBalancerPolicyTypes.</param>
///
/// <returns>Returns a DescribeLoadBalancerPolicyTypesResult from AmazonElasticLoadBalancing.</returns>
DescribeLoadBalancerPolicyTypesResponse EndDescribeLoadBalancerPolicyTypes(IAsyncResult asyncResult);
/// <summary>
/// <para> Returns meta-information on the specified LoadBalancer policies defined by the Elastic Load Balancing service. The policy types that
/// are returned from this action can be used in a CreateLoadBalancerPolicy action to instantiate specific policy configurations that will be
/// applied to an Elastic LoadBalancer. </para>
/// </summary>
///
/// <returns>The response from the DescribeLoadBalancerPolicyTypes service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="PolicyTypeNotFoundException"/>
DescribeLoadBalancerPolicyTypesResponse DescribeLoadBalancerPolicyTypes();
#endregion
#region ConfigureHealthCheck
/// <summary>
/// <para> Enables the client to define an application healthcheck for the instances. </para>
/// </summary>
///
/// <param name="configureHealthCheckRequest">Container for the necessary parameters to execute the ConfigureHealthCheck service method on
/// AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the ConfigureHealthCheck service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="LoadBalancerNotFoundException"/>
ConfigureHealthCheckResponse ConfigureHealthCheck(ConfigureHealthCheckRequest configureHealthCheckRequest);
/// <summary>
/// Initiates the asynchronous execution of the ConfigureHealthCheck operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.ConfigureHealthCheck"/>
/// </summary>
///
/// <param name="configureHealthCheckRequest">Container for the necessary parameters to execute the ConfigureHealthCheck operation on
/// AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndConfigureHealthCheck operation.</returns>
IAsyncResult BeginConfigureHealthCheck(ConfigureHealthCheckRequest configureHealthCheckRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ConfigureHealthCheck operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.ConfigureHealthCheck"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginConfigureHealthCheck.</param>
///
/// <returns>Returns a ConfigureHealthCheckResult from AmazonElasticLoadBalancing.</returns>
ConfigureHealthCheckResponse EndConfigureHealthCheck(IAsyncResult asyncResult);
#endregion
#region DetachLoadBalancerFromSubnets
/// <summary>
/// <para> Removes subnets from the set of configured subnets in the VPC for the LoadBalancer. </para> <para> After a subnet is removed all of
/// the EndPoints registered with the LoadBalancer that are in the removed subnet will go into the <i>OutOfService</i> state. When a subnet is
/// removed, the LoadBalancer will balance the traffic among the remaining routable subnets for the LoadBalancer. </para>
/// </summary>
///
/// <param name="detachLoadBalancerFromSubnetsRequest">Container for the necessary parameters to execute the DetachLoadBalancerFromSubnets
/// service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DetachLoadBalancerFromSubnets service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
DetachLoadBalancerFromSubnetsResponse DetachLoadBalancerFromSubnets(DetachLoadBalancerFromSubnetsRequest detachLoadBalancerFromSubnetsRequest);
/// <summary>
/// Initiates the asynchronous execution of the DetachLoadBalancerFromSubnets operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DetachLoadBalancerFromSubnets"/>
/// </summary>
///
/// <param name="detachLoadBalancerFromSubnetsRequest">Container for the necessary parameters to execute the DetachLoadBalancerFromSubnets
/// operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDetachLoadBalancerFromSubnets operation.</returns>
IAsyncResult BeginDetachLoadBalancerFromSubnets(DetachLoadBalancerFromSubnetsRequest detachLoadBalancerFromSubnetsRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DetachLoadBalancerFromSubnets operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DetachLoadBalancerFromSubnets"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDetachLoadBalancerFromSubnets.</param>
///
/// <returns>Returns a DetachLoadBalancerFromSubnetsResult from AmazonElasticLoadBalancing.</returns>
DetachLoadBalancerFromSubnetsResponse EndDetachLoadBalancerFromSubnets(IAsyncResult asyncResult);
#endregion
#region DescribeLoadBalancerPolicies
/// <summary>
/// <para>Returns detailed descriptions of the policies. If you specify a LoadBalancer name, the operation returns either the descriptions of
/// the specified policies, or descriptions of all the policies created for the LoadBalancer. If you don't specify a LoadBalancer name, the
/// operation returns descriptions of the specified sample policies, or descriptions of all the sample policies. The names of the sample
/// policies have the <c>ELBSample-</c> prefix. </para>
/// </summary>
///
/// <param name="describeLoadBalancerPoliciesRequest">Container for the necessary parameters to execute the DescribeLoadBalancerPolicies service
/// method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DescribeLoadBalancerPolicies service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="PolicyNotFoundException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
DescribeLoadBalancerPoliciesResponse DescribeLoadBalancerPolicies(DescribeLoadBalancerPoliciesRequest describeLoadBalancerPoliciesRequest);
/// <summary>
/// Initiates the asynchronous execution of the DescribeLoadBalancerPolicies operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeLoadBalancerPolicies"/>
/// </summary>
///
/// <param name="describeLoadBalancerPoliciesRequest">Container for the necessary parameters to execute the DescribeLoadBalancerPolicies
/// operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDescribeLoadBalancerPolicies operation.</returns>
IAsyncResult BeginDescribeLoadBalancerPolicies(DescribeLoadBalancerPoliciesRequest describeLoadBalancerPoliciesRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DescribeLoadBalancerPolicies operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeLoadBalancerPolicies"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeLoadBalancerPolicies.</param>
///
/// <returns>Returns a DescribeLoadBalancerPoliciesResult from AmazonElasticLoadBalancing.</returns>
DescribeLoadBalancerPoliciesResponse EndDescribeLoadBalancerPolicies(IAsyncResult asyncResult);
/// <summary>
/// <para>Returns detailed descriptions of the policies. If you specify a LoadBalancer name, the operation returns either the descriptions of
/// the specified policies, or descriptions of all the policies created for the LoadBalancer. If you don't specify a LoadBalancer name, the
/// operation returns descriptions of the specified sample policies, or descriptions of all the sample policies. The names of the sample
/// policies have the <c>ELBSample-</c> prefix. </para>
/// </summary>
///
/// <returns>The response from the DescribeLoadBalancerPolicies service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="PolicyNotFoundException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
DescribeLoadBalancerPoliciesResponse DescribeLoadBalancerPolicies();
#endregion
#region SetLoadBalancerPoliciesOfListener
/// <summary>
/// <para> Associates, updates, or disables a policy with a listener on the LoadBalancer. You can associate multiple policies with a listener.
/// </para>
/// </summary>
///
/// <param name="setLoadBalancerPoliciesOfListenerRequest">Container for the necessary parameters to execute the
/// SetLoadBalancerPoliciesOfListener service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the SetLoadBalancerPoliciesOfListener service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="PolicyNotFoundException"/>
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
/// <exception cref="ListenerNotFoundException"/>
SetLoadBalancerPoliciesOfListenerResponse SetLoadBalancerPoliciesOfListener(SetLoadBalancerPoliciesOfListenerRequest setLoadBalancerPoliciesOfListenerRequest);
/// <summary>
/// Initiates the asynchronous execution of the SetLoadBalancerPoliciesOfListener operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.SetLoadBalancerPoliciesOfListener"/>
/// </summary>
///
/// <param name="setLoadBalancerPoliciesOfListenerRequest">Container for the necessary parameters to execute the
/// SetLoadBalancerPoliciesOfListener operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndSetLoadBalancerPoliciesOfListener operation.</returns>
IAsyncResult BeginSetLoadBalancerPoliciesOfListener(SetLoadBalancerPoliciesOfListenerRequest setLoadBalancerPoliciesOfListenerRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the SetLoadBalancerPoliciesOfListener operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.SetLoadBalancerPoliciesOfListener"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginSetLoadBalancerPoliciesOfListener.</param>
///
/// <returns>Returns a SetLoadBalancerPoliciesOfListenerResult from AmazonElasticLoadBalancing.</returns>
SetLoadBalancerPoliciesOfListenerResponse EndSetLoadBalancerPoliciesOfListener(IAsyncResult asyncResult);
#endregion
#region DisableAvailabilityZonesForLoadBalancer
/// <summary>
/// <para> Removes the specified EC2 Availability Zones from the set of configured Availability Zones for the LoadBalancer. </para> <para> There
/// must be at least one Availability Zone registered with a LoadBalancer at all times. A client cannot remove all the Availability Zones from a
/// LoadBalancer. Once an Availability Zone is removed, all the instances registered with the LoadBalancer that are in the removed Availability
/// Zone go into the OutOfService state. Upon Availability Zone removal, the LoadBalancer attempts to equally balance the traffic among its
/// remaining usable Availability Zones. Trying to remove an Availability Zone that was not associated with the LoadBalancer does nothing.
/// </para> <para><b>NOTE:</b> In order for this call to be successful, the client must have created the LoadBalancer. The client must provide
/// the same account credentials as those that were used to create the LoadBalancer. </para>
/// </summary>
///
/// <param name="disableAvailabilityZonesForLoadBalancerRequest">Container for the necessary parameters to execute the
/// DisableAvailabilityZonesForLoadBalancer service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DisableAvailabilityZonesForLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
DisableAvailabilityZonesForLoadBalancerResponse DisableAvailabilityZonesForLoadBalancer(DisableAvailabilityZonesForLoadBalancerRequest disableAvailabilityZonesForLoadBalancerRequest);
/// <summary>
/// Initiates the asynchronous execution of the DisableAvailabilityZonesForLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DisableAvailabilityZonesForLoadBalancer"/>
/// </summary>
///
/// <param name="disableAvailabilityZonesForLoadBalancerRequest">Container for the necessary parameters to execute the
/// DisableAvailabilityZonesForLoadBalancer operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDisableAvailabilityZonesForLoadBalancer operation.</returns>
IAsyncResult BeginDisableAvailabilityZonesForLoadBalancer(DisableAvailabilityZonesForLoadBalancerRequest disableAvailabilityZonesForLoadBalancerRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DisableAvailabilityZonesForLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DisableAvailabilityZonesForLoadBalancer"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDisableAvailabilityZonesForLoadBalancer.</param>
///
/// <returns>Returns a DisableAvailabilityZonesForLoadBalancerResult from AmazonElasticLoadBalancing.</returns>
DisableAvailabilityZonesForLoadBalancerResponse EndDisableAvailabilityZonesForLoadBalancer(IAsyncResult asyncResult);
#endregion
#region DescribeInstanceHealth
/// <summary>
/// <para> Returns the current state of the instances of the specified LoadBalancer. If no instances are specified, the state of all the
/// instances for the LoadBalancer is returned. </para> <para><b>NOTE:</b> The client must have created the specified input LoadBalancer in
/// order to retrieve this information; the client must provide the same account credentials as those that were used to create the LoadBalancer.
/// </para>
/// </summary>
///
/// <param name="describeInstanceHealthRequest">Container for the necessary parameters to execute the DescribeInstanceHealth service method on
/// AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DescribeInstanceHealth service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="LoadBalancerNotFoundException"/>
/// <exception cref="InvalidInstanceException"/>
DescribeInstanceHealthResponse DescribeInstanceHealth(DescribeInstanceHealthRequest describeInstanceHealthRequest);
/// <summary>
/// Initiates the asynchronous execution of the DescribeInstanceHealth operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeInstanceHealth"/>
/// </summary>
///
/// <param name="describeInstanceHealthRequest">Container for the necessary parameters to execute the DescribeInstanceHealth operation on
/// AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDescribeInstanceHealth operation.</returns>
IAsyncResult BeginDescribeInstanceHealth(DescribeInstanceHealthRequest describeInstanceHealthRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DescribeInstanceHealth operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeInstanceHealth"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeInstanceHealth.</param>
///
/// <returns>Returns a DescribeInstanceHealthResult from AmazonElasticLoadBalancing.</returns>
DescribeInstanceHealthResponse EndDescribeInstanceHealth(IAsyncResult asyncResult);
#endregion
#region DeleteLoadBalancerPolicy
/// <summary>
/// <para> Deletes a policy from the LoadBalancer. The specified policy must not be enabled for any listeners. </para>
/// </summary>
///
/// <param name="deleteLoadBalancerPolicyRequest">Container for the necessary parameters to execute the DeleteLoadBalancerPolicy service method
/// on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DeleteLoadBalancerPolicy service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
DeleteLoadBalancerPolicyResponse DeleteLoadBalancerPolicy(DeleteLoadBalancerPolicyRequest deleteLoadBalancerPolicyRequest);
/// <summary>
/// Initiates the asynchronous execution of the DeleteLoadBalancerPolicy operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeleteLoadBalancerPolicy"/>
/// </summary>
///
/// <param name="deleteLoadBalancerPolicyRequest">Container for the necessary parameters to execute the DeleteLoadBalancerPolicy operation on
/// AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDeleteLoadBalancerPolicy operation.</returns>
IAsyncResult BeginDeleteLoadBalancerPolicy(DeleteLoadBalancerPolicyRequest deleteLoadBalancerPolicyRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeleteLoadBalancerPolicy operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeleteLoadBalancerPolicy"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteLoadBalancerPolicy.</param>
///
/// <returns>Returns a DeleteLoadBalancerPolicyResult from AmazonElasticLoadBalancing.</returns>
DeleteLoadBalancerPolicyResponse EndDeleteLoadBalancerPolicy(IAsyncResult asyncResult);
#endregion
#region CreateLoadBalancerPolicy
/// <summary>
/// <para> Creates a new policy that contains the necessary attributes depending on the policy type. Policies are settings that are saved for
/// your Elastic LoadBalancer and that can be applied to the front-end listener, or the back-end application server, depending on your policy
/// type. </para>
/// </summary>
///
/// <param name="createLoadBalancerPolicyRequest">Container for the necessary parameters to execute the CreateLoadBalancerPolicy service method
/// on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the CreateLoadBalancerPolicy service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="PolicyTypeNotFoundException"/>
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="DuplicatePolicyNameException"/>
/// <exception cref="TooManyPoliciesException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
CreateLoadBalancerPolicyResponse CreateLoadBalancerPolicy(CreateLoadBalancerPolicyRequest createLoadBalancerPolicyRequest);
/// <summary>
/// Initiates the asynchronous execution of the CreateLoadBalancerPolicy operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancerPolicy"/>
/// </summary>
///
/// <param name="createLoadBalancerPolicyRequest">Container for the necessary parameters to execute the CreateLoadBalancerPolicy operation on
/// AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndCreateLoadBalancerPolicy operation.</returns>
IAsyncResult BeginCreateLoadBalancerPolicy(CreateLoadBalancerPolicyRequest createLoadBalancerPolicyRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateLoadBalancerPolicy operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancerPolicy"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateLoadBalancerPolicy.</param>
///
/// <returns>Returns a CreateLoadBalancerPolicyResult from AmazonElasticLoadBalancing.</returns>
CreateLoadBalancerPolicyResponse EndCreateLoadBalancerPolicy(IAsyncResult asyncResult);
#endregion
#region EnableAvailabilityZonesForLoadBalancer
/// <summary>
/// <para> Adds one or more EC2 Availability Zones to the LoadBalancer. </para> <para> The LoadBalancer evenly distributes requests across all
/// its registered Availability Zones that contain instances. As a result, the client must ensure that its LoadBalancer is appropriately scaled
/// for each registered Availability Zone. </para> <para><b>NOTE:</b> The new EC2 Availability Zones to be added must be in the same EC2 Region
/// as the Availability Zones for which the LoadBalancer was created. </para>
/// </summary>
///
/// <param name="enableAvailabilityZonesForLoadBalancerRequest">Container for the necessary parameters to execute the
/// EnableAvailabilityZonesForLoadBalancer service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the EnableAvailabilityZonesForLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="LoadBalancerNotFoundException"/>
EnableAvailabilityZonesForLoadBalancerResponse EnableAvailabilityZonesForLoadBalancer(EnableAvailabilityZonesForLoadBalancerRequest enableAvailabilityZonesForLoadBalancerRequest);
/// <summary>
/// Initiates the asynchronous execution of the EnableAvailabilityZonesForLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.EnableAvailabilityZonesForLoadBalancer"/>
/// </summary>
///
/// <param name="enableAvailabilityZonesForLoadBalancerRequest">Container for the necessary parameters to execute the
/// EnableAvailabilityZonesForLoadBalancer operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndEnableAvailabilityZonesForLoadBalancer operation.</returns>
IAsyncResult BeginEnableAvailabilityZonesForLoadBalancer(EnableAvailabilityZonesForLoadBalancerRequest enableAvailabilityZonesForLoadBalancerRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the EnableAvailabilityZonesForLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.EnableAvailabilityZonesForLoadBalancer"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginEnableAvailabilityZonesForLoadBalancer.</param>
///
/// <returns>Returns a EnableAvailabilityZonesForLoadBalancerResult from AmazonElasticLoadBalancing.</returns>
EnableAvailabilityZonesForLoadBalancerResponse EndEnableAvailabilityZonesForLoadBalancer(IAsyncResult asyncResult);
#endregion
#region CreateLoadBalancerListeners
/// <summary>
/// <para> Creates one or more listeners on a LoadBalancer for the specified port. If a listener with the given port does not already exist, it
/// will be created; otherwise, the properties of the new listener must match the properties of the existing listener. </para>
/// </summary>
///
/// <param name="createLoadBalancerListenersRequest">Container for the necessary parameters to execute the CreateLoadBalancerListeners service
/// method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the CreateLoadBalancerListeners service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="DuplicateListenerException"/>
/// <exception cref="CertificateNotFoundException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
CreateLoadBalancerListenersResponse CreateLoadBalancerListeners(CreateLoadBalancerListenersRequest createLoadBalancerListenersRequest);
/// <summary>
/// Initiates the asynchronous execution of the CreateLoadBalancerListeners operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancerListeners"/>
/// </summary>
///
/// <param name="createLoadBalancerListenersRequest">Container for the necessary parameters to execute the CreateLoadBalancerListeners operation
/// on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndCreateLoadBalancerListeners operation.</returns>
IAsyncResult BeginCreateLoadBalancerListeners(CreateLoadBalancerListenersRequest createLoadBalancerListenersRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateLoadBalancerListeners operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancerListeners"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateLoadBalancerListeners.</param>
///
/// <returns>Returns a CreateLoadBalancerListenersResult from AmazonElasticLoadBalancing.</returns>
CreateLoadBalancerListenersResponse EndCreateLoadBalancerListeners(IAsyncResult asyncResult);
#endregion
#region CreateLoadBalancer
/// <summary>
/// <para> Creates a new LoadBalancer. </para> <para> After the call has completed successfully, a new LoadBalancer is created; however, it will
/// not be usable until at least one instance has been registered. When the LoadBalancer creation is completed, the client can check whether or
/// not it is usable by using the DescribeInstanceHealth action. The LoadBalancer is usable as soon as any registered instance is
/// <i>InService</i> .
/// </para> <para><b>NOTE:</b> Currently, the client's quota of LoadBalancers is limited to ten per Region. </para> <para><b>NOTE:</b>
/// LoadBalancer DNS names vary depending on the Region they're created in. For LoadBalancers created in the United States, the DNS name ends
/// with: us-east-1.elb.amazonaws.com (for the US Standard Region) us-west-1.elb.amazonaws.com (for the Northern California Region) For
/// LoadBalancers created in the EU (Ireland) Region, the DNS name ends with: eu-west-1.elb.amazonaws.com </para> <para>For information on using
/// CreateLoadBalancer to create a new LoadBalancer in Amazon EC2, go to Using Query API section in the <i>Creating a Load Balancer With SSL
/// Cipher Settings and Back-end Authentication</i> topic of the <i>Elastic Load Balancing Developer Guide</i> .</para> <para>For information on
/// using CreateLoadBalancer to create a new LoadBalancer in Amazon VPC, go to Using Query API section in the <i>Creating a Basic Load Balancer
/// in Amazon VPC</i> topic of the <i>Elastic Load Balancing Developer Guide</i> .</para>
/// </summary>
///
/// <param name="createLoadBalancerRequest">Container for the necessary parameters to execute the CreateLoadBalancer service method on
/// AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the CreateLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidSubnetException"/>
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="InvalidSecurityGroupException"/>
/// <exception cref="CertificateNotFoundException"/>
/// <exception cref="InvalidSchemeException"/>
/// <exception cref="DuplicateLoadBalancerNameException"/>
/// <exception cref="TooManyLoadBalancersException"/>
/// <exception cref="SubnetNotFoundException"/>
CreateLoadBalancerResponse CreateLoadBalancer(CreateLoadBalancerRequest createLoadBalancerRequest);
/// <summary>
/// Initiates the asynchronous execution of the CreateLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancer"/>
/// </summary>
///
/// <param name="createLoadBalancerRequest">Container for the necessary parameters to execute the CreateLoadBalancer operation on
/// AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndCreateLoadBalancer operation.</returns>
IAsyncResult BeginCreateLoadBalancer(CreateLoadBalancerRequest createLoadBalancerRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancer"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateLoadBalancer.</param>
///
/// <returns>Returns a CreateLoadBalancerResult from AmazonElasticLoadBalancing.</returns>
CreateLoadBalancerResponse EndCreateLoadBalancer(IAsyncResult asyncResult);
#endregion
#region DeleteLoadBalancer
/// <summary>
/// <para> Deletes the specified LoadBalancer. </para> <para> If attempting to recreate the LoadBalancer, the client must reconfigure all the
/// settings. The DNS name associated with a deleted LoadBalancer will no longer be usable. Once deleted, the name and associated DNS record of
/// the LoadBalancer no longer exist and traffic sent to any of its IP addresses will no longer be delivered to client instances. The client
/// will not receive the same DNS name even if a new LoadBalancer with same LoadBalancerName is created. </para> <para> To successfully call
/// this API, the client must provide the same account credentials as were used to create the LoadBalancer. </para> <para><b>NOTE:</b> By
/// design, if the LoadBalancer does not exist or has already been deleted, DeleteLoadBalancer still succeeds. </para>
/// </summary>
///
/// <param name="deleteLoadBalancerRequest">Container for the necessary parameters to execute the DeleteLoadBalancer service method on
/// AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DeleteLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns>
///
DeleteLoadBalancerResponse DeleteLoadBalancer(DeleteLoadBalancerRequest deleteLoadBalancerRequest);
/// <summary>
/// Initiates the asynchronous execution of the DeleteLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeleteLoadBalancer"/>
/// </summary>
///
/// <param name="deleteLoadBalancerRequest">Container for the necessary parameters to execute the DeleteLoadBalancer operation on
/// AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDeleteLoadBalancer operation.</returns>
IAsyncResult BeginDeleteLoadBalancer(DeleteLoadBalancerRequest deleteLoadBalancerRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeleteLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeleteLoadBalancer"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteLoadBalancer.</param>
///
/// <returns>Returns a DeleteLoadBalancerResult from AmazonElasticLoadBalancing.</returns>
DeleteLoadBalancerResponse EndDeleteLoadBalancer(IAsyncResult asyncResult);
#endregion
#region SetLoadBalancerPoliciesForBackendServer
/// <summary>
/// <para> Replaces the current set of policies associated with a port on which the back-end server is listening with a new set of policies.
/// After the policies have been created using CreateLoadBalancerPolicy, they can be applied here as a list. At this time, only the back-end
/// server authentication policy type can be applied to the back-end ports; this policy type is composed of multiple public key policies.
/// </para>
/// </summary>
///
/// <param name="setLoadBalancerPoliciesForBackendServerRequest">Container for the necessary parameters to execute the
/// SetLoadBalancerPoliciesForBackendServer service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the SetLoadBalancerPoliciesForBackendServer service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="PolicyNotFoundException"/>
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
SetLoadBalancerPoliciesForBackendServerResponse SetLoadBalancerPoliciesForBackendServer(SetLoadBalancerPoliciesForBackendServerRequest setLoadBalancerPoliciesForBackendServerRequest);
/// <summary>
/// Initiates the asynchronous execution of the SetLoadBalancerPoliciesForBackendServer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.SetLoadBalancerPoliciesForBackendServer"/>
/// </summary>
///
/// <param name="setLoadBalancerPoliciesForBackendServerRequest">Container for the necessary parameters to execute the
/// SetLoadBalancerPoliciesForBackendServer operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndSetLoadBalancerPoliciesForBackendServer operation.</returns>
IAsyncResult BeginSetLoadBalancerPoliciesForBackendServer(SetLoadBalancerPoliciesForBackendServerRequest setLoadBalancerPoliciesForBackendServerRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the SetLoadBalancerPoliciesForBackendServer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.SetLoadBalancerPoliciesForBackendServer"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginSetLoadBalancerPoliciesForBackendServer.</param>
///
/// <returns>Returns a SetLoadBalancerPoliciesForBackendServerResult from AmazonElasticLoadBalancing.</returns>
SetLoadBalancerPoliciesForBackendServerResponse EndSetLoadBalancerPoliciesForBackendServer(IAsyncResult asyncResult);
#endregion
#region DeleteLoadBalancerListeners
/// <summary>
/// <para> Deletes listeners from the LoadBalancer for the specified port. </para>
/// </summary>
///
/// <param name="deleteLoadBalancerListenersRequest">Container for the necessary parameters to execute the DeleteLoadBalancerListeners service
/// method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DeleteLoadBalancerListeners service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="LoadBalancerNotFoundException"/>
DeleteLoadBalancerListenersResponse DeleteLoadBalancerListeners(DeleteLoadBalancerListenersRequest deleteLoadBalancerListenersRequest);
/// <summary>
/// Initiates the asynchronous execution of the DeleteLoadBalancerListeners operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeleteLoadBalancerListeners"/>
/// </summary>
///
/// <param name="deleteLoadBalancerListenersRequest">Container for the necessary parameters to execute the DeleteLoadBalancerListeners operation
/// on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDeleteLoadBalancerListeners operation.</returns>
IAsyncResult BeginDeleteLoadBalancerListeners(DeleteLoadBalancerListenersRequest deleteLoadBalancerListenersRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeleteLoadBalancerListeners operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeleteLoadBalancerListeners"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteLoadBalancerListeners.</param>
///
/// <returns>Returns a DeleteLoadBalancerListenersResult from AmazonElasticLoadBalancing.</returns>
DeleteLoadBalancerListenersResponse EndDeleteLoadBalancerListeners(IAsyncResult asyncResult);
#endregion
#region DeregisterInstancesFromLoadBalancer
/// <summary>
/// <para> Deregisters instances from the LoadBalancer. Once the instance is deregistered, it will stop receiving traffic from the LoadBalancer.
/// </para> <para> In order to successfully call this API, the same account credentials as those used to create the LoadBalancer must be
/// provided. </para>
/// </summary>
///
/// <param name="deregisterInstancesFromLoadBalancerRequest">Container for the necessary parameters to execute the
/// DeregisterInstancesFromLoadBalancer service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DeregisterInstancesFromLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="LoadBalancerNotFoundException"/>
/// <exception cref="InvalidInstanceException"/>
DeregisterInstancesFromLoadBalancerResponse DeregisterInstancesFromLoadBalancer(DeregisterInstancesFromLoadBalancerRequest deregisterInstancesFromLoadBalancerRequest);
/// <summary>
/// Initiates the asynchronous execution of the DeregisterInstancesFromLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeregisterInstancesFromLoadBalancer"/>
/// </summary>
///
/// <param name="deregisterInstancesFromLoadBalancerRequest">Container for the necessary parameters to execute the
/// DeregisterInstancesFromLoadBalancer operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDeregisterInstancesFromLoadBalancer operation.</returns>
IAsyncResult BeginDeregisterInstancesFromLoadBalancer(DeregisterInstancesFromLoadBalancerRequest deregisterInstancesFromLoadBalancerRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeregisterInstancesFromLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeregisterInstancesFromLoadBalancer"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeregisterInstancesFromLoadBalancer.</param>
///
/// <returns>Returns a DeregisterInstancesFromLoadBalancerResult from AmazonElasticLoadBalancing.</returns>
DeregisterInstancesFromLoadBalancerResponse EndDeregisterInstancesFromLoadBalancer(IAsyncResult asyncResult);
#endregion
#region SetLoadBalancerListenerSSLCertificate
/// <summary>
/// <para> Sets the certificate that terminates the specified listener's SSL connections. The specified certificate replaces any prior
/// certificate that was used on the same LoadBalancer and port. </para> <para>For information on using SetLoadBalancerListenerSSLCertificate,
/// go to Using the Query API in <i>Updating an SSL Certificate for a Load Balancer</i> section of the <i>Elastic Load Balancing Developer
/// Guide</i> .</para>
/// </summary>
///
/// <param name="setLoadBalancerListenerSSLCertificateRequest">Container for the necessary parameters to execute the
/// SetLoadBalancerListenerSSLCertificate service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the SetLoadBalancerListenerSSLCertificate service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="CertificateNotFoundException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
/// <exception cref="ListenerNotFoundException"/>
SetLoadBalancerListenerSSLCertificateResponse SetLoadBalancerListenerSSLCertificate(SetLoadBalancerListenerSSLCertificateRequest setLoadBalancerListenerSSLCertificateRequest);
/// <summary>
/// Initiates the asynchronous execution of the SetLoadBalancerListenerSSLCertificate operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.SetLoadBalancerListenerSSLCertificate"/>
/// </summary>
///
/// <param name="setLoadBalancerListenerSSLCertificateRequest">Container for the necessary parameters to execute the
/// SetLoadBalancerListenerSSLCertificate operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndSetLoadBalancerListenerSSLCertificate operation.</returns>
IAsyncResult BeginSetLoadBalancerListenerSSLCertificate(SetLoadBalancerListenerSSLCertificateRequest setLoadBalancerListenerSSLCertificateRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the SetLoadBalancerListenerSSLCertificate operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.SetLoadBalancerListenerSSLCertificate"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginSetLoadBalancerListenerSSLCertificate.</param>
///
/// <returns>Returns a SetLoadBalancerListenerSSLCertificateResult from AmazonElasticLoadBalancing.</returns>
SetLoadBalancerListenerSSLCertificateResponse EndSetLoadBalancerListenerSSLCertificate(IAsyncResult asyncResult);
#endregion
#region CreateLBCookieStickinessPolicy
/// <summary>
/// <para> Generates a stickiness policy with sticky session lifetimes controlled by the lifetime of the browser (user-agent) or a specified
/// expiration period. This policy can be associated only with HTTP/HTTPS listeners. </para> <para> When a LoadBalancer implements this policy,
/// the LoadBalancer uses a special cookie to track the backend server instance for each request. When the LoadBalancer receives a request, it
/// first checks to see if this cookie is present in the request. If so, the LoadBalancer sends the request to the application server specified
/// in the cookie. If not, the LoadBalancer sends the request to a server that is chosen based on the existing load balancing algorithm. </para>
/// <para> A cookie is inserted into the response for binding subsequent requests from the same user to that server. The validity of the cookie
/// is based on the cookie expiration time, which is specified in the policy configuration. </para>
/// </summary>
///
/// <param name="createLBCookieStickinessPolicyRequest">Container for the necessary parameters to execute the CreateLBCookieStickinessPolicy
/// service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the CreateLBCookieStickinessPolicy service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="DuplicatePolicyNameException"/>
/// <exception cref="TooManyPoliciesException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
CreateLBCookieStickinessPolicyResponse CreateLBCookieStickinessPolicy(CreateLBCookieStickinessPolicyRequest createLBCookieStickinessPolicyRequest);
/// <summary>
/// Initiates the asynchronous execution of the CreateLBCookieStickinessPolicy operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLBCookieStickinessPolicy"/>
/// </summary>
///
/// <param name="createLBCookieStickinessPolicyRequest">Container for the necessary parameters to execute the CreateLBCookieStickinessPolicy
/// operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndCreateLBCookieStickinessPolicy operation.</returns>
IAsyncResult BeginCreateLBCookieStickinessPolicy(CreateLBCookieStickinessPolicyRequest createLBCookieStickinessPolicyRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateLBCookieStickinessPolicy operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLBCookieStickinessPolicy"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateLBCookieStickinessPolicy.</param>
///
/// <returns>Returns a CreateLBCookieStickinessPolicyResult from AmazonElasticLoadBalancing.</returns>
CreateLBCookieStickinessPolicyResponse EndCreateLBCookieStickinessPolicy(IAsyncResult asyncResult);
#endregion
#region AttachLoadBalancerToSubnets
/// <summary>
/// <para> Adds one or more subnets to the set of configured subnets in the VPC for the LoadBalancer. </para> <para> The Loadbalancers evenly
/// distribute requests across all of the registered subnets. </para>
/// </summary>
///
/// <param name="attachLoadBalancerToSubnetsRequest">Container for the necessary parameters to execute the AttachLoadBalancerToSubnets service
/// method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the AttachLoadBalancerToSubnets service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidSubnetException"/>
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
/// <exception cref="SubnetNotFoundException"/>
AttachLoadBalancerToSubnetsResponse AttachLoadBalancerToSubnets(AttachLoadBalancerToSubnetsRequest attachLoadBalancerToSubnetsRequest);
/// <summary>
/// Initiates the asynchronous execution of the AttachLoadBalancerToSubnets operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.AttachLoadBalancerToSubnets"/>
/// </summary>
///
/// <param name="attachLoadBalancerToSubnetsRequest">Container for the necessary parameters to execute the AttachLoadBalancerToSubnets operation
/// on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndAttachLoadBalancerToSubnets operation.</returns>
IAsyncResult BeginAttachLoadBalancerToSubnets(AttachLoadBalancerToSubnetsRequest attachLoadBalancerToSubnetsRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the AttachLoadBalancerToSubnets operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.AttachLoadBalancerToSubnets"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginAttachLoadBalancerToSubnets.</param>
///
/// <returns>Returns a AttachLoadBalancerToSubnetsResult from AmazonElasticLoadBalancing.</returns>
AttachLoadBalancerToSubnetsResponse EndAttachLoadBalancerToSubnets(IAsyncResult asyncResult);
#endregion
#region CreateAppCookieStickinessPolicy
/// <summary>
/// <para> Generates a stickiness policy with sticky session lifetimes that follow that of an application-generated cookie. This policy can be
/// associated only with HTTP/HTTPS listeners. </para> <para> This policy is similar to the policy created by CreateLBCookieStickinessPolicy,
/// except that the lifetime of the special Elastic Load Balancing cookie follows the lifetime of the application-generated cookie specified in
/// the policy configuration. The LoadBalancer only inserts a new stickiness cookie when the application response includes a new application
/// cookie. </para> <para> If the application cookie is explicitly removed or expires, the session stops being sticky until a new application
/// cookie is issued. </para> <para><b>NOTE:</b> An application client must receive and send two cookies: the application-generated cookie and
/// the special Elastic Load Balancing cookie named AWSELB. This is the default behavior for many common web browsers. </para>
/// </summary>
///
/// <param name="createAppCookieStickinessPolicyRequest">Container for the necessary parameters to execute the CreateAppCookieStickinessPolicy
/// service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the CreateAppCookieStickinessPolicy service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="DuplicatePolicyNameException"/>
/// <exception cref="TooManyPoliciesException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
CreateAppCookieStickinessPolicyResponse CreateAppCookieStickinessPolicy(CreateAppCookieStickinessPolicyRequest createAppCookieStickinessPolicyRequest);
/// <summary>
/// Initiates the asynchronous execution of the CreateAppCookieStickinessPolicy operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateAppCookieStickinessPolicy"/>
/// </summary>
///
/// <param name="createAppCookieStickinessPolicyRequest">Container for the necessary parameters to execute the CreateAppCookieStickinessPolicy
/// operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndCreateAppCookieStickinessPolicy operation.</returns>
IAsyncResult BeginCreateAppCookieStickinessPolicy(CreateAppCookieStickinessPolicyRequest createAppCookieStickinessPolicyRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateAppCookieStickinessPolicy operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateAppCookieStickinessPolicy"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateAppCookieStickinessPolicy.</param>
///
/// <returns>Returns a CreateAppCookieStickinessPolicyResult from AmazonElasticLoadBalancing.</returns>
CreateAppCookieStickinessPolicyResponse EndCreateAppCookieStickinessPolicy(IAsyncResult asyncResult);
#endregion
#region RegisterInstancesWithLoadBalancer
/// <summary>
/// <para> Adds new instances to the LoadBalancer. </para> <para> Once the instance is registered, it starts receiving traffic and requests from
/// the LoadBalancer. Any instance that is not in any of the Availability Zones registered for the LoadBalancer will be moved to the
/// <i>OutOfService</i> state. It will move to the <i>InService</i> state when the Availability Zone is added to the LoadBalancer. </para>
/// <para><b>NOTE:</b> In order for this call to be successful, the client must have created the LoadBalancer. The client must provide the same
/// account credentials as those that were used to create the LoadBalancer. </para> <para><b>NOTE:</b> Completion of this API does not guarantee
/// that operation has completed. Rather, it means that the request has been registered and the changes will happen shortly. </para>
/// </summary>
///
/// <param name="registerInstancesWithLoadBalancerRequest">Container for the necessary parameters to execute the
/// RegisterInstancesWithLoadBalancer service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the RegisterInstancesWithLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="LoadBalancerNotFoundException"/>
/// <exception cref="InvalidInstanceException"/>
RegisterInstancesWithLoadBalancerResponse RegisterInstancesWithLoadBalancer(RegisterInstancesWithLoadBalancerRequest registerInstancesWithLoadBalancerRequest);
/// <summary>
/// Initiates the asynchronous execution of the RegisterInstancesWithLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.RegisterInstancesWithLoadBalancer"/>
/// </summary>
///
/// <param name="registerInstancesWithLoadBalancerRequest">Container for the necessary parameters to execute the
/// RegisterInstancesWithLoadBalancer operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndRegisterInstancesWithLoadBalancer operation.</returns>
IAsyncResult BeginRegisterInstancesWithLoadBalancer(RegisterInstancesWithLoadBalancerRequest registerInstancesWithLoadBalancerRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the RegisterInstancesWithLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.RegisterInstancesWithLoadBalancer"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginRegisterInstancesWithLoadBalancer.</param>
///
/// <returns>Returns a RegisterInstancesWithLoadBalancerResult from AmazonElasticLoadBalancing.</returns>
RegisterInstancesWithLoadBalancerResponse EndRegisterInstancesWithLoadBalancer(IAsyncResult asyncResult);
#endregion
#region ApplySecurityGroupsToLoadBalancer
/// <summary>
/// <para> Associates one or more security groups with your LoadBalancer in VPC. The provided security group IDs will override any currently
/// applied security groups. </para>
/// </summary>
///
/// <param name="applySecurityGroupsToLoadBalancerRequest">Container for the necessary parameters to execute the
/// ApplySecurityGroupsToLoadBalancer service method on AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the ApplySecurityGroupsToLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="InvalidConfigurationRequestException"/>
/// <exception cref="InvalidSecurityGroupException"/>
/// <exception cref="LoadBalancerNotFoundException"/>
ApplySecurityGroupsToLoadBalancerResponse ApplySecurityGroupsToLoadBalancer(ApplySecurityGroupsToLoadBalancerRequest applySecurityGroupsToLoadBalancerRequest);
/// <summary>
/// Initiates the asynchronous execution of the ApplySecurityGroupsToLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.ApplySecurityGroupsToLoadBalancer"/>
/// </summary>
///
/// <param name="applySecurityGroupsToLoadBalancerRequest">Container for the necessary parameters to execute the
/// ApplySecurityGroupsToLoadBalancer operation on AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndApplySecurityGroupsToLoadBalancer operation.</returns>
IAsyncResult BeginApplySecurityGroupsToLoadBalancer(ApplySecurityGroupsToLoadBalancerRequest applySecurityGroupsToLoadBalancerRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ApplySecurityGroupsToLoadBalancer operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.ApplySecurityGroupsToLoadBalancer"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginApplySecurityGroupsToLoadBalancer.</param>
///
/// <returns>Returns a ApplySecurityGroupsToLoadBalancerResult from AmazonElasticLoadBalancing.</returns>
ApplySecurityGroupsToLoadBalancerResponse EndApplySecurityGroupsToLoadBalancer(IAsyncResult asyncResult);
#endregion
#region DescribeLoadBalancers
/// <summary>
/// <para> Returns detailed configuration information for the specified LoadBalancers. If no LoadBalancers are specified, the operation returns
/// configuration information for all LoadBalancers created by the caller. </para> <para><b>NOTE:</b> The client must have created the specified
/// input LoadBalancers in order to retrieve this information; the client must provide the same account credentials as those that were used to
/// create the LoadBalancer. </para>
/// </summary>
///
/// <param name="describeLoadBalancersRequest">Container for the necessary parameters to execute the DescribeLoadBalancers service method on
/// AmazonElasticLoadBalancing.</param>
///
/// <returns>The response from the DescribeLoadBalancers service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="LoadBalancerNotFoundException"/>
DescribeLoadBalancersResponse DescribeLoadBalancers(DescribeLoadBalancersRequest describeLoadBalancersRequest);
/// <summary>
/// Initiates the asynchronous execution of the DescribeLoadBalancers operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeLoadBalancers"/>
/// </summary>
///
/// <param name="describeLoadBalancersRequest">Container for the necessary parameters to execute the DescribeLoadBalancers operation on
/// AmazonElasticLoadBalancing.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndDescribeLoadBalancers operation.</returns>
IAsyncResult BeginDescribeLoadBalancers(DescribeLoadBalancersRequest describeLoadBalancersRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DescribeLoadBalancers operation.
/// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeLoadBalancers"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeLoadBalancers.</param>
///
/// <returns>Returns a DescribeLoadBalancersResult from AmazonElasticLoadBalancing.</returns>
DescribeLoadBalancersResponse EndDescribeLoadBalancers(IAsyncResult asyncResult);
/// <summary>
/// <para> Returns detailed configuration information for the specified LoadBalancers. If no LoadBalancers are specified, the operation returns
/// configuration information for all LoadBalancers created by the caller. </para> <para><b>NOTE:</b> The client must have created the specified
/// input LoadBalancers in order to retrieve this information; the client must provide the same account credentials as those that were used to
/// create the LoadBalancer. </para>
/// </summary>
///
/// <returns>The response from the DescribeLoadBalancers service method, as returned by AmazonElasticLoadBalancing.</returns>
///
/// <exception cref="LoadBalancerNotFoundException"/>
DescribeLoadBalancersResponse DescribeLoadBalancers();
#endregion
}
}
| 66.883503 | 199 | 0.713496 | [
"Apache-2.0"
] | mahanthbeeraka/dataservices-sdk-dotnet | AWSSDK/Amazon.ElasticLoadBalancing/AmazonElasticLoadBalancing.cs | 78,655 | C# |
using System;
using Rhino.ServiceBus.Impl;
namespace Rhino.ServiceBus.Internal
{
public interface ITransport : IDisposable
{
void Start();
Endpoint Endpoint { get; }
int ThreadCount { get; }
/// <summary>
/// The information for the message currently being received and handled by the transport.
/// </summary>
CurrentMessageInformation CurrentMessageInformation { get; }
void Send(Endpoint destination, object[] msgs);
void Send(Endpoint endpoint, DateTime processAgainAt, object[] msgs);
void Reply(params object[] messages);
event Action<CurrentMessageInformation> MessageSent;
event Func<CurrentMessageInformation,bool> AdministrativeMessageArrived;
event Func<CurrentMessageInformation, bool> MessageArrived;
event Action<CurrentMessageInformation, Exception> MessageSerializationException;
event Action<CurrentMessageInformation, Exception> MessageProcessingFailure;
event Action<CurrentMessageInformation, Exception> MessageProcessingCompleted;
event Action<CurrentMessageInformation> BeforeMessageTransactionRollback;
event Action<CurrentMessageInformation> BeforeMessageTransactionCommit;
event Action<CurrentMessageInformation, Exception> AdministrativeMessageProcessingCompleted;
event Action Started;
}
}
| 33.25 | 101 | 0.701299 | [
"BSD-3-Clause"
] | EzyWebwerkstaden/rhino-esb | Rhino.ServiceBus/Internal/ITransport.cs | 1,463 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pokladna
{
public interface IRepos
{
List<PokladniZaznam> NactiVse();
List<PokladniZaznam> NactiMesic(int rok, int mesic, string sloupecTrideni, bool sestupne);
PokladniZaznam NactiZaznam(int idPokladniZaznam);
PokladniZaznam VytvorZaznam(PokladniZaznam pokladniZaznam);
void UpravZaznam(PokladniZaznam pokladniZaznam);
void SmazZaznam(PokladniZaznam pokladniZaznam);
}
}
| 29.473684 | 98 | 0.742857 | [
"MIT"
] | SmurFoun/Pokladna | Pokladna/Pokladna/IRepos.cs | 562 | C# |
// Copyright (c) 2017 Andrew Vardeman. Published under the MIT license.
// See license.txt in the FileSharper distribution or repository for the
// full text of the license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using FileSharperCore.Util;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
namespace FileSharperCore.Conditions.Text
{
public class CountComparisonParameters
{
[PropertyOrder(1, UsageContextEnum.Both)]
public ComparisonType ComparisonType { get; set; } = ComparisonType.GreaterThan;
[PropertyOrder(2, UsageContextEnum.Both)]
public int Count { get; set; } = 300;
}
public class WordCountCondition : ConditionBase
{
private CountComparisonParameters m_Parameters = new CountComparisonParameters();
public override string Name => "Word Count";
public override string Category => "Text";
public override string Description => "Compares the word count to the specified value";
public override object Parameters => m_Parameters;
public override int ColumnCount => 1;
public override string[] ColumnHeaders => new string[] { "Word Count" };
public override MatchResult Matches(FileInfo file, Dictionary<Type, IFileCache> fileCaches, CancellationToken token)
{
int wordCount = 0;
MatchResultType resultType = MatchResultType.NotApplicable;
try
{
using (StreamReader reader = new StreamReader(file.FullName))
{
wordCount = TextUtil.GetWordCount(reader, token);
}
resultType = CompareUtil.Compare(wordCount, m_Parameters.ComparisonType, m_Parameters.Count);
}
catch (Exception ex)
{
}
return new MatchResult(resultType, wordCount.ToString());
}
}
}
| 33 | 124 | 0.655367 | [
"MIT"
] | adv12/FileSharper | src/FileSharper/FileSharperCore/Conditions/Text/WordCountCondition.cs | 1,949 | C# |
using System;
namespace Cybtans.Services.DependencyInjection
{
public interface ITypeResolver
{
Type ResolveImplementer(Type contract, out LifeType? lifeType);
}
}
| 15.666667 | 71 | 0.718085 | [
"MIT"
] | ansel86castro/cybtans-sdk | CybtansSDK/Cybtans.Services/DependencyInjection/ITypeResolver.cs | 190 | C# |
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Basket.API.Infrastructure.Filters;
using Basket.API.Infrastructure.Middlewares;
using Basket.API.IntegrationEvents.EventHandling;
using Basket.API.IntegrationEvents.Events;
using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.ServiceBus;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus;
using Microsoft.eShopOnContainers.Services.Basket.API.Controllers;
using Microsoft.eShopOnContainers.Services.Basket.API.Infrastructure.Repositories;
using Microsoft.eShopOnContainers.Services.Basket.API.IntegrationEvents.EventHandling;
using Microsoft.eShopOnContainers.Services.Basket.API.IntegrationEvents.Events;
using Microsoft.eShopOnContainers.Services.Basket.API.Model;
using Microsoft.eShopOnContainers.Services.Basket.API.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using RabbitMQ.Client;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using GrpcBasket;
using Microsoft.AspNetCore.Http.Features;
using Serilog;
using Newtonsoft.Json.Converters;
namespace Microsoft.eShopOnContainers.Services.Basket.API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public virtual IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddGrpc(options =>
{
options.EnableDetailedErrors = true;
});
RegisterAppInsights(services);
services.AddControllers(options =>
{
options.Filters.Add(typeof(HttpGlobalExceptionFilter));
options.Filters.Add(typeof(ValidateModelStateFilter));
}) // Added for functional tests
.AddApplicationPart(typeof(BasketController).Assembly)
.AddNewtonsoftJson(options => options.SerializerSettings.Converters.Add(new StringEnumConverter()));
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "eShopOnContainers - Basket HTTP API",
Version = "v1",
Description = "The Basket Service HTTP API"
});
options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows()
{
Implicit = new OpenApiOAuthFlow()
{
AuthorizationUrl = new Uri($"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize"),
TokenUrl = new Uri($"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/token"),
Scopes = new Dictionary<string, string>()
{
{ "basket", "Basket API" }
}
}
}
});
options.OperationFilter<AuthorizeCheckOperationFilter>();
});
services.AddSwaggerGenNewtonsoftSupport();
ConfigureAuthService(services);
services.AddCustomHealthCheck(Configuration);
services.Configure<BasketSettings>(Configuration);
//By connecting here we are making sure that our service
//cannot start until redis is ready. This might slow down startup,
//but given that there is a delay on resolving the ip address
//and then creating the connection it seems reasonable to move
//that cost to startup instead of having the first request pay the
//penalty.
services.AddSingleton<ConnectionMultiplexer>(sp =>
{
var settings = sp.GetRequiredService<IOptions<BasketSettings>>().Value;
return ConnectionMultiplexer.Connect(settings.ConnectionString);
});
if (Configuration.GetValue<bool>("AzureServiceBusEnabled"))
{
services.AddSingleton<IServiceBusPersisterConnection>(sp =>
{
var logger = sp.GetRequiredService<ILogger<DefaultServiceBusPersisterConnection>>();
var serviceBusConnectionString = Configuration["EventBusConnection"];
var serviceBusConnection = new ServiceBusConnectionStringBuilder(serviceBusConnectionString);
return new DefaultServiceBusPersisterConnection(serviceBusConnection, logger);
});
}
else
{
services.AddSingleton<IRabbitMQPersistentConnection>(sp =>
{
var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>();
var factory = new ConnectionFactory()
{
HostName = Configuration["EventBusConnection"],
DispatchConsumersAsync = true
};
if (!string.IsNullOrEmpty(Configuration["EventBusUserName"]))
{
factory.UserName = Configuration["EventBusUserName"];
}
if (!string.IsNullOrEmpty(Configuration["EventBusPassword"]))
{
factory.Password = Configuration["EventBusPassword"];
}
var retryCount = 5;
if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
{
retryCount = int.Parse(Configuration["EventBusRetryCount"]);
}
return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount);
});
}
RegisterEventBus(services);
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.SetIsOriginAllowed((host) => true)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddTransient<IBasketRepository, RedisBasketRepository>();
services.AddTransient<IIdentityService, IdentityService>();
services.AddOptions();
var container = new ContainerBuilder();
container.Populate(services);
return new AutofacServiceProvider(container.Build());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
var pathBase = Configuration["PATH_BASE"];
if (!string.IsNullOrEmpty(pathBase))
{
app.UsePathBase(pathBase);
}
app.UseSwagger()
.UseSwaggerUI(setup =>
{
setup.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Basket.API V1");
setup.OAuthClientId("basketswaggerui");
setup.OAuthAppName("Basket Swagger UI");
});
app.UseRouting();
ConfigureAuth(app);
app.UseStaticFiles();
app.UseCors("CorsPolicy");
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<BasketService>();
endpoints.MapDefaultControllerRoute();
endpoints.MapControllers();
endpoints.MapGet("/_proto/", async ctx =>
{
ctx.Response.ContentType = "text/plain";
using var fs = new FileStream(Path.Combine(env.ContentRootPath, "Proto", "basket.proto"), FileMode.Open, FileAccess.Read);
using var sr = new StreamReader(fs);
while (!sr.EndOfStream)
{
var line = await sr.ReadLineAsync();
if (line != "/* >>" || line != "<< */")
{
await ctx.Response.WriteAsync(line);
}
}
});
endpoints.MapHealthChecks("/hc", new HealthCheckOptions()
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
endpoints.MapHealthChecks("/liveness", new HealthCheckOptions
{
Predicate = r => r.Name.Contains("self")
});
});
ConfigureEventBus(app);
}
private void RegisterAppInsights(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.AddApplicationInsightsKubernetesEnricher();
}
private void ConfigureAuthService(IServiceCollection services)
{
// prevent from mapping "sub" claim to nameidentifier.
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub");
var identityUrl = Configuration.GetValue<string>("IdentityUrl");
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = identityUrl;
options.RequireHttpsMetadata = false;
options.Audience = "basket";
});
}
protected virtual void ConfigureAuth(IApplicationBuilder app)
{
if (Configuration.GetValue<bool>("UseLoadTest"))
{
app.UseMiddleware<ByPassAuthMiddleware>();
}
app.UseAuthentication();
app.UseAuthorization();
}
private void RegisterEventBus(IServiceCollection services)
{
var subscriptionClientName = Configuration["SubscriptionClientName"];
if (Configuration.GetValue<bool>("AzureServiceBusEnabled"))
{
services.AddSingleton<IEventBus, EventBusServiceBus>(sp =>
{
var serviceBusPersisterConnection = sp.GetRequiredService<IServiceBusPersisterConnection>();
var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>();
var logger = sp.GetRequiredService<ILogger<EventBusServiceBus>>();
var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();
return new EventBusServiceBus(serviceBusPersisterConnection, logger,
eventBusSubcriptionsManager, subscriptionClientName, iLifetimeScope);
});
}
else
{
services.AddSingleton<IEventBus, EventBusRabbitMQ>(sp =>
{
var rabbitMQPersistentConnection = sp.GetRequiredService<IRabbitMQPersistentConnection>();
var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>();
var logger = sp.GetRequiredService<ILogger<EventBusRabbitMQ>>();
var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();
var retryCount = 5;
if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
{
retryCount = int.Parse(Configuration["EventBusRetryCount"]);
}
return new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, iLifetimeScope, eventBusSubcriptionsManager, subscriptionClientName, retryCount);
});
}
services.AddSingleton<IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>();
services.AddTransient<ProductPriceChangedIntegrationEventHandler>();
services.AddTransient<OrderStartedIntegrationEventHandler>();
}
private void ConfigureEventBus(IApplicationBuilder app)
{
var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
eventBus.Subscribe<ProductPriceChangedIntegrationEvent, ProductPriceChangedIntegrationEventHandler>();
eventBus.Subscribe<OrderStartedIntegrationEvent, OrderStartedIntegrationEventHandler>();
}
}
public static class CustomExtensionMethods
{
public static IServiceCollection AddCustomHealthCheck(this IServiceCollection services, IConfiguration configuration)
{
var hcBuilder = services.AddHealthChecks();
hcBuilder.AddCheck("self", () => HealthCheckResult.Healthy());
hcBuilder
.AddRedis(
configuration["ConnectionString"],
name: "redis-check",
tags: new string[] { "redis" });
if (configuration.GetValue<bool>("AzureServiceBusEnabled"))
{
hcBuilder
.AddAzureServiceBusTopic(
configuration["EventBusConnection"],
topicName: "eshop_event_bus",
name: "basket-servicebus-check",
tags: new string[] { "servicebus" });
}
else
{
hcBuilder
.AddRabbitMQ(
$"amqp://{configuration["EventBusConnection"]}",
name: "basket-rabbitmqbus-check",
tags: new string[] { "rabbitmqbus" });
}
return services;
}
}
}
| 41.07337 | 167 | 0.587297 | [
"MIT"
] | AZ2021lab/mslearn-aspnet-core | modules/microservices-logging-aspnet-core/src/src/Services/Basket/Basket.API/Startup.cs | 15,117 | 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.Kusto.Cmdlets
{
using static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Extensions;
/// <summary>
/// Diagnoses network connectivity status for external resources on which the service is dependent on.
/// </summary>
/// <remarks>
/// [OpenAPI] Clusters_DiagnoseVirtualNetwork=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/Clusters/{clusterName}/diagnoseVirtualNetwork"
/// </remarks>
[global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzKustoDiagnoseClusterVirtualNetwork_DiagnoseViaIdentity", SupportsShouldProcess = true)]
[global::System.Management.Automation.OutputType(typeof(string))]
[global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Description(@"Diagnoses network connectivity status for external resources on which the service is dependent on.")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Generated]
public partial class InvokeAzKustoDiagnoseClusterVirtualNetwork_DiagnoseViaIdentity : global::System.Management.Automation.PSCmdlet,
Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener
{
/// <summary>A unique id generatd for the this cmdlet when it is instantiated.</summary>
private string __correlationId = System.Guid.NewGuid().ToString();
/// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary>
private global::System.Management.Automation.InvocationInfo __invocationInfo;
/// <summary>A unique id generatd for the this cmdlet when ProcessRecord() is called.</summary>
private string __processRecordId;
/// <summary>
/// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation.
/// </summary>
private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource();
/// <summary>when specified, runs this cmdlet as a PowerShell job</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)]
public global::System.Management.Automation.SwitchParameter AsJob { get; set; }
/// <summary>Wait for .NET debugger to attach</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)]
public global::System.Management.Automation.SwitchParameter Break { get; set; }
/// <summary>The reference to the client API class.</summary>
public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Kusto Client => Microsoft.Azure.PowerShell.Cmdlets.Kusto.Module.Instance.ClientAPI;
/// <summary>
/// The credentials, account, tenant, and subscription used for communication with Azure
/// </summary>
[global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")]
[global::System.Management.Automation.ValidateNotNull]
[global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Azure)]
public global::System.Management.Automation.PSObject DefaultProfile { get; set; }
/// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)]
public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; }
/// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)]
public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; }
/// <summary>Backing field for <see cref="InputObject" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.IKustoIdentity _inputObject;
/// <summary>Identity Parameter</summary>
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)]
[global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Path)]
public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.IKustoIdentity InputObject { get => this._inputObject; set => this._inputObject = value; }
/// <summary>Accessor for our copy of the InvocationInfo.</summary>
public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } }
/// <summary>
/// <see cref="IEventListener" /> cancellation delegate. Stops the cmdlet when called.
/// </summary>
global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel;
/// <summary><see cref="IEventListener" /> cancellation token.</summary>
global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener.Token => _cancellationTokenSource.Token;
/// <summary>
/// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue
/// asynchronously.
/// </summary>
[global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)]
public global::System.Management.Automation.SwitchParameter NoWait { get; set; }
/// <summary>
/// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.HttpPipeline" /> that the remote call will use.
/// </summary>
private Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.HttpPipeline Pipeline { get; set; }
/// <summary>The URI for the proxy server to use</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)]
public global::System.Uri Proxy { get; set; }
/// <summary>Credentials for a proxy server to use for the remote call</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)]
public global::System.Management.Automation.PSCredential ProxyCredential { get; set; }
/// <summary>Use the default credentials for the proxy</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)]
public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; }
/// <summary>
/// <c>overrideOnDefault</c> will be called before the regular onDefault has been processed, allowing customization of what
/// happens on that response. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.ICloudError"
/// /> from the remote call</param>
/// <param name="returnNow">/// Determines if the rest of the onDefault method should be processed, or if the method should
/// return immediately (set to true to skip further processing )</param>
partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.ICloudError> response, ref global::System.Threading.Tasks.Task<bool> returnNow);
/// <summary>
/// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens
/// on that response. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.IDiagnoseVirtualNetworkResult"
/// /> from the remote call</param>
/// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return
/// immediately (set to true to skip further processing )</param>
partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.IDiagnoseVirtualNetworkResult> response, ref global::System.Threading.Tasks.Task<bool> returnNow);
/// <summary>
/// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet)
/// </summary>
protected override void BeginProcessing()
{
Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials);
if (Break)
{
Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.AttachDebugger.Break();
}
((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
/// <summary>Creates a duplicate instance of this cmdlet (via JSON serialization).</summary>
/// <returns>
/// a duplicate instance of InvokeAzKustoDiagnoseClusterVirtualNetwork_DiagnoseViaIdentity
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Cmdlets.InvokeAzKustoDiagnoseClusterVirtualNetwork_DiagnoseViaIdentity Clone()
{
var clone = new InvokeAzKustoDiagnoseClusterVirtualNetwork_DiagnoseViaIdentity();
clone.__correlationId = this.__correlationId;
clone.__processRecordId = this.__processRecordId;
clone.DefaultProfile = this.DefaultProfile;
clone.InvocationInformation = this.InvocationInformation;
clone.Proxy = this.Proxy;
clone.Pipeline = this.Pipeline;
clone.AsJob = this.AsJob;
clone.Break = this.Break;
clone.ProxyCredential = this.ProxyCredential;
clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials;
clone.HttpPipelinePrepend = this.HttpPipelinePrepend;
clone.HttpPipelineAppend = this.HttpPipelineAppend;
return clone;
}
/// <summary>Performs clean-up after the command execution</summary>
protected override void EndProcessing()
{
((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
/// <summary>
/// Intializes a new instance of the <see cref="InvokeAzKustoDiagnoseClusterVirtualNetwork_DiagnoseViaIdentity" /> cmdlet
/// class.
/// </summary>
public InvokeAzKustoDiagnoseClusterVirtualNetwork_DiagnoseViaIdentity()
{
}
/// <summary>Handles/Dispatches events during the call to the REST service.</summary>
/// <param name="id">The message id</param>
/// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param>
/// <param name="messageData">Detailed message data for the message event.</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed.
/// </returns>
async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.EventData> messageData)
{
using( NoSynchronizationContext )
{
if (token.IsCancellationRequested)
{
return ;
}
switch ( id )
{
case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Verbose:
{
WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Warning:
{
WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Information:
{
// When an operation supports asjob, Information messages must go thru verbose.
WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Debug:
{
WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Error:
{
WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) );
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.DelayBeforePolling:
{
if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait"))
{
var data = messageData();
if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response)
{
var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation");
var location = response.GetFirstHeader(@"Location");
var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation;
WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell.AsyncOperationResponse { Target = uri });
// do nothing more.
data.Cancel();
return;
}
}
break;
}
}
await Microsoft.Azure.PowerShell.Cmdlets.Kusto.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null );
if (token.IsCancellationRequested)
{
return ;
}
WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}");
}
}
/// <summary>Performs execution of the command.</summary>
protected override void ProcessRecord()
{
((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
__processRecordId = System.Guid.NewGuid().ToString();
try
{
// work
if (ShouldProcess($"Call remote 'ClustersDiagnoseVirtualNetwork' operation"))
{
if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob"))
{
var instance = this.Clone();
var job = new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel);
JobRepository.Add(job);
var task = instance.ProcessRecordAsync();
job.Monitor(task);
WriteObject(job);
}
else
{
using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token) )
{
asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token);
}
}
}
}
catch (global::System.AggregateException aggregateException)
{
// unroll the inner exceptions to get the root cause
foreach( var innerException in aggregateException.Flatten().InnerExceptions )
{
((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
// Write exception out to error channel.
WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) );
}
}
catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null)
{
((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
// Write exception out to error channel.
WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) );
}
finally
{
((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletProcessRecordEnd).Wait();
}
}
/// <summary>Performs execution of the command, working asynchronously if required.</summary>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
protected async global::System.Threading.Tasks.Task ProcessRecordAsync()
{
using( NoSynchronizationContext )
{
await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Kusto.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName);
if (null != HttpPipelinePrepend)
{
Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend);
}
if (null != HttpPipelineAppend)
{
Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend);
}
// get the client instance
try
{
await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
if (InputObject?.Id != null)
{
await this.Client.ClustersDiagnoseVirtualNetworkViaIdentity(InputObject.Id, onOk, onDefault, this, Pipeline);
}
else
{
// try to call with PATH parameters from Input Object
if (null == InputObject.ResourceGroupName)
{
ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) );
}
if (null == InputObject.ClusterName)
{
ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ClusterName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) );
}
if (null == InputObject.SubscriptionId)
{
ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) );
}
await this.Client.ClustersDiagnoseVirtualNetwork(InputObject.ResourceGroupName ?? null, InputObject.ClusterName ?? null, InputObject.SubscriptionId ?? null, onOk, onDefault, this, Pipeline);
}
await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
catch (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.UndeclaredResponseException urexception)
{
WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { })
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action }
});
}
finally
{
await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletProcessRecordAsyncEnd);
}
}
}
/// <summary>Interrupts currently running code within the command.</summary>
protected override void StopProcessing()
{
((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Cancel();
base.StopProcessing();
}
/// <summary>
/// a delegate that is called when the remote service returns default (any response code not handled elsewhere).
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.ICloudError"
/// /> from the remote call</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.ICloudError> response)
{
using( NoSynchronizationContext )
{
var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false);
overrideOnDefault(responseMessage, response, ref _returnNow);
// if overrideOnDefault has returned true, then return right away.
if ((null != _returnNow && await _returnNow))
{
return ;
}
// Error Response : default
var code = (await response)?.Code;
var message = (await response)?.Message;
if ((null == code || null == message))
{
// Unrecognized Response. Create an error record based on what we have.
var ex = new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.RestException<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.ICloudError>(responseMessage, await response);
WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { })
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action }
});
}
else
{
WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { })
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty }
});
}
}
}
/// <summary>a delegate that is called when the remote service returns 200 (OK).</summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.IDiagnoseVirtualNetworkResult"
/// /> from the remote call</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.IDiagnoseVirtualNetworkResult> response)
{
using( NoSynchronizationContext )
{
var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false);
overrideOnOk(responseMessage, response, ref _returnNow);
// if overrideOnOk has returned true, then return right away.
if ((null != _returnNow && await _returnNow))
{
return ;
}
// onOk - response for 200 / application/json
// response should be returning an array of some kind. +Pageable
// nested-array / findings / <none>
WriteObject((await response).Finding, true);
}
}
}
} | 72.717149 | 451 | 0.652925 | [
"MIT"
] | Arsasana/azure-powershell | src/Kusto/generated/cmdlets/InvokeAzKustoDiagnoseClusterVirtualNetwork_DiagnoseViaIdentity.cs | 32,202 | C# |
[Serializable]
public class SharedPartnerNPCActionBehaviorType : SharedVariable<PartnerNPCActionBehaviorType> // TypeDefIndex: 6443
{
// Methods
// RVA: 0x1C8E900 Offset: 0x1C8EA01 VA: 0x1C8E900 Slot: 3
public override string ToString() { }
// RVA: 0x1C8E990 Offset: 0x1C8EA91 VA: 0x1C8E990
public static SharedPartnerNPCActionBehaviorType op_Implicit(PartnerNPCActionBehaviorType value) { }
// RVA: 0x1C8EA40 Offset: 0x1C8EB41 VA: 0x1C8EA40
public void .ctor() { }
}
| 29.9375 | 116 | 0.778706 | [
"MIT"
] | SinsofSloth/RF5-global-metadata | _no_namespace/SharedPartnerNPCActionBehaviorType.cs | 479 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using RogueSheep.RandomNumbers;
namespace RogueSheep.Maps.Generation
{
public class CellularAutomaton : IMapGenerator<bool>
{
private readonly IRandom rng;
private readonly CellularAutomatonOptions options;
public CellularAutomaton() : this(new CellularAutomatonOptions()) {}
public CellularAutomaton(IRandom rng) : this(rng, new CellularAutomatonOptions()) {}
public CellularAutomaton(CellularAutomatonOptions options)
{
this.rng = new PCGRandom();
this.options = options;
}
public CellularAutomaton(IRandom rng, CellularAutomatonOptions options)
{
this.rng = rng;
this.options = options;
}
public GameGrid<bool> Generate(Point2i size)
{
var mapDto = new GameGrid<bool>(size);
// fill 50-50 with alive (true) and dead (false)
for (var i = 0; i < mapDto.Length; i++)
{
mapDto[i] = rng.Next(100) < options.AliveProbabilityAtStart;
}
// generate a few steps
for (var s = 0; s < options.NumberOfSteps; s++)
{
mapDto = ProcessStep(mapDto);
}
if (options.EnsureWalled)
{
mapDto = EnsureWalled(mapDto);
}
if (options.EnsureConnected)
{
mapDto = EnsureConnected(mapDto);
}
return mapDto;
}
private GameGrid<bool> ProcessStep(GameGrid<bool> mapDto)
{
var newGeneration = new GameGrid<bool>(mapDto.Size);
for (var i = 0; i < mapDto.Length; i++)
{
var neighborCount = mapDto.GetNeighborhood(i, true, false).Count(c => c);
if (mapDto[i] && neighborCount >= options.NeighborCountToKeepAlive)
{
newGeneration[i] = true;
}
else if (!mapDto[i] && neighborCount >= options.NeighborCountToMakeAlive)
{
newGeneration[i] = true;
}
}
return newGeneration;
}
private GameGrid<bool> EnsureWalled(GameGrid<bool> mapDto)
{
var newMap = new GameGrid<bool>(mapDto.Size);
for (var i = 0; i < mapDto.Length; i++)
{
newMap[i] = mapDto[i];
}
var maxX = mapDto.Size.X - 1;
var maxY = mapDto.Size.Y - 1;
for (var x = 0; x < maxX; x++)
{
newMap[(x, 0)] = true;
newMap[(x, maxY)] = true;
}
for (var y = 0; y < maxY; y++)
{
newMap[(0, y)] = true;
newMap[(maxX, y)] = true;
}
return newMap;
}
private GameGrid<bool> EnsureConnected(GameGrid<bool> mapDto)
{
var regionList = new Dictionary<int, List<Point2i>>();
var regionCount = 0;
GameGrid<int> regionMap = new GameGrid<int>(mapDto.Size);
for (var i = 0; i < mapDto.Length; i++)
{
regionMap[i] = mapDto[i] ? 0 : -1;
}
while (regionMap.Array.Contains(-1))
{
var newRegionOrigin = regionMap.ClosestPosition((0, 0), (g, p) => g[p] == -1);
var newRegionNumber = ++regionCount;
regionList.Add(newRegionNumber, FloodFill(regionMap, newRegionOrigin, newRegionNumber));
}
while (regionList.Count > 1)
{
// select two regions
var startingRegion = regionList.First().Value;
var endingRegion = regionList.Last().Value;
// select random starting points in both
var startingPoint = startingRegion[rng.Next(startingRegion.Count)];
var regionNumber = regionMap[startingPoint];
var endingPoint = endingRegion[rng.Next(endingRegion.Count)];
var endingRegionNumber = regionMap[endingPoint];
// join them by random walk, removing walls from mapDto
var path = DrunkardWalk(regionMap, startingPoint, endingPoint).ToHashSet();
var regionsTouched = new HashSet<int>();
foreach (var point in path)
{
regionMap[point] = regionNumber;
// check if random walk touches any other regions
var touchedRegions = regionMap.GetNeighborhood(point, -1, false);
regionsTouched.UnionWith(touchedRegions.Where(x => x > 0).ToHashSet());
}
// merge all regions touched
for (var i = 0; i < regionMap.Count(); i++)
{
if (regionsTouched.Contains(regionMap[i]))
{
var region = regionMap[i];
var position = regionMap.IndexToPosition(i);
regionList[region].Remove(position);
regionList[regionNumber].Add(position);
regionMap[i] = regionNumber;
}
}
regionsTouched.Remove(regionNumber);
foreach (var regionTouched in regionsTouched)
{
regionList.Remove(regionTouched);
}
}
var retVal = new GameGrid<bool>(mapDto.Size);
for (var i = 0; i < mapDto.Length; i++)
{
retVal[i] = regionMap[i] == 0;
}
return retVal;
}
private List<Point2i> FloodFill(GameGrid<int> grid, Point2i origin, int newRegionNumber)
{
var newRegion = new List<Point2i>();
var directions = new[] { (0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (-1, -1), (1, -1), (-1, 1) };
grid[origin] = newRegionNumber;
var queue = new Queue<Point2i>();
queue.Enqueue(origin);
newRegion.Add(origin);
while (queue.Count > 0)
{
var p = queue.Dequeue();
foreach (var direction in directions)
{
var newPoint = p + direction;
if (grid.IsInBounds(newPoint) && grid[newPoint] == -1)
{
grid[newPoint] = newRegionNumber;
newRegion.Add(newPoint);
queue.Enqueue(newPoint);
}
}
}
return newRegion;
}
private List<Point2i> DrunkardWalk<T>(GameGrid<T> grid, Point2i origin, Point2i target)
{
var walk = new List<Point2i>();
var currentPoint = origin;
bool canBeVisited(Point2i x) => x.X > 0 && x.X < grid.Size.X - 1 && x.Y > 0 && x.Y < grid.Size.Y - 1;
while (currentPoint != target)
{
walk.Add(currentPoint);
var diffX = target.X - currentPoint.X;
var diffY = target.Y - currentPoint.Y;
var weightPlusX = diffX > 0 ? 4 : 1;
var weightMinusX = diffX < 0 ? 4 : 1;
var weightPlusY = diffY > 0 ? 4 : 1;
var weightMinusY = diffY < 0 ? 4 : 1;
var totalWeight = weightMinusX + weightMinusY + weightPlusX + weightPlusY;
var roll = rng.Next(totalWeight) + 1;
var runningTotal = weightPlusX;
Point2i testPoint;
if (roll <= runningTotal)
{
testPoint = currentPoint + (1, 0);
if (canBeVisited(testPoint))
{
currentPoint = testPoint;
}
continue;
}
runningTotal += weightMinusX;
if (roll <= runningTotal)
{
testPoint = currentPoint + (-1, 0);
if (canBeVisited(testPoint))
{
currentPoint = testPoint;
}
continue;
}
runningTotal += weightPlusY;
if (roll <= runningTotal)
{
testPoint = currentPoint + (0, 1);
if (canBeVisited(testPoint))
{
currentPoint = testPoint;
}
continue;
}
testPoint = currentPoint + (0, -1);
if (canBeVisited(testPoint))
{
currentPoint = testPoint;
}
}
return walk;
}
}
}
| 34.288973 | 113 | 0.465181 | [
"MIT"
] | KarbonKitty/rogue-sheep | RogueSheep/Maps/Generation/CellularAutomaton.cs | 9,018 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace LogJoint.Extensibility
{
public class Model : IModel, IPostprocessingModel
{
public Model(
IInvokeSynchronization threadSync,
Telemetry.ITelemetryCollector telemetryCollector,
Persistence.IWebContentCache webCache,
Persistence.IContentCache contentCache,
Persistence.IStorageManager storageManager,
IBookmarks bookmarks,
ILogSourcesManager sourcesManager,
IModelThreads threads,
ITempFilesManager tempFilesManager,
Preprocessing.IPreprocessingManagerExtensionsRegistry preprocessingManagerExtentionsRegistry,
Preprocessing.ILogSourcesPreprocessingManager logSourcesPreprocessingManager,
Preprocessing.IPreprocessingStepsFactory preprocessingStepsFactory,
Progress.IProgressAggregator progressAggregator,
ILogProviderFactoryRegistry logProviderFactoryRegistry,
IUserDefinedFormatsManager userDefinedFormatsManager,
MRU.IRecentlyUsedEntities mru,
Progress.IProgressAggregatorFactory progressAggregatorsFactory,
IHeartBeatTimer heartbeat,
ILogSourcesController logSourcesController,
IShutdown shutdown,
WebBrowserDownloader.IDownloader webBrowserDownloader,
AppLaunch.ICommandLineHandler commandLineHandler,
Postprocessing.IPostprocessorsManager postprocessorsManager,
Postprocessing.IUserNamesProvider analyticsShortNames,
Analytics.TimeSeries.ITimeSeriesTypesAccess timeSeriesTypes,
Postprocessing.IAggregatingLogSourceNamesProvider logSourceNamesProvider
)
{
this.ModelThreadSynchronization = threadSync;
this.Telemetry = telemetryCollector;
this.WebContentCache = webCache;
this.ContentCache = contentCache;
this.StorageManager = storageManager;
this.Bookmarks = bookmarks;
this.SourcesManager = sourcesManager;
this.Threads = threads;
this.TempFilesManager = tempFilesManager;
this.PreprocessingManagerExtensionsRegistry = preprocessingManagerExtentionsRegistry;
this.PreprocessingStepsFactory = preprocessingStepsFactory;
this.LogSourcesPreprocessingManager = logSourcesPreprocessingManager;
this.ProgressAggregator = progressAggregator;
this.LogProviderFactoryRegistry = logProviderFactoryRegistry;
this.UserDefinedFormatsManager = userDefinedFormatsManager;
this.ProgressAggregatorsFactory = progressAggregatorsFactory;
this.MRU = mru;
this.Heartbeat = heartbeat;
this.LogSourcesController = logSourcesController;
this.Shutdown = shutdown;
this.WebBrowserDownloader = webBrowserDownloader;
this.CommandLineHandler = commandLineHandler;
this.PostprocessorsManager = postprocessorsManager;
this.ShortNames = analyticsShortNames;
this.TimeSeriesTypes = timeSeriesTypes;
this.LogSourceNamesProvider = logSourceNamesProvider;
}
public IInvokeSynchronization ModelThreadSynchronization { get; private set; }
public Telemetry.ITelemetryCollector Telemetry { get; private set; }
public Persistence.IWebContentCache WebContentCache { get; private set; }
public Persistence.IContentCache ContentCache { get; private set; }
public Persistence.IStorageManager StorageManager { get; private set; }
public IBookmarks Bookmarks { get; private set; }
public ILogSourcesManager SourcesManager { get; private set; }
public IModelThreads Threads { get; private set; }
public ITempFilesManager TempFilesManager { get; private set; }
public Preprocessing.IPreprocessingManagerExtensionsRegistry PreprocessingManagerExtensionsRegistry { get; private set; }
public Preprocessing.ILogSourcesPreprocessingManager LogSourcesPreprocessingManager { get; private set; }
public Preprocessing.IPreprocessingStepsFactory PreprocessingStepsFactory { get; private set; }
public Progress.IProgressAggregator ProgressAggregator { get; private set; }
public ILogProviderFactoryRegistry LogProviderFactoryRegistry { get; private set; }
public IUserDefinedFormatsManager UserDefinedFormatsManager { get; private set; }
public MRU.IRecentlyUsedEntities MRU { get; private set; }
public Progress.IProgressAggregatorFactory ProgressAggregatorsFactory { get; private set; }
public IHeartBeatTimer Heartbeat { get; private set; }
public ILogSourcesController LogSourcesController { get; private set; }
public IShutdown Shutdown { get; private set; }
public WebBrowserDownloader.IDownloader WebBrowserDownloader { get; private set; }
public AppLaunch.ICommandLineHandler CommandLineHandler { get; private set; }
public IPostprocessingModel Postprocessing { get { return this; } }
#region IPostprocessingModel
public Postprocessing.IPostprocessorsManager PostprocessorsManager { get; private set; }
public Postprocessing.IUserNamesProvider ShortNames { get; private set; }
public Analytics.TimeSeries.ITimeSeriesTypesAccess TimeSeriesTypes { get; private set; }
public Postprocessing.IAggregatingLogSourceNamesProvider LogSourceNamesProvider { get; private set; }
#endregion
};
}
| 51.44898 | 124 | 0.808409 | [
"MIT"
] | logjointfork/logjoint | trunk/extensibility/Model.cs | 5,044 | C# |
namespace HtmlGenerator
{
public class HtmlObjectElement : HtmlElement
{
public HtmlObjectElement() : base("object") { }
public HtmlObjectElement WithData(string value) => this.WithAttribute(Attribute.Data(value));
public HtmlObjectElement WithForm(string value) => this.WithAttribute(Attribute.Form(value));
public HtmlObjectElement WithHeight(string value) => this.WithAttribute(Attribute.Height(value));
public HtmlObjectElement WithName(string value) => this.WithAttribute(Attribute.Name(value));
public HtmlObjectElement WithType(string value) => this.WithAttribute(Attribute.Type(value));
public HtmlObjectElement WithTypeMustMatch() => this.WithAttribute(Attribute.TypeMustMatch);
public HtmlObjectElement WithUseMap(string value) => this.WithAttribute(Attribute.UseMap(value));
public HtmlObjectElement WithWidth(string value) => this.WithAttribute(Attribute.Width(value));
}
}
| 40.75 | 105 | 0.738241 | [
"MIT"
] | hughbe/HtmlGenerator | src/Elements/HtmlObjectElement.cs | 978 | C# |
// Animancer // https://kybernetik.com.au/animancer // Copyright 2021 Kybernetik //
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Audio;
using UnityEngine.Playables;
using Object = UnityEngine.Object;
namespace Animancer
{
/// <summary>[Pro-Only] An <see cref="AnimancerState"/> which plays a <see cref="PlayableAsset"/>.</summary>
/// <remarks>
/// Documentation: <see href="https://kybernetik.com.au/animancer/docs/manual/timeline">Timeline</see>
/// </remarks>
/// https://kybernetik.com.au/animancer/api/Animancer/PlayableAssetState
///
public sealed class PlayableAssetState : AnimancerState
{
/************************************************************************************************************************/
/// <summary>An <see cref="ITransition{TState}"/> that creates a <see cref="PlayableAssetState"/>.</summary>
public interface ITransition : ITransition<PlayableAssetState> { }
/************************************************************************************************************************/
#region Fields and Properties
/************************************************************************************************************************/
/// <summary>The <see cref="PlayableAsset"/> which this state plays.</summary>
private PlayableAsset _Asset;
/// <summary>The <see cref="PlayableAsset"/> which this state plays.</summary>
public PlayableAsset Asset
{
get => _Asset;
set => ChangeMainObject(ref _Asset, value);
}
/// <summary>The <see cref="PlayableAsset"/> which this state plays.</summary>
public override Object MainObject
{
get => _Asset;
set => _Asset = (PlayableAsset)value;
}
/************************************************************************************************************************/
private float _Length;
/// <summary>The <see cref="PlayableAsset.duration"/>.</summary>
public override float Length => _Length;
/************************************************************************************************************************/
/// <inheritdoc/>
protected override void OnSetIsPlaying()
{
var inputCount = _Playable.GetInputCount();
for (int i = 0; i < inputCount; i++)
{
var playable = _Playable.GetInput(i);
if (!playable.IsValid())
continue;
if (IsPlaying)
playable.Play();
else
playable.Pause();
}
}
/************************************************************************************************************************/
/// <summary>IK cannot be dynamically enabled on a <see cref="PlayableAssetState"/>.</summary>
public override void CopyIKFlags(AnimancerNode node) { }
/************************************************************************************************************************/
/// <summary>IK cannot be dynamically enabled on a <see cref="PlayableAssetState"/>.</summary>
public override bool ApplyAnimatorIK
{
get => false;
set
{
#if UNITY_ASSERTIONS
if (value)
OptionalWarning.UnsupportedIK.Log(
$"IK cannot be dynamically enabled on a {nameof(PlayableAssetState)}.", Root?.Component);
#endif
}
}
/************************************************************************************************************************/
/// <summary>IK cannot be dynamically enabled on a <see cref="PlayableAssetState"/>.</summary>
public override bool ApplyFootIK
{
get => false;
set
{
#if UNITY_ASSERTIONS
if (value)
OptionalWarning.UnsupportedIK.Log(
$"IK cannot be dynamically enabled on a {nameof(PlayableAssetState)}.", Root?.Component);
#endif
}
}
/************************************************************************************************************************/
#endregion
/************************************************************************************************************************/
#region Methods
/************************************************************************************************************************/
/// <summary>Creates a new <see cref="PlayableAssetState"/> to play the `asset`.</summary>
/// <exception cref="ArgumentNullException">The `asset` is null.</exception>
public PlayableAssetState(PlayableAsset asset)
{
if (asset == null)
throw new ArgumentNullException(nameof(asset));
_Asset = asset;
}
/************************************************************************************************************************/
/// <inheritdoc/>
protected override void CreatePlayable(out Playable playable)
{
playable = _Asset.CreatePlayable(Root._Graph, Root.Component.gameObject);
playable.SetDuration(9223372.03685477);// https://github.com/KybernetikGames/animancer/issues/111
_Length = (float)_Asset.duration;
if (!_HasInitializedBindings)
InitializeBindings();
}
/************************************************************************************************************************/
private IList<Object> _Bindings;
private bool _HasInitializedBindings;
/************************************************************************************************************************/
/// <summary>The objects controlled by each track in the asset.</summary>
public IList<Object> Bindings
{
get => _Bindings;
set
{
_Bindings = value;
InitializeBindings();
}
}
/************************************************************************************************************************/
/// <summary>Sets the <see cref="Bindings"/>.</summary>
public void SetBindings(params Object[] bindings)
{
Bindings = bindings;
}
/************************************************************************************************************************/
private void InitializeBindings()
{
if (_Bindings == null || Root == null)
return;
_HasInitializedBindings = true;
var bindingCount = _Bindings.Count;
if (bindingCount == 0)
return;
var output = _Asset.outputs.GetEnumerator();
var graph = Root._Graph;
for (int i = 0; i < bindingCount; i++)
{
if (!output.MoveNext())
return;
if (ShouldSkipBinding(output.Current, out var name, out var type))
{
i--;
continue;
}
var binding = _Bindings[i];
if (binding == null && type != null)
continue;
#if UNITY_ASSERTIONS
if (type != null && !type.IsAssignableFrom(binding.GetType()))
{
Debug.LogError(
$"Binding Type Mismatch: bindings[{i}] is '{binding}' but should be a {type.FullName} for {name}",
Root?.Component as Object);
continue;
}
Validate.AssertPlayable(this);
#endif
var playable = _Playable.GetInput(i);
if (type == typeof(Animator))
{
var playableOutput = AnimationPlayableOutput.Create(graph, name, (Animator)binding);
playableOutput.SetSourcePlayable(playable);
}
else if (type == typeof(AudioSource))
{
var playableOutput = AudioPlayableOutput.Create(graph, name, (AudioSource)binding);
playableOutput.SetSourcePlayable(playable);
}
else// ActivationTrack, SignalTrack, ControlTrack, PlayableTrack.
{
var playableOutput = ScriptPlayableOutput.Create(graph, name);
playableOutput.SetUserData(binding);
playableOutput.SetSourcePlayable(playable);
}
}
}
/************************************************************************************************************************/
/// <summary>Should the `binding` be skipped when determining how to map the <see cref="Bindings"/>?</summary>
public static bool ShouldSkipBinding(PlayableBinding binding, out string name, out Type type)
{
name = binding.streamName;
type = binding.outputTargetType;
if (type == typeof(GameObject) && name == "Markers")
return true;
return false;
}
/************************************************************************************************************************/
/// <inheritdoc/>
public override void Destroy()
{
_Asset = null;
base.Destroy();
}
/************************************************************************************************************************/
#endregion
/************************************************************************************************************************/
}
}
| 38.880309 | 130 | 0.399801 | [
"MIT"
] | malering/ET | Unity/Assets/VCFrame/EngineCode/ThirdParty/Animancer/Internal/Core/PlayableAssetState.cs | 10,070 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Monitor.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Definition of association of a data collection rule with a monitored
/// Azure resource.
/// </summary>
public partial class DataCollectionRuleAssociation
{
/// <summary>
/// Initializes a new instance of the DataCollectionRuleAssociation
/// class.
/// </summary>
public DataCollectionRuleAssociation()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the DataCollectionRuleAssociation
/// class.
/// </summary>
/// <param name="description">Description of the association.</param>
/// <param name="dataCollectionRuleId">The resource ID of the data
/// collection rule that is to be associated.</param>
/// <param name="dataCollectionEndpointId">The resource ID of the data
/// collection endpoint that is to be associated.</param>
/// <param name="provisioningState">The resource provisioning state.
/// Possible values include: 'Creating', 'Updating', 'Deleting',
/// 'Succeeded', 'Failed'</param>
/// <param name="metadata">Metadata about the resource</param>
public DataCollectionRuleAssociation(string description = default(string), string dataCollectionRuleId = default(string), string dataCollectionEndpointId = default(string), string provisioningState = default(string), DataCollectionRuleAssociationMetadata metadata = default(DataCollectionRuleAssociationMetadata))
{
Description = description;
DataCollectionRuleId = dataCollectionRuleId;
DataCollectionEndpointId = dataCollectionEndpointId;
ProvisioningState = provisioningState;
Metadata = metadata;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets description of the association.
/// </summary>
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
/// <summary>
/// Gets or sets the resource ID of the data collection rule that is to
/// be associated.
/// </summary>
[JsonProperty(PropertyName = "dataCollectionRuleId")]
public string DataCollectionRuleId { get; set; }
/// <summary>
/// Gets or sets the resource ID of the data collection endpoint that
/// is to be associated.
/// </summary>
[JsonProperty(PropertyName = "dataCollectionEndpointId")]
public string DataCollectionEndpointId { get; set; }
/// <summary>
/// Gets the resource provisioning state. Possible values include:
/// 'Creating', 'Updating', 'Deleting', 'Succeeded', 'Failed'
/// </summary>
[JsonProperty(PropertyName = "provisioningState")]
public string ProvisioningState { get; private set; }
/// <summary>
/// Gets metadata about the resource
/// </summary>
[JsonProperty(PropertyName = "metadata")]
public DataCollectionRuleAssociationMetadata Metadata { get; private set; }
}
}
| 39.840426 | 321 | 0.640854 | [
"MIT"
] | AikoBB/azure-sdk-for-net | sdk/monitor/Microsoft.Azure.Management.Monitor/src/Generated/Models/DataCollectionRuleAssociation.cs | 3,745 | C# |
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
using Xunit;
namespace SixLabors.ImageSharp.Tests.Metadata.Profiles.ICC.DataReader
{
[Trait("Profile", "Icc")]
public class IccDataReaderMatrixTests
{
[Theory]
[MemberData(nameof(IccTestDataMatrix.Matrix2D_FloatArrayTestData), MemberType = typeof(IccTestDataMatrix))]
public void ReadMatrix2D(byte[] data, int xCount, int yCount, bool isSingle, float[,] expected)
{
IccDataReader reader = CreateReader(data);
float[,] output = reader.ReadMatrix(xCount, yCount, isSingle);
Assert.Equal(expected, output);
}
[Theory]
[MemberData(nameof(IccTestDataMatrix.Matrix1D_ArrayTestData), MemberType = typeof(IccTestDataMatrix))]
public void ReadMatrix1D(byte[] data, int yCount, bool isSingle, float[] expected)
{
IccDataReader reader = CreateReader(data);
float[] output = reader.ReadMatrix(yCount, isSingle);
Assert.Equal(expected, output);
}
private static IccDataReader CreateReader(byte[] data)
{
return new IccDataReader(data);
}
}
}
| 31.775 | 115 | 0.654603 | [
"Apache-2.0"
] | 0xced/ImageSharp | tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderMatrixTests.cs | 1,271 | 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.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Route53.Model
{
/// <summary>
/// Container for the parameters to the ListResourceRecordSets operation.
/// <para>Imagine all the resource record sets in a zone listed out in front of you. Imagine them sorted lexicographically first by DNS name
/// (with the labels reversed, like "com.amazon.www" for example), and secondarily, lexicographically by record type. This operation retrieves
/// at most MaxItems resource record sets from this list, in order, starting at a position specified by the Name and Type arguments:</para>
/// <ul>
/// <li>If both Name and Type are omitted, this means start the results at the first RRSET in the HostedZone.</li>
/// <li>If Name is specified but Type is omitted, this means start the results at the first RRSET in the list whose name is greater than or
/// equal to Name. </li>
/// <li>If both Name and Type are specified, this means start the results at the first RRSET in the list whose name is greater than or equal to
/// Name and whose type is greater than or equal to Type.</li>
/// <li>It is an error to specify the Type but not the Name.</li>
///
/// </ul>
/// <para>Use ListResourceRecordSets to retrieve a single known record set by specifying the record set's name and type, and setting MaxItems =
/// 1</para> <para>To retrieve all the records in a HostedZone, first pause any processes making calls to ChangeResourceRecordSets. Initially
/// call ListResourceRecordSets without a Name and Type to get the first page of record sets. For subsequent calls, set Name and Type to the
/// NextName and NextType values returned by the previous response. </para> <para>In the presence of concurrent ChangeResourceRecordSets calls,
/// there is no consistency of results across calls to ListResourceRecordSets. The only way to get a consistent multi-page snapshot of all
/// RRSETs in a zone is to stop making changes while pagination is in progress.</para> <para>However, the results from ListResourceRecordSets
/// are consistent within a page. If MakeChange calls are taking place concurrently, the result of each one will either be completely visible in
/// your results or not at all. You will not see partial changes, or changes that do not ultimately succeed. (This follows from the fact that
/// MakeChange is atomic) </para> <para>The results from ListResourceRecordSets are strongly consistent with ChangeResourceRecordSets. To be
/// precise, if a single process makes a call to ChangeResourceRecordSets and receives a successful response, the effects of that change will be
/// visible in a subsequent call to ListResourceRecordSets by that process.</para>
/// </summary>
public partial class ListResourceRecordSetsRequest : AmazonRoute53Request
{
private string hostedZoneId;
private string startRecordName;
private RRType startRecordType;
private string startRecordIdentifier;
private string maxItems;
/// <summary>
/// The ID of the hosted zone that contains the resource record sets that you want to get.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 32</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string HostedZoneId
{
get { return this.hostedZoneId; }
set { this.hostedZoneId = value; }
}
// Check to see if HostedZoneId property is set
internal bool IsSetHostedZoneId()
{
return this.hostedZoneId != null;
}
/// <summary>
/// The first name in the lexicographic ordering of domain names that you want the <c>ListResourceRecordSets</c> request to list.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 1024</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string StartRecordName
{
get { return this.startRecordName; }
set { this.startRecordName = value; }
}
// Check to see if StartRecordName property is set
internal bool IsSetStartRecordName()
{
return this.startRecordName != null;
}
/// <summary>
/// The DNS type at which to begin the listing of resource record sets. Valid values: <c>A</c> | <c>AAAA</c> | <c>CNAME</c> | <c>MX</c> |
/// <c>NS</c> | <c>PTR</c> | <c>SOA</c> | <c>SPF</c> | <c>SRV</c> | <c>TXT</c> Values for Weighted Resource Record Sets: <c>A</c> | <c>AAAA</c>
/// | <c>CNAME</c> | <c>TXT</c> Values for Regional Resource Record Sets: <c>A</c> | <c>AAAA</c> | <c>CNAME</c> | <c>TXT</c> Values for Alias
/// Resource Record Sets: <c>A</c> | <c>AAAA</c> Constraint: Specifying <c>type</c> without specifying <c>name</c> returns an
/// <a>InvalidInput</a> error.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>SOA, A, TXT, NS, CNAME, MX, PTR, SRV, SPF, AAAA</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public RRType StartRecordType
{
get { return this.startRecordType; }
set { this.startRecordType = value; }
}
// Check to see if StartRecordType property is set
internal bool IsSetStartRecordType()
{
return this.startRecordType != null;
}
/// <summary>
/// <i>Weighted resource record sets only:</i> If results were truncated for a given DNS name and type, specify the value of
/// <c>ListResourceRecordSetsResponse$NextRecordIdentifier</c> from the previous response to get the next resource record set that has the
/// current DNS name and type.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 128</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string StartRecordIdentifier
{
get { return this.startRecordIdentifier; }
set { this.startRecordIdentifier = value; }
}
// Check to see if StartRecordIdentifier property is set
internal bool IsSetStartRecordIdentifier()
{
return this.startRecordIdentifier != null;
}
/// <summary>
/// The maximum number of records you want in the response body.
///
/// </summary>
public string MaxItems
{
get { return this.maxItems; }
set { this.maxItems = value; }
}
// Check to see if MaxItems property is set
internal bool IsSetMaxItems()
{
return this.maxItems != null;
}
}
}
| 43.612903 | 151 | 0.611563 | [
"Apache-2.0"
] | virajs/aws-sdk-net | AWSSDK_DotNet35/Amazon.Route53/Model/ListResourceRecordSetsRequest.cs | 8,112 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace EventCloud.Migrations
{
public partial class _27Feb1addPackage : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "Value",
table: "AbpUserTokens",
maxLength: 512,
nullable: true,
oldClrType: typeof(string),
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "AbpUserTokens",
maxLength: 128,
nullable: true,
oldClrType: typeof(string),
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "LoginProvider",
table: "AbpUserTokens",
maxLength: 128,
nullable: true,
oldClrType: typeof(string),
oldNullable: true);
migrationBuilder.AddColumn<DateTime>(
name: "ExpireDate",
table: "AbpUserTokens",
nullable: true);
migrationBuilder.AlterColumn<string>(
name: "UserName",
table: "AbpUsers",
maxLength: 256,
nullable: false,
oldClrType: typeof(string),
oldMaxLength: 32);
migrationBuilder.AlterColumn<string>(
name: "Surname",
table: "AbpUsers",
maxLength: 64,
nullable: false,
oldClrType: typeof(string),
oldMaxLength: 32);
migrationBuilder.AlterColumn<string>(
name: "SecurityStamp",
table: "AbpUsers",
maxLength: 128,
nullable: true,
oldClrType: typeof(string),
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "PhoneNumber",
table: "AbpUsers",
maxLength: 32,
nullable: true,
oldClrType: typeof(string),
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "NormalizedUserName",
table: "AbpUsers",
maxLength: 256,
nullable: false,
oldClrType: typeof(string),
oldMaxLength: 32);
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "AbpUsers",
maxLength: 64,
nullable: false,
oldClrType: typeof(string),
oldMaxLength: 32);
migrationBuilder.AlterColumn<string>(
name: "ConcurrencyStamp",
table: "AbpUsers",
maxLength: 128,
nullable: true,
oldClrType: typeof(string),
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "BrowserInfo",
table: "AbpUserLoginAttempts",
maxLength: 512,
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 256,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "UserName",
table: "AbpUserAccounts",
maxLength: 256,
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 32,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "ConcurrencyStamp",
table: "AbpRoles",
maxLength: 128,
nullable: true,
oldClrType: typeof(string),
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "BrowserInfo",
table: "AbpEntityChangeSets",
maxLength: 512,
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 256,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "BrowserInfo",
table: "AbpAuditLogs",
maxLength: 512,
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 256,
oldNullable: true);
migrationBuilder.CreateTable(
name: "HealthPackage",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
IsDeleted = table.Column<bool>(nullable: false),
DeleterUserId = table.Column<long>(nullable: true),
DeletionTime = table.Column<DateTime>(nullable: true),
TenantId = table.Column<int>(nullable: false),
LabPackageName = table.Column<string>(nullable: true),
LabPackageDescription = table.Column<string>(nullable: true),
LabPackageCode = table.Column<string>(nullable: true),
ImageUrl = table.Column<string>(nullable: true),
Gender = table.Column<int>(nullable: false),
AgeGroup = table.Column<string>(nullable: true),
Price = table.Column<decimal>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_HealthPackage", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "HealthPackage");
migrationBuilder.DropColumn(
name: "ExpireDate",
table: "AbpUserTokens");
migrationBuilder.AlterColumn<string>(
name: "Value",
table: "AbpUserTokens",
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 512,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "AbpUserTokens",
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 128,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "LoginProvider",
table: "AbpUserTokens",
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 128,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "UserName",
table: "AbpUsers",
maxLength: 32,
nullable: false,
oldClrType: typeof(string),
oldMaxLength: 256);
migrationBuilder.AlterColumn<string>(
name: "Surname",
table: "AbpUsers",
maxLength: 32,
nullable: false,
oldClrType: typeof(string),
oldMaxLength: 64);
migrationBuilder.AlterColumn<string>(
name: "SecurityStamp",
table: "AbpUsers",
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 128,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "PhoneNumber",
table: "AbpUsers",
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 32,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "NormalizedUserName",
table: "AbpUsers",
maxLength: 32,
nullable: false,
oldClrType: typeof(string),
oldMaxLength: 256);
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "AbpUsers",
maxLength: 32,
nullable: false,
oldClrType: typeof(string),
oldMaxLength: 64);
migrationBuilder.AlterColumn<string>(
name: "ConcurrencyStamp",
table: "AbpUsers",
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 128,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "BrowserInfo",
table: "AbpUserLoginAttempts",
maxLength: 256,
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 512,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "UserName",
table: "AbpUserAccounts",
maxLength: 32,
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 256,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "ConcurrencyStamp",
table: "AbpRoles",
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 128,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "BrowserInfo",
table: "AbpEntityChangeSets",
maxLength: 256,
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 512,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "BrowserInfo",
table: "AbpAuditLogs",
maxLength: 256,
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 512,
oldNullable: true);
}
}
}
| 35.043189 | 82 | 0.4781 | [
"MIT"
] | HealthPro-Alborg-Demo/alborg_project | aspnet-core/src/EventCloud.EntityFrameworkCore/Migrations/20190227091233_27-Feb-1-addPackage.cs | 10,550 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Excellent_Or_Not_Book
{
class Program
{
static void Main(string[] args)
{
var grade = double.Parse(Console.ReadLine());
if (grade >= 5.50)
{
Console.WriteLine("Excellent!");
}
else
{
Console.WriteLine("Not excellent.");
}
}
}
}
| 19.576923 | 57 | 0.514735 | [
"MIT"
] | Radostta/Programming-Basics-And-Fundamentals-SoftUni | Simple-Conditions/Excellent-Or-Not-Book/Program.cs | 511 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class animImportFacialInitialPoseEntryDesc : CVariable
{
[Ordinal(0)] [RED("id")] public CInt16 Id { get; set; }
[Ordinal(1)] [RED("initAnimationPoseMax")] public CFloat InitAnimationPoseMax { get; set; }
[Ordinal(2)] [RED("initAnimationPoseMid")] public CFloat InitAnimationPoseMid { get; set; }
[Ordinal(3)] [RED("initAnimationPoseMin")] public CFloat InitAnimationPoseMin { get; set; }
[Ordinal(4)] [RED("isCachable")] public CBool IsCachable { get; set; }
[Ordinal(5)] [RED("poseName")] public CName PoseName { get; set; }
[Ordinal(6)] [RED("side")] public CUInt8 Side { get; set; }
[Ordinal(7)] [RED("type")] public CUInt8 Type { get; set; }
[Ordinal(8)] [RED("weight")] public CFloat Weight { get; set; }
public animImportFacialInitialPoseEntryDesc(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 43.25 | 123 | 0.683044 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/animImportFacialInitialPoseEntryDesc.cs | 1,015 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace OpenActive.NET
{
/// <summary>
///
/// ## **EARLY RELEASE NOTICE**
/// In order to expedite the OpenActive tooling work, this class has been added to the model for the purposes of testing.
/// IT IS SUBJECT TO CHANGE, as the [Dataset API Discovery specification](https://www.openactive.io/dataset-api-discovery/EditorsDraft/) evolves.
///
/// This type is derived from [WebAPI](https://pending.schema.org/WebAPI).
/// </summary>
[DataContract]
public partial class WebAPI : Schema.NET.JsonLdObject
{
/// <summary>
/// Returns the JSON-LD representation of this instance.
/// This method overrides Schema.NET ToString() to serialise using OpenActiveSerializer.
/// </summary>
/// <returns>A <see cref="string" /> that represents the JSON-LD representation of this instance.</returns>
public override string ToString()
{
return OpenActiveSerializer.Serialize(this);
}
/// <summary>
/// Returns the JSON-LD representation of this instance, including "https://schema.org" in the "@context".
///
/// This method must be used when you want to embed the output raw (as-is) into a web
/// page. It uses serializer settings with HTML escaping to avoid Cross-Site Scripting (XSS)
/// vulnerabilities if the object was constructed from an untrusted source.
///
/// This method overrides Schema.NET ToHtmlEscapedString() to serialise using OpenActiveSerializer.
/// </summary>
/// <returns>
/// A <see cref="string" /> that represents the JSON-LD representation of this instance.
/// </returns>
public new string ToHtmlEscapedString()
{
return OpenActiveSerializer.SerializeToHtmlEmbeddableString(this);
}
/// <summary>
/// Gets the name of the type as specified by schema.org.
/// </summary>
[DataMember(Name = "@type", Order = 1)]
public override string Type => "WebAPI";
/// <summary>
/// The name of the WebAPI
/// </summary>
/// <example>
/// <code>
/// "name": "Acme Leisure Sessions and Facilities"
/// </code>
/// </example>
[DataMember(Name = "name", EmitDefaultValue = false, Order = 7)]
[JsonConverter(typeof(ValuesConverter))]
public virtual string Name { get; set; }
/// <summary>
/// The description of the Dataset
/// </summary>
/// <example>
/// <code>
/// "description": "Near real-time availability and rich descriptions relating to the sessions and facilities available from {OrganisationName}, published using the OpenActive Modelling Specification 2.0."
/// </code>
/// </example>
[DataMember(Name = "description", EmitDefaultValue = false, Order = 8)]
[JsonConverter(typeof(ValuesConverter))]
public virtual string Description { get; set; }
/// <summary>
/// Indicates the version and profiles of OpenActive Open Booking Specification with which this WebAPI conforms, by specifying these as URLs.
/// </summary>
/// <example>
/// <code>
/// "conformsTo": [
/// "https://www.openactive.io/open-booking-api/1.0/#core"
/// ]
/// </code>
/// </example>
[DataMember(Name = "conformsTo", EmitDefaultValue = false, Order = 9)]
[JsonConverter(typeof(ValuesConverter))]
public virtual List<Uri> ConformsTo { get; set; }
/// <summary>
/// A link to documentation related to the Dataset, or a link to the OpenActive developer documentation if no Dataset-specific documentation is available.
/// </summary>
/// <example>
/// <code>
/// "documentation": "https://developer.openactive.io"
/// </code>
/// </example>
[DataMember(Name = "documentation", EmitDefaultValue = false, Order = 10)]
[JsonConverter(typeof(ValuesConverter))]
public virtual Uri Documentation { get; set; }
/// <summary>
/// The Open API document associated with this version of the Open Booking API
/// </summary>
/// <example>
/// <code>
/// "endpointDescription": "https://www.openactive.io/open-booking-api/1.0/swagger.json"
/// </code>
/// </example>
[DataMember(Name = "endpointDescription", EmitDefaultValue = false, Order = 11)]
[JsonConverter(typeof(ValuesConverter))]
public virtual Uri EndpointDescription { get; set; }
/// <summary>
/// The base URL of the Open Booking API
/// </summary>
/// <example>
/// <code>
/// "endpointURL": "https://example.bookingsystem.com/api/openbooking"
/// </code>
/// </example>
[DataMember(Name = "endpointURL", EmitDefaultValue = false, Order = 12)]
[JsonConverter(typeof(ValuesConverter))]
public virtual Uri EndpointURL { get; set; }
/// <summary>
/// The web page the broker uses to obtain access to the API, e.g. via a web form.
/// </summary>
/// <example>
/// <code>
/// "landingPage": "https://exampleforms.com/get-me-an-api-access-key"
/// </code>
/// </example>
[DataMember(Name = "landingPage", EmitDefaultValue = false, Order = 13)]
[JsonConverter(typeof(ValuesConverter))]
public virtual Uri LandingPage { get; set; }
/// <summary>
/// A link to terms of service related to the use of this API.
/// </summary>
/// <example>
/// <code>
/// "termsOfService": "https://example.bookingsystem.com/terms"
/// </code>
/// </example>
[DataMember(Name = "termsOfService", EmitDefaultValue = false, Order = 14)]
[JsonConverter(typeof(ValuesConverter))]
public virtual Uri TermsOfService { get; set; }
}
}
| 38.440994 | 213 | 0.589594 | [
"MIT"
] | shervinw/OpenActive.NET | OpenActive.NET/models/WebAPI.cs | 6,189 | C# |
using OneData.Exceptions;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Globalization;
namespace OneData.Tools
{
public class SimpleConverter
{
/// <summary>
/// Convierte un objeto de tipo String al tipo proporcionado. Esta funcion acepta Nullable Types.
/// </summary>
/// <param name="value">Cadena string a convertir.</param>
/// <param name="targetType">El tipo objetivo para la conversion.</param>
/// <returns>Regresa un nuevo Objeto ya convertido al tipo deseado.</returns>
public static object ConvertStringToType(string value, Type targetType)
{
Type underlyingType = Nullable.GetUnderlyingType(targetType);
if (underlyingType != null)
{
if (string.IsNullOrEmpty(value))
{
return null;
}
}
else
{
underlyingType = targetType;
}
try
{
switch (underlyingType.Name)
{
case "Guid":
return Guid.Parse(value);
case "String":
return value;
case "Decimal":
return Convert.ChangeType(value.Replace("$", string.Empty), underlyingType);
case "Float":
return Convert.ChangeType(value.Replace("$", string.Empty), underlyingType);
case "Double":
return Convert.ChangeType(value.Replace("$", string.Empty), underlyingType);
case "DateTime":
try
{
DateTime newDateTime;
if (!DateTime.TryParse(value, out newDateTime))
{
newDateTime = DateTime.ParseExact(value, "dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
}
return newDateTime;
}
catch
{
return DateTime.FromOADate(double.Parse(value));
}
default:
if (underlyingType.IsEnum)
{
return Enum.Parse(underlyingType, value);
}
else
{
return Convert.ChangeType(value, underlyingType);
}
}
}
catch (FormatException e)
{
throw new ConvertionFailedException(value, targetType, e);
}
}
/// <summary>
/// Convierte un objeto de tipo string en un objeto de tipo Nullable<int>.
/// </summary>
/// <param name="value">Valor a convertir.</param>
/// <param name="nullable">Especifica si el valor es nullable (int?) o no.</param>
/// <returns>Regresa un nuevo objeto de tipo Nullable<int> ya con el valor incorporado.</returns>
public static int? StringToInteger(string value, bool nullable)
{
if (!int.TryParse(value, out int newValue))
{
if (!nullable)
{
newValue = 0;
}
else
{
return null;
}
}
return newValue;
}
/// <summary>
/// Convierte un objeto de tipo string en un objeto de tipo Nullable<Int64>.
/// </summary>
/// <param name="value">Valor a convertir.</param>
/// <param name="nullable">Especifica si el valor es nullable (Int64?) o no.</param>
/// <returns>Regresa un nuevo objeto de tipo Nullable<Int64> ya con el valor incorporado.</returns>
public static Int64? StringToInt64(string value, bool nullable)
{
if (!Int64.TryParse(value, out long newValue))
{
if (!nullable)
{
newValue = 0;
}
else
{
return null;
}
}
return newValue;
}
/// <summary>
/// Convierte un objeto de tipo string en un objeto de tipo Nullable<decimal>.
/// </summary>
/// <param name="value">Valor a convertir.</param>
/// <param name="nullable">Especifica si el valor es nullable (decimal?) o no.</param>
/// <returns>Regresa un nuevo objeto de tipo Nullable<decimal> ya con el valor incorporado.</returns>
public static decimal? StringToDecimal(string value, bool nullable)
{
if (!Decimal.TryParse(value, out decimal newValue))
{
if (!nullable)
{
newValue = 0;
}
else
{
return null;
}
}
return newValue;
}
/// <summary>
/// Convierte un objeto de tipo string a un objeto de tipo Guid.
/// </summary>
/// <param name="value">Valor a convertir.</param>
/// <returns>Regresa un nuevo objeto de tipo Guid ya con el valor incorporado.</returns>
public static Guid StringToGuid(string value)
{
if (!Guid.TryParse(value, out Guid newValue))
{
newValue = new Guid();
}
return newValue;
}
private static Object MySqlParameterToObject(MySqlParameter parameter)
{
return parameter.Value;
}
private static Object MSSqlParameterToObject(SqlParameter parameter)
{
return parameter.Value;
}
/// <summary>
/// Convierte la coleccion contenida en un objeto de tipo MySqlParameterCollection en un objeto List<Object>.
/// </summary>
/// <param name="parameters">Coleccion de parametros a convertir.</param>
/// <returns>Regresa un nuevo objeto List<Object> con los valores de la colleccion proporcionada.</returns>
public static List<Object> MySqlParameterCollectionToList(MySqlParameterCollection parameters)
{
List<Object> objects = new List<object>();
foreach (MySqlParameter parameter in parameters)
{
objects.Add(MySqlParameterToObject(parameter));
}
return objects;
}
/// <summary>
/// Convierte la coleccion contenida en un objeto de tipo SqlParameterCollection en un objeto List<Object>.
/// </summary>
/// <param name="parameters">Coleccion de parametros a convertir.</param>
/// <returns>Regresa un nuevo objeto List<Object> con los valores de la colleccion proporcionada.</returns>
public static List<Object> MsSqlParameterCollectionToList(SqlParameterCollection parameters)
{
List<Object> objects = new List<object>();
foreach (SqlParameter parameter in parameters)
{
objects.Add(MSSqlParameterToObject(parameter));
}
return objects;
}
}
}
| 36.217391 | 129 | 0.502734 | [
"MIT"
] | jorgemk85/OneData | Tools/SimpleConverter.cs | 7,499 | C# |
#if !NETSTANDARD13
/*
* Copyright 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 iotthingsgraph-2018-09-06.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using Amazon.Runtime;
namespace Amazon.IoTThingsGraph.Model
{
/// <summary>
/// Base class for ListTagsForResource paginators.
/// </summary>
internal sealed partial class ListTagsForResourcePaginator : IPaginator<ListTagsForResourceResponse>, IListTagsForResourcePaginator
{
private readonly IAmazonIoTThingsGraph _client;
private readonly ListTagsForResourceRequest _request;
private int _isPaginatorInUse = 0;
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
public IPaginatedEnumerable<ListTagsForResourceResponse> Responses => new PaginatedResponse<ListTagsForResourceResponse>(this);
/// <summary>
/// Enumerable containing all of the Tags
/// </summary>
public IPaginatedEnumerable<Tag> Tags =>
new PaginatedResultKeyResponse<ListTagsForResourceResponse, Tag>(this, (i) => i.Tags);
internal ListTagsForResourcePaginator(IAmazonIoTThingsGraph client, ListTagsForResourceRequest request)
{
this._client = client;
this._request = request;
}
#if BCL
IEnumerable<ListTagsForResourceResponse> IPaginator<ListTagsForResourceResponse>.Paginate()
{
if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0)
{
throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance.");
}
var nextToken = _request.NextToken;
ListTagsForResourceResponse response;
do
{
_request.NextToken = nextToken;
response = _client.ListTagsForResource(_request);
nextToken = response.NextToken;
yield return response;
}
while (nextToken != null);
}
#endif
#if AWS_ASYNC_ENUMERABLES_API
async IAsyncEnumerable<ListTagsForResourceResponse> IPaginator<ListTagsForResourceResponse>.PaginateAsync(CancellationToken cancellationToken = default)
{
if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0)
{
throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance.");
}
var nextToken = _request.NextToken;
ListTagsForResourceResponse response;
do
{
_request.NextToken = nextToken;
response = await _client.ListTagsForResourceAsync(_request, cancellationToken).ConfigureAwait(false);
nextToken = response.NextToken;
cancellationToken.ThrowIfCancellationRequested();
yield return response;
}
while (nextToken != null);
}
#endif
}
}
#endif | 38.958763 | 160 | 0.665255 | [
"Apache-2.0"
] | orinem/aws-sdk-net | sdk/src/Services/IoTThingsGraph/Generated/Model/_bcl45+netstandard/ListTagsForResourcePaginator.cs | 3,779 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace ZDevTools.Utilities
{
/// <summary>
/// 哈希工具
/// </summary>
public static class HashTools
{
/// <summary>
/// 使用UTF8编码计算明文的Sha384编码字符串
/// </summary>
/// <param name="clearText"></param>
/// <returns></returns>
public static string ComputeSha384(string clearText) => ComputeSha384(Encoding.UTF8.GetBytes(clearText));
/// <summary>
/// 计算明文字节数组的Sha384编码字符串
/// </summary>
public static string ComputeSha384(byte[] clearBytes)
{
using (var sha384 = SHA384.Create())
return StringTools.ToHexString(sha384.ComputeHash(clearBytes));
}
/// <summary>
/// 使用UTF8编码计算明文的Md5编码字符串
/// </summary>
public static string ComputeMd5(string clearText) => ComputeMd5(Encoding.UTF8.GetBytes(clearText));
/// <summary>
/// 计算明文字节数组的Md5编码字符串
/// </summary>
public static string ComputeMd5(byte[] clearBytes)
{
using (var md5 = MD5.Create())
return StringTools.ToHexString(md5.ComputeHash(clearBytes));
}
}
}
| 28.478261 | 113 | 0.596947 | [
"Apache-2.0"
] | zhyy2008z/ZDevTools | ZDevTools/Utilities/HashTools.cs | 1,432 | C# |
namespace _07.Sum_Big_Numbers
{
using System;
using System.Text;
public class SumBigNumbers
{
public static void Main()
{
string firstNum = Console.ReadLine();
string secondNum = Console.ReadLine();
int numInMind = 0;
int remainder = 0;
StringBuilder sb = new StringBuilder();
int longestNum = Math.Max(firstNum.Length, secondNum.Length);
string formatedFirstNum = string.Format("{0}", firstNum.PadLeft(longestNum ,'0'));
string formatedSecondNum = string.Format("{0}", secondNum.PadLeft(longestNum, '0'));
for (int i = longestNum - 1; i >= 0; i--)
{
int sum = int.Parse(formatedFirstNum[i].ToString()) + int.Parse(formatedSecondNum[i].ToString()) + numInMind;
numInMind = sum / 10;
remainder = sum % 10;
sb.Append(remainder);
if (numInMind > 0 && i == 0)
{
sb.Append(numInMind);
}
}
char[] result = sb.ToString().TrimEnd('0').ToCharArray();
Array.Reverse(result);
Console.WriteLine(result);
}
}
}
| 31.375 | 130 | 0.513147 | [
"MIT"
] | ELalkovski/Software-University | 04. C# Advanced/04. Manual String Processing Exercises/07. Sum Big Numbers/SumBigNumbers.cs | 1,257 | C# |
/*
* Copyright (C) Sportradar AG. See LICENSE for full license governing this code
*/
using System.Collections.Generic;
using Dawn;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Sportradar.OddsFeed.SDK.Entities.REST.Internal.Caching.Events;
namespace Sportradar.OddsFeed.SDK.Entities.REST.Internal.EntitiesImpl
{
/// <summary>
/// Class MatchStatus
/// </summary>
/// <seealso cref="CompetitionStatus" />
/// <seealso cref="IMatchStatus" />
public class MatchStatus : CompetitionStatus, IMatchStatusV3
{
private readonly decimal? _homeScore;
private readonly decimal? _awayScore;
/// <summary>
/// Gets the <see cref="IEventClock" /> instance describing the timings in the current event
/// </summary>
/// <value>The <see cref="IEventClock" /> instance describing the timings in the current event</value>
public IEventClock EventClock { get; }
/// <summary>
/// Gets the list of <see cref="IPeriodScore" />
/// </summary>
/// <value>The list of <see cref="IPeriodScore" /></value>
public IEnumerable<IPeriodScore> PeriodScores { get; }
/// <summary>
/// Gets the score of the home competitor competing on the associated sport event
/// </summary>
/// <value>The score of the home competitor competing on the associated sport event</value>
decimal? IMatchStatusV3.HomeScore => _homeScore;
/// <summary>
/// Gets the score of the away competitor competing on the associated sport event
/// </summary>
/// <value>The score of the away competitor competing on the associated sport event</value>
decimal? IMatchStatusV3.AwayScore => _awayScore;
/// <summary>
/// Gets the score of the home competitor competing on the associated sport event
/// </summary>
/// <value>The score of the home competitor competing on the associated sport event</value>
public decimal HomeScore => _homeScore ?? 0;
/// <summary>
/// Gets the score of the away competitor competing on the associated sport event
/// </summary>
/// <value>The score of the away competitor competing on the associated sport event</value>
public decimal AwayScore => _awayScore ?? 0;
/// <summary>
/// Gets the penalty score of the home competitor competing on the associated sport event (for Ice Hockey)
/// </summary>
public int? HomePenaltyScore { get; }
/// <summary>
/// Gets the penalty score of the away competitor competing on the associated sport event (for Ice Hockey)
/// </summary>
public int? AwayPenaltyScore { get; }
/// <summary>
/// Gets the indicator wither the event is decided by fed
/// </summary>
public bool? DecidedByFed { get; }
/// <summary>
/// Get match status as an asynchronous operation
/// </summary>
/// <param name="culture">The culture used to fetch status id and description</param>
/// <returns>ILocalizedNamedValue</returns>
public async Task<ILocalizedNamedValue> GetMatchStatusAsync(CultureInfo culture)
{
return SportEventStatusCI == null || SportEventStatusCI.MatchStatusId < 0 || MatchStatusCache == null
? null
: await MatchStatusCache.GetAsync(SportEventStatusCI.MatchStatusId, new List<CultureInfo> {culture}).ConfigureAwait(false);
}
/// <summary>
/// Initializes a new instance of the <see cref="MatchStatus"/> class
/// </summary>
/// <param name="ci">The cache item</param>
/// <param name="matchStatusesCache">The cache for match statuses</param>
public MatchStatus(SportEventStatusCI ci, ILocalizedNamedValueCache matchStatusesCache)
: base(ci, matchStatusesCache)
{
Guard.Argument(ci, nameof(ci)).NotNull();
Guard.Argument(matchStatusesCache, nameof(matchStatusesCache)).NotNull();
if (ci.EventClock != null)
{
EventClock = new EventClock(ci.EventClock);
}
if (ci.PeriodScores != null)
{
PeriodScores = ci.PeriodScores.Select(s => new PeriodScore(s, MatchStatusCache));
}
_homeScore = ci.HomeScore;
_awayScore = ci.AwayScore;
HomePenaltyScore = ci.HomePenaltyScore;
AwayPenaltyScore = ci.AwayPenaltyScore;
DecidedByFed = ci.DecidedByFed;
}
}
}
| 41.212389 | 139 | 0.625295 | [
"Apache-2.0"
] | sportradar/UnifiedOddsSdkNet | src/Sportradar.OddsFeed.SDK.Entities.REST/Internal/EntitiesImpl/MatchStatus.cs | 4,659 | C# |
/*
* Copyright 2010-2013 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.
*/
using System.Collections.Generic;
using Amazon.ElasticBeanstalk.Model;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.ElasticBeanstalk.Model.Internal.MarshallTransformations
{
/// <summary>
/// CreateStorageLocationResult Unmarshaller
/// </summary>
internal class CreateStorageLocationResultUnmarshaller : IUnmarshaller<CreateStorageLocationResult, XmlUnmarshallerContext>, IUnmarshaller<CreateStorageLocationResult, JsonUnmarshallerContext>
{
public CreateStorageLocationResult Unmarshall(XmlUnmarshallerContext context)
{
CreateStorageLocationResult createStorageLocationResult = new CreateStorageLocationResult();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.Read())
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("S3Bucket", targetDepth))
{
createStorageLocationResult.S3Bucket = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
}
else if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
return createStorageLocationResult;
}
}
return createStorageLocationResult;
}
public CreateStorageLocationResult Unmarshall(JsonUnmarshallerContext context)
{
return null;
}
private static CreateStorageLocationResultUnmarshaller instance;
public static CreateStorageLocationResultUnmarshaller GetInstance()
{
if (instance == null)
instance = new CreateStorageLocationResultUnmarshaller();
return instance;
}
}
}
| 35.533333 | 197 | 0.627767 | [
"Apache-2.0"
] | jdluzen/aws-sdk-net-android | AWSSDK/Amazon.ElasticBeanstalk/Model/Internal/MarshallTransformations/CreateStorageLocationResultUnmarshaller.cs | 2,665 | C# |
// Copyright (c) zhenlei520 All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using EInfrastructure.Core.Configuration.Enumerations.SeedWork;
namespace EInfrastructure.Core.Configuration.Enumerations
{
/// <summary>
/// 性别
/// </summary>
public class Gender : Enumeration
{
/// <summary>
/// 未知
/// </summary>
public static Gender Unknow = new Gender(0, "未知");
/// <summary>
/// 男
/// </summary>
public static Gender Boy = new Gender(1, "男");
/// <summary>
/// 女
/// </summary>
public static Gender Girl = new Gender(2, "女");
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="name">描述</param>
public Gender(int id, string name) : base(id, name)
{
}
}
}
| 24.710526 | 95 | 0.533546 | [
"MIT"
] | Hunfnfmvkvllv26/System.Extension.Core | src/Configuration/src/EInfrastructure.Core.Configuration/Enumerations/Gender.cs | 963 | C# |
using System.Linq;
using AspNetUpgrade.Model;
using Newtonsoft.Json.Linq;
namespace AspNetUpgrade.UpgradeContext
{
public class ProjectJsonWrapper
{
JObject JsonObject { get; set; }
public ProjectJsonWrapper(JObject jsonObject)
{
JsonObject = jsonObject;
}
/// <summary>
/// Returns the project type.
/// </summary>
/// <returns></returns>
public ProjectType GetProjectType()
{
// if the project.json has emitEntryPoint = true then this is an application, otherwise its a library.
var compilationOpions = JsonObject["compilationOptions"] ?? JsonObject["buildOptions"];
if (compilationOpions != null)
{
var emitEntryPoint = compilationOpions["emitEntryPoint"];
if (emitEntryPoint != null)
{
if (emitEntryPoint.ToString().ToLowerInvariant() == "true")
{
// application
return ProjectType.Application;
}
}
}
return ProjectType.Library;
}
public bool HasDependency(string dependencyName)
{
bool hasDependency = JsonObject["dependencies"]?[dependencyName] != null;
return hasDependency;
}
public bool HasFramework(string targetFrameworkMoniker)
{
bool hasDependency = JsonObject["frameworks"]?[targetFrameworkMoniker] != null;
return hasDependency;
}
public bool IsMvcProject()
{
return HasDependency("Microsoft.AspNetCore.Mvc")
|| HasDependency("Microsoft.AspNet.Mvc");
}
public void AddNetCoreAppFramework(string netCoreAppVersion, string netCoreAppTfm)
{
var prop = BuildNetCoreAppProperty(netCoreAppVersion, netCoreAppTfm);
JObject frameworks = (JObject)JsonObject.GetOrAddProperty("frameworks", null);
frameworks.Add(prop);
}
public void AddNetStandardFramework(string netStandardLibraryVersion, string netStandardTfm)
{
string[] imports = new string[] { "dnxcore50", "portable-net45+win8" };
JObject projectJsonObject = JsonObject;
var frameworks = projectJsonObject.GetOrAddProperty("frameworks", null);
var netStadardTfm = frameworks.GetOrAddProperty(netStandardTfm, null);
var netStandardImports = netStadardTfm["imports"];
JArray importsArray = new JArray();
foreach (var import in imports)
{
importsArray.Add(import);
}
if (netStandardImports == null)
{
netStadardTfm["imports"] = importsArray;
}
JObject netStadardDependencies = netStadardTfm.GetOrAddProperty("dependencies", null);
netStadardDependencies["NETStandard.Library"] = netStandardLibraryVersion;
}
public void IncludeInCopyToOutput(JArray itemsToInclude)
{
var buildOptions = JsonObject.GetOrAddProperty("buildOptions", null);
// var existingCopyToOutput = buildOptions[copyToOutputArray];
var copyToOutput = buildOptions.Property("copyToOutput");
if (copyToOutput != null)
{
if (copyToOutput.Value is JValue)
{
// promote to include array.
var jvalue = (JValue)copyToOutput.Value;
//jvalue.Remove();
if (!itemsToInclude.Contains(jvalue.Value))
{
itemsToInclude.Add(jvalue.Value);
}
buildOptions["copyToOutput"]["include"] = itemsToInclude;
}
else if (copyToOutput.Value is JArray)
{
// add to existing array.
var existingArray = (JArray)copyToOutput.Value;
IncludeInArray(existingArray, itemsToInclude);
}
else if (copyToOutput.Value is JObject)
{
// check for an include property.
var copyToOutputObject = (JObject)copyToOutput.Value;
var includeProperty = copyToOutputObject.Property("include");
if (includeProperty == null)
{
buildOptions["copyToOutput"]["include"] = itemsToInclude;
}
else if (includeProperty.Value is JValue)
{
// single value, promote to an array
var jvalue = (JValue)includeProperty.Value;
if (!itemsToInclude.Contains(jvalue.Value))
{
itemsToInclude.Add(jvalue.Value);
}
buildOptions["copyToOutput"]["include"] = itemsToInclude;
}
else if (includeProperty.Value is JArray)
{
// already array, merge
var propArray = (JArray)includeProperty.Value;
IncludeInArray(propArray, itemsToInclude);
}
}
}
else
{
buildOptions["copyToOutput"] = new JObject();
buildOptions["copyToOutput"]["include"] = itemsToInclude;
}
}
private void IncludeInArray(JArray existingArray, JArray includeValues)
{
foreach (var val in includeValues)
{
if (!existingArray.Contains(val))
{
existingArray.Add(val);
}
}
}
private JProperty BuildNetCoreAppProperty(string netCoreAppVersion, string netCoreAppTfm)
{
// think these imports may only be needed temporarily for RC2 and may be disappearing after RC2?
// applications should depend upon netcoreapp1.0
JArray importsArray = new JArray();
importsArray.Add("dotnet5.6");
importsArray.Add("dnxcore50");
importsArray.Add("portable-net45+win8");
var importsProperty = new JProperty("imports", importsArray);
var netCoreAppObj = new JObject(importsProperty);
// Add the netCoreAppDependency dependency.
// as per: https://github.com/dotnet/cli/issues/3171
JObject netCoreAppDependencyObject = new JObject();
netCoreAppDependencyObject.Add(new JProperty("version", netCoreAppVersion));
netCoreAppDependencyObject.Add(new JProperty("type", "platform"));
var deps = netCoreAppObj.GetOrAddProperty("dependencies", importsProperty);
deps["Microsoft.NETCore.App"] = netCoreAppDependencyObject;
return new JProperty(netCoreAppTfm, netCoreAppObj);
}
}
} | 37.497382 | 114 | 0.544541 | [
"MIT"
] | dazinator/AspNetRC1toRC2UpgradeTool | src/AspNetUpgrade/AspNetUpgrade/UpgradeContext/ProjectJsonWrapper.cs | 7,164 | C# |
using System;
using System.ComponentModel.DataAnnotations;
namespace RouteDelivery.Models
{
public class DeliverySchedule: IEntity
{
[Display(Name = "Optimization Request ID")]
public int OptimizationRequestID { get; set; }
[Display(Name = "Customer No")]
public int CustomerID { get; set; }
[Display(Name = "Package No")]
public int PackageID { get; set; }
[Display(Name = "Transport Type")]
public TransportType TransportType { get; set; }
[Display(Name = "Driver Name")]
public string DriverName { get; set; }
[Display(Name = "Estimated Time")]
public DateTime EstimatedTime { get; set; }
public int ID { get; set; }
}
} | 34.636364 | 57 | 0.598425 | [
"MIT"
] | codeyu/RouteDelivery | src/RouteDelivery.Models/DeliverySchedule.cs | 764 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the config-2014-11-12.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.ConfigService.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.ConfigService.Model.Internal.MarshallTransformations
{
/// <summary>
/// DeleteConfigRule Request Marshaller
/// </summary>
public class DeleteConfigRuleRequestMarshaller : IMarshaller<IRequest, DeleteConfigRuleRequest> , 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((DeleteConfigRuleRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(DeleteConfigRuleRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.ConfigService");
string target = "StarlingDoveService.DeleteConfigRule";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.HttpMethod = "POST";
string uriResourcePath = "/";
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.IsSetConfigRuleName())
{
context.Writer.WritePropertyName("ConfigRuleName");
context.Writer.Write(publicRequest.ConfigRuleName);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
}
} | 35.977273 | 147 | 0.6494 | [
"Apache-2.0"
] | Bynder/aws-sdk-net | sdk/src/Services/ConfigService/Generated/Model/Internal/MarshallTransformations/DeleteConfigRuleRequestMarshaller.cs | 3,166 | C# |
namespace RemoteKeys;
public interface IPathParser
{
IEnumerable<string> Parse( string path );
} | 17.333333 | 43 | 0.740385 | [
"MIT"
] | palpha/remotekeys | src/RemoteKeys/IPathParser.cs | 106 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Diagnostics.ContractsLight;
using System.Globalization;
using System.IO;
using BuildXL.Pips.Filter;
using BuildXL.Storage;
using BuildXL.Utilities;
using BuildXL.Utilities.Collections;
using BuildXL.Utilities.Configuration.Mutable;
using Test.BuildXL.TestUtilities;
using Xunit.Abstractions;
namespace Test.BuildXL.Scheduler
{
public abstract class SchedulerTestBase : PipTestBase
{
private const string SourceFilePrefix = "src_file_";
private const string OutputFilePrefix = "out_file_";
private const string SpecFilePrefix = "spec_";
private const string FilePrefix = "file_";
private const string DirectoryPrefix = "directory_";
private Paths m_paths;
private AbsolutePath m_readOnlyObjectRootPath = AbsolutePath.Invalid;
private AbsolutePath m_nonHashableObjectRootPath = AbsolutePath.Invalid;
private AbsolutePath m_nonReadableObjectRootPath = AbsolutePath.Invalid;
private int m_fileFreshId;
private int m_directoryFreshId;
public SchedulerTestBase(ITestOutputHelper output)
: base(output)
{
m_paths = new Paths(Context.PathTable);
m_fileFreshId = 0;
}
protected AbsolutePath ReadOnlyObjectRootPath => m_readOnlyObjectRootPath;
protected AbsolutePath NonHashableObjectRootPath => m_nonHashableObjectRootPath;
protected AbsolutePath NonReadableObjectRootPath => m_nonReadableObjectRootPath;
protected virtual void UpdateConfiguration(CommandLineConfiguration config)
{
}
private bool TryCreateDirectoryPath(string directoryPath, out AbsolutePath path)
{
Contract.Requires(!string.IsNullOrEmpty(directoryPath));
Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out path).IsValid);
path = AbsolutePath.Invalid;
bool result = false;
try
{
Directory.CreateDirectory(directoryPath);
result = m_paths.TryCreateAbsolutePath(directoryPath, out path);
}
#pragma warning disable ERP022 // Unobserved exception in generic exception handler
catch
{
}
#pragma warning restore ERP022 // Unobserved exception in generic exception handler
return result;
}
/// <summary>
/// Creates source file artifact.
/// </summary>
protected FileArtifact CreateSourceFile(string fileName = null, string content = null)
{
return CreateSourceFile(SourceRootPath, fileName, content);
}
/// <summary>
/// Creates source file artifact.
/// </summary>
protected FileArtifact CreateSourceFile(AbsolutePath rootPath, string fileName = null, string content = null)
{
Contract.Requires(rootPath.IsValid);
if (string.IsNullOrEmpty(fileName))
{
fileName = CreateUniqueFileName(SourceFilePrefix);
}
AbsolutePath filePath = m_paths.CreateAbsolutePath(rootPath, fileName);
FileArtifact sourceFile = FileArtifact.CreateSourceFile(filePath);
WriteFile(sourceFile, content: content, appendIfExists: false);
return sourceFile;
}
/// <summary>
/// Creates output/derived file artifact.
/// </summary>
protected FileArtifact CreateOutputFile(string fileName = null, int rewriteCount = -1)
{
return CreateOutputFile(ObjectRootPath, fileName, rewriteCount);
}
/// <summary>
/// Creates output/derived file artifact.
/// </summary>
protected FileArtifact CreateOutputFile(AbsolutePath rootPath, string fileName = null, int rewriteCount = -1)
{
Contract.Requires(rootPath.IsValid);
if (string.IsNullOrEmpty(fileName))
{
fileName = CreateUniqueFileName(OutputFilePrefix);
}
AbsolutePath filePath = m_paths.CreateAbsolutePath(rootPath, fileName);
return rewriteCount < 1
? FileArtifact.CreateSourceFile(filePath).CreateNextWrittenVersion()
: new FileArtifact(filePath, rewriteCount: rewriteCount);
}
/// <summary>
/// Creates a directory artifact with zero partial seal id.
/// </summary>
protected DirectoryArtifact CreateDirectory(
AbsolutePath rootPath = default(AbsolutePath),
RelativePath relativePathToDirectory = default(RelativePath))
{
var directoryPath = CreateDirectoryPath(
rootPath.IsValid ? rootPath : ObjectRootPath,
relativePathToDirectory.IsValid
? relativePathToDirectory
: RelativePath.Create(Context.StringTable, CreateUniqueDirectoryName()));
return DirectoryArtifact.CreateWithZeroPartialSealId(directoryPath);
}
/// <summary>
/// Creates an output directory.
/// </summary>
protected ValueTuple<DirectoryArtifact, ReadOnlyArray<FileArtifactWithAttributes>> CreateOutputDirectory(
AbsolutePath rootPath = default(AbsolutePath),
RelativePath relativePathToDirectory = default(RelativePath),
RelativePath[] relativePathToMembers = null)
{
var directory = CreateDirectory(rootPath, relativePathToDirectory);
ReadOnlyArray<FileArtifactWithAttributes> members;
if (relativePathToMembers == null || relativePathToMembers.Length == 0)
{
members = ReadOnlyArray<FileArtifactWithAttributes>.Empty;
}
else
{
var fullMemberNames = new FileArtifactWithAttributes[relativePathToMembers.Length];
for (int i = 0; i < fullMemberNames.Length; ++i)
{
fullMemberNames[i] = FileArtifactWithAttributes.Create(FileArtifact.CreateOutputFile(directory.Path.Combine(Context.PathTable, relativePathToMembers[i])), FileExistence.Required);
}
members = ReadOnlyArray<FileArtifactWithAttributes>.FromWithoutCopy(fullMemberNames);
}
return (directory, members);
}
/// <summary>
/// Creates a directory path relative to a root path.
/// </summary>
protected AbsolutePath CreateDirectoryPath(AbsolutePath rootPath, RelativePath relative)
{
Contract.Requires(rootPath.IsValid);
Contract.Requires(relative.IsValid);
return m_paths.CreateAbsolutePath(rootPath, relative);
}
private string CreateUniqueFileName(string filePrefix = null)
{
return string.Format(CultureInfo.InvariantCulture, "{0}{1}", filePrefix ?? FilePrefix, m_fileFreshId++);
}
private string CreateUniqueDirectoryName(string directoryPrefix = null)
{
return string.Format(CultureInfo.InvariantCulture, "{0}{1}", directoryPrefix ?? DirectoryPrefix, m_directoryFreshId++);
}
/// <summary>
/// Writes to file artifact.
/// </summary>
protected void WriteFile(FileArtifact file, string content = null, bool appendIfExists = false)
{
content = content ?? Guid.NewGuid().ToString();
string fullPath = m_paths.Expand(file.Path);
string directoryPath = Path.GetDirectoryName(fullPath);
if (!string.IsNullOrEmpty(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
if (appendIfExists && File.Exists(fullPath))
{
content += File.ReadAllText(fullPath);
}
File.WriteAllText(fullPath, content);
}
/// <summary>
/// Deletes file artifact.
/// </summary>
protected void DeleteFile(FileArtifact file)
{
string fullPath = m_paths.Expand(file.Path);
if (File.Exists(fullPath))
{
File.Delete(fullPath);
}
}
/// <summary>
/// Creates a file content table.
/// </summary>
protected FileContentTable CreateFileContentTable()
{
Contract.Ensures(Contract.Result<FileContentTable>() != null);
return FileContentTable.CreateNew(LoggingContext);
}
/// <summary>
/// Gets content hash.
/// </summary>
protected byte[] GetContentHash(FileArtifact file)
{
Contract.Requires(file.IsValid);
byte[] hash = null;
string fullPath = m_paths.Expand(file.Path);
if (File.Exists(fullPath))
{
var stream = new MemoryStream(File.ReadAllBytes(fullPath));
var contentHash = ContentHashingUtilities.HashContentStream(stream);
return contentHash.ToHashByteArray();
}
return hash;
}
/// <summary>
/// Reads file.
/// </summary>
protected string ReadFile(FileArtifact file)
{
Contract.Requires(file.IsValid);
string fullPath = m_paths.Expand(file.Path);
if (File.Exists(fullPath))
{
string s = File.ReadAllText(fullPath);
return s;
}
return null;
}
/// <summary>
/// Creates filter from tags.
/// </summary>
protected RootFilter CreateFilterFromTags(string tag1, string tag2 = null)
{
PipFilter filter;
if (tag2 != null)
{
filter = new BinaryFilter(new TagFilter(StringId.Create(Context.PathTable.StringTable, tag1)),
FilterOperator.Or,
new TagFilter(StringId.Create(Context.PathTable.StringTable, tag2)));
}
else
{
filter = new TagFilter(StringId.Create(Context.PathTable.StringTable, tag1));
}
return new RootFilter(filter);
}
}
}
| 35.722408 | 200 | 0.590769 | [
"MIT"
] | Microsoft-Android/BuildXL | Public/Src/Engine/UnitTests/Scheduler/SchedulerTestBase.cs | 10,681 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace game_Simulation.Enums
{
public enum LoanLevel : int
{
Category1Loan = 1,
Category2Loan = 2,
Category3Loan = 3,
Category4Loan = 4,
Category5Loan = 5
}
public enum LoanTrustedLevel
{
VeryLow,
Low,
Medium,
High,
VeryHigh
}
public enum TransactionRequestType : byte
{
Deposit = 0x44,
WithDrawal = 0x57,
Invalid = 0x00
}
public enum BankReputationTitle
{
BeginnerBanker1,
BeginnerBanker2,
BeginnerBanker3,
NoviceBanker1,
NoviceBanker2,
NoviceBanker3,
ProfessionalBanker1,
ProfessionalBanker2,
ProfessionalBanker3,
MasterBanker1,
MasterBanker2,
MasterBanker3,
EliteBanker1,
EliteBanker2,
EliteBanker3,
GlobalBanker
}
public static class BankTitleExtensions
{
const int L1 = 400,
L2 = 700,
L3 = 1000,
L4 = 1693,
L5 = 2386,
L6 = 3079,
L7 = 3772,
L8 = 4465,
L9 = 5158,
L10 = 5851,
L11 = 6544,
L12 = 7237,
L13 = 7930,
L14 = 8623,
L15 = 9316,
L16 = 10000;
public static string GetString(BankReputationTitle title)
{
switch (title)
{
case BankReputationTitle.BeginnerBanker1: return "Beginner Banker L1";
case BankReputationTitle.BeginnerBanker2: return "Beginner Banker L2";
case BankReputationTitle.BeginnerBanker3: return "Beginner Banker L2";
case BankReputationTitle.NoviceBanker1: return "Novice Banker L1";
case BankReputationTitle.NoviceBanker2: return "Novice Banker L2";
case BankReputationTitle.NoviceBanker3: return "Novice Banker L3";
case BankReputationTitle.ProfessionalBanker1: return "Professional Banker L1";
case BankReputationTitle.ProfessionalBanker2: return "Professional Banker L2";
case BankReputationTitle.ProfessionalBanker3: return "Professional Banker L3";
case BankReputationTitle.MasterBanker1: return "Master Banker L1";
case BankReputationTitle.MasterBanker2: return "Master Banker L2";
case BankReputationTitle.MasterBanker3: return "Master Banker L3";
case BankReputationTitle.EliteBanker1: return "Elite Banker L1";
case BankReputationTitle.EliteBanker2: return "Elite Banker L2";
case BankReputationTitle.EliteBanker3: return "Elite Banker L3";
case BankReputationTitle.GlobalBanker: return "Global Banker";
default: return "Unknown Title";
}
}
public static string GetBankTitle(double reputation)
{
return GetString(GetTitle(reputation));
}
public static BankReputationTitle GetTitle(double reputation)
{
if (reputation < L1)
return BankReputationTitle.BeginnerBanker1;
if (reputation < L2)
return BankReputationTitle.BeginnerBanker2;
if (reputation < L3)
return BankReputationTitle.BeginnerBanker3;
if (reputation < L4)
return BankReputationTitle.NoviceBanker1;
if (reputation < L5)
return BankReputationTitle.NoviceBanker2;
if (reputation < L6)
return BankReputationTitle.NoviceBanker3;
if (reputation < L7)
return BankReputationTitle.ProfessionalBanker1;
if (reputation < L8)
return BankReputationTitle.ProfessionalBanker2;
if (reputation < L9)
return BankReputationTitle.ProfessionalBanker3;
if (reputation < L10)
return BankReputationTitle.MasterBanker1;
if (reputation < L11)
return BankReputationTitle.MasterBanker2;
if (reputation < L12)
return BankReputationTitle.MasterBanker3;
if (reputation < L13)
return BankReputationTitle.EliteBanker1;
if (reputation < L14)
return BankReputationTitle.EliteBanker2;
if (reputation < L15)
return BankReputationTitle.EliteBanker3;
return BankReputationTitle.GlobalBanker;
}
}
}
| 37.435115 | 95 | 0.559747 | [
"MIT"
] | michael-kamel/BankSim | game_Simulation/Enums/Bank.cs | 4,906 | C# |
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Security;
namespace SliceIsRightTracker.Overlay
{
internal static class Constants
{
// ReSharper disable InconsistentNaming
public const uint SWP_NOSIZE = 0x0001;
public const uint SWP_NOMOVE = 0x0002;
public const uint TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;
public const int LWA_COLORKEY = 0x1;
public const int LWA_ALPHA = 0x2;
public const int GWL_ID = (-12);
public const int GWL_STYLE = (-16);
public const int GWL_EXSTYLE = (-20);
// Window Styles
public const uint WS_OVERLAPPED = 0;
public const uint WS_POPUP = 0x80000000;
public const uint WS_CHILD = 0x40000000;
public const uint WS_MINIMIZE = 0x20000000;
public const uint WS_VISIBLE = 0x10000000;
public const uint WS_DISABLED = 0x8000000;
public const uint WS_CLIPSIBLINGS = 0x4000000;
public const uint WS_CLIPCHILDREN = 0x2000000;
public const uint WS_MAXIMIZE = 0x1000000;
public const uint WS_CAPTION = 0xC00000; // WS_BORDER or WS_DLGFRAME
public const uint WS_BORDER = 0x800000;
public const uint WS_DLGFRAME = 0x400000;
public const uint WS_VSCROLL = 0x200000;
public const uint WS_HSCROLL = 0x100000;
public const uint WS_SYSMENU = 0x80000;
public const uint WS_THICKFRAME = 0x40000;
public const uint WS_GROUP = 0x20000;
public const uint WS_TABSTOP = 0x10000;
public const uint WS_MINIMIZEBOX = 0x20000;
public const uint WS_MAXIMIZEBOX = 0x10000;
public const uint WS_TILED = WS_OVERLAPPED;
public const uint WS_ICONIC = WS_MINIMIZE;
public const uint WS_SIZEBOX = WS_THICKFRAME;
// Extended Window Styles
public const uint WS_EX_DLGMODALFRAME = 0x0001;
public const uint WS_EX_NOPARENTNOTIFY = 0x0004;
public const uint WS_EX_TOPMOST = 0x0008;
public const uint WS_EX_ACCEPTFILES = 0x0010;
public const uint WS_EX_TRANSPARENT = 0x0020;
public const uint WS_EX_MDICHILD = 0x0040;
public const uint WS_EX_TOOLWINDOW = 0x0080;
public const uint WS_EX_WINDOWEDGE = 0x0100;
public const uint WS_EX_CLIENTEDGE = 0x0200;
public const uint WS_EX_CONTEXTHELP = 0x0400;
public const uint WS_EX_RIGHT = 0x1000;
public const uint WS_EX_LEFT = 0x0000;
public const uint WS_EX_RTLREADING = 0x2000;
public const uint WS_EX_LTRREADING = 0x0000;
public const uint WS_EX_LEFTSCROLLBAR = 0x4000;
public const uint WS_EX_RIGHTSCROLLBAR = 0x0000;
public const uint WS_EX_CONTROLPARENT = 0x10000;
public const uint WS_EX_STATICEDGE = 0x20000;
public const uint WS_EX_APPWINDOW = 0x40000;
public const uint WS_EX_OVERLAPPEDWINDOW = (WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE);
public const uint WS_EX_PALETTEWINDOW = (WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST);
public const uint WS_EX_LAYERED = 0x00080000;
public const uint WS_EX_NOINHERITLAYOUT = 0x00100000; // Disable inheritence of mirroring by children
public const uint WS_EX_LAYOUTRTL = 0x00400000; // Right to left mirroring
public const uint WS_EX_COMPOSITED = 0x02000000;
public const uint WS_EX_NOACTIVATE = 0x08000000;
// ReSharper restore InconsistentNaming
}
internal static class Imports
{
[DllImport("user32.dll")]
internal static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetWindow(IntPtr hWnd, int uCmd);
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
[SuppressUnmanagedCodeSecurity]
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool PeekMessage(out Message msg, IntPtr hWnd, UInt32 msgFilterMin, UInt32 msgFilterMax, UInt32 flags);
[DllImport("dwmapi.dll")]
public static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref Margins pMargins);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
[DllImport("dwmapi.dll")]
public static extern int DwmIsCompositionEnabled(out bool enabled);
[DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
[DllImport("user32.dll")]
public static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
[DllImport("user32.dll")]
public static extern bool GetClientRect(IntPtr hWnd, out Rect lpRect);
[DllImport("user32.dll")]
public static extern bool ClientToScreen(IntPtr hWnd, ref Point lpPoint);
[DllImport("user32.dll", SetLastError = true)]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
}
[StructLayout(LayoutKind.Sequential)]
public struct Margins
{
public int Left;
public int Right;
public int Top;
public int Bottom;
}
[StructLayout(LayoutKind.Sequential)]
public struct Rect
{
public int Left; // x position of upper-left corner
public int Top; // y position of upper-left corner
public int Right; // x position of lower-right corner
public int Bottom; // y position of lower-right corner
}
/// <summary>Windows Message</summary>
[StructLayout(LayoutKind.Sequential)]
public struct Message
{
public IntPtr hWnd;
public UInt32 msg;
public IntPtr wParam;
public IntPtr lParam;
public UInt32 time;
public Point p;
};
}
| 40.466667 | 132 | 0.676936 | [
"MIT"
] | Ilyatk/FFXIVSliceIsRightTracker | Overlay/Imports.cs | 6,072 | 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 Gamma.Entities
{
using System;
public partial class GetCharacteristicsForPM_Result
{
public System.Guid C1CCharacteristicID { get; set; }
public string CharacteristicName { get; set; }
}
}
| 33 | 85 | 0.522727 | [
"Unlicense"
] | Polimat/Gamma | Entities/GetCharacteristicsForPM_Result.cs | 660 | C# |
using Ancheta.Model.Data;
using Microsoft.EntityFrameworkCore;
namespace Ancheta.WebApi.Contexts
{
public class ApplicationDbContext : DbContext
{
public DbSet<Poll> Polls { get; set; }
public DbSet<Answer> Answers { get; set; }
public DbSet<Vote> Votes { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Poll>()
.HasMany(p => p.Answers)
.WithOne(a => a.OwnerPoll)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Answer>()
.HasOne(a => a.OwnerPoll)
.WithMany(p => p.Answers);
modelBuilder.Entity<Vote>()
.HasOne(v => v.OwnerAnswer)
.WithMany(a => a.Votes);
}
}
} | 28.472222 | 83 | 0.531707 | [
"MIT"
] | Mehigh17/Ancheta | Ancheta.WebApi/Contexts/ApplicationDbContext.cs | 1,025 | 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.
using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
namespace System.Security.Cryptography.Asn1
{
[StructLayout(LayoutKind.Sequential)]
internal partial struct Pbkdf2Params
{
private static byte[] s_defaultPrf = { 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x07, 0x05, 0x00 };
internal System.Security.Cryptography.Asn1.Pbkdf2SaltChoice Salt;
internal int IterationCount;
internal byte? KeyLength;
internal System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn Prf;
#if DEBUG
static Pbkdf2Params()
{
Pbkdf2Params decoded = default;
AsnReader reader;
reader = new AsnReader(s_defaultPrf, AsnEncodingRules.DER);
System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn.Decode(reader, out decoded.Prf);
reader.ThrowIfNotEmpty();
}
#endif
internal void Encode(AsnWriter writer)
{
Encode(writer, Asn1Tag.Sequence);
}
internal void Encode(AsnWriter writer, Asn1Tag tag)
{
writer.PushSequence(tag);
Salt.Encode(writer);
writer.WriteInteger(IterationCount);
if (KeyLength.HasValue)
{
writer.WriteInteger(KeyLength.Value);
}
// DEFAULT value handler for Prf.
{
using (AsnWriter tmp = new AsnWriter(AsnEncodingRules.DER))
{
Prf.Encode(tmp);
ReadOnlySpan<byte> encoded = tmp.EncodeAsSpan();
if (!encoded.SequenceEqual(s_defaultPrf))
{
writer.WriteEncodedValue(encoded.ToArray());
}
}
}
writer.PopSequence(tag);
}
internal static Pbkdf2Params Decode(ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet)
{
return Decode(Asn1Tag.Sequence, encoded, ruleSet);
}
internal static Pbkdf2Params Decode(Asn1Tag expectedTag, ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet)
{
AsnReader reader = new AsnReader(encoded, ruleSet);
Decode(reader, expectedTag, out Pbkdf2Params decoded);
reader.ThrowIfNotEmpty();
return decoded;
}
internal static void Decode(AsnReader reader, out Pbkdf2Params decoded)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
Decode(reader, Asn1Tag.Sequence, out decoded);
}
internal static void Decode(AsnReader reader, Asn1Tag expectedTag, out Pbkdf2Params decoded)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
decoded = default;
AsnReader sequenceReader = reader.ReadSequence(expectedTag);
AsnReader defaultReader;
System.Security.Cryptography.Asn1.Pbkdf2SaltChoice.Decode(sequenceReader, out decoded.Salt);
if (!sequenceReader.TryReadInt32(out decoded.IterationCount))
{
sequenceReader.ThrowIfNotEmpty();
}
if (sequenceReader.HasData && sequenceReader.PeekTag().HasSameClassAndValue(Asn1Tag.Integer))
{
if (sequenceReader.TryReadUInt8(out byte tmpKeyLength))
{
decoded.KeyLength = tmpKeyLength;
}
else
{
sequenceReader.ThrowIfNotEmpty();
}
}
if (sequenceReader.HasData && sequenceReader.PeekTag().HasSameClassAndValue(Asn1Tag.Sequence))
{
System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn.Decode(sequenceReader, out decoded.Prf);
}
else
{
defaultReader = new AsnReader(s_defaultPrf, AsnEncodingRules.DER);
System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn.Decode(defaultReader, out decoded.Prf);
}
sequenceReader.ThrowIfNotEmpty();
}
}
}
| 33 | 132 | 0.586517 | [
"MIT"
] | ARhj/corefx | src/Common/src/System/Security/Cryptography/Asn1/Pbkdf2Params.xml.cs | 4,556 | C# |
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace OdbcQueryTool.Converters
{
[ValueConversion(typeof(bool), typeof(Visibility))]
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || value.GetType() != typeof(bool) || targetType != typeof(Visibility))
{
throw new InvalidOperationException();
}
return (bool)value ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || value.GetType() != typeof(Visibility) || targetType != typeof(bool))
{
throw new InvalidOperationException();
}
return (Visibility)value == Visibility.Visible;
}
}
}
| 33.833333 | 103 | 0.623645 | [
"Unlicense"
] | jehugaleahsa/OdbcQueryTool | OdbcQueryTool/Converters/BooleanToVisibilityConverter.cs | 1,017 | C# |
/*
M2Mqtt Project - MQTT Client Library for .Net and GnatMQ MQTT Broker for .NET
Copyright (c) 2014, Paolo Patierno, All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library.
*/
#if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3)
using System;
#else
using Microsoft.SPOT;
#endif
namespace uPLibrary.Networking.M2Mqtt.Messages
{
/// <summary>
/// Event Args class for subscribe request on topics
/// </summary>
public class MqttMsgSubscribeEventArgs : EventArgs
{
#region Properties...
/// <summary>
/// Message identifier
/// </summary>
public ushort MessageId
{
get { return this.messageId; }
internal set { this.messageId = value; }
}
/// <summary>
/// Topics requested to subscribe
/// </summary>
public string[] Topics
{
get { return this.topics; }
internal set { this.topics = value; }
}
/// <summary>
/// List of QOS Levels requested
/// </summary>
public byte[] QoSLevels
{
get { return this.qosLevels; }
internal set { this.qosLevels = value; }
}
#endregion
// message identifier
ushort messageId;
// topics requested to subscribe
string[] topics;
// QoS levels requested
byte[] qosLevels;
/// <summary>
/// Constructor
/// </summary>
/// <param name="messageId">Message identifier for subscribe topics request</param>
/// <param name="topics">Topics requested to subscribe</param>
/// <param name="qosLevels">List of QOS Levels requested</param>
public MqttMsgSubscribeEventArgs(ushort messageId, string[] topics, byte[] qosLevels)
{
this.messageId = messageId;
this.topics = topics;
this.qosLevels = qosLevels;
}
}
}
| 30.892857 | 94 | 0.603854 | [
"MIT"
] | JadeCong/AvatarGame_Unity | Assets/Plugins/MQTT/scripts/Messages/MqttMsgSubscribeEventArgs.cs | 2,595 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("PazzleDrag.Droid")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PazzleDrag.Droid")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// 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")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
| 36.542857 | 84 | 0.756059 | [
"MIT"
] | moonmile/PazzleDrag | PazzleDrag/PazzleDrag.Droid/Properties/AssemblyInfo.cs | 1,282 | C# |
namespace SuperCharactersApp.ViewModels.DTO.SuperPowerViewModels
{
using SuperCharacters.Models;
using SuperCharacters.Services.Mapping.Contracts;
using SuperCharactersApp.ViewModels.Contracts;
using SuperCharactersApp.ViewModels.DTO.ReusableModalModel;
using System.ComponentModel.DataAnnotations;
public class SuperPowersListingViewModel :
IReusableModalViewModel,
IMapTo<SuperPower>,
IMapFrom<SuperPower>
{
public string Id { get; set; }
[Required]
[StringLength(100, MinimumLength = 1)]
[Display(Name ="Name of Superpower")]
public string SuperPowerName { get; set; }
[Required]
public string Type { get; set; }
[Required]
public double Value { get; set; }
public ModalViewModel ModalView { get; set; }
}
}
| 31.925926 | 65 | 0.664733 | [
"MIT"
] | pavsavov/SuperCharacterApp | src/Data/SuperCharactersApp.ViewModels/DTO/SuperPowerViewModels/SuperPowerListingViewModel.cs | 864 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace ForgedOnce.TsLanguageServices.FullSyntaxTree.AstBuilder
{
public static partial class StNonNullExpressionExtensions
{
public static ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StNonNullExpression WithExpression(this ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StNonNullExpression subject, ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.IStExpression expression)
{
subject.expression = expression;
return subject;
}
public static ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StNonNullExpression WithFlags(this ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StNonNullExpression subject, ForgedOnce.TsLanguageServices.FullSyntaxTree.TransportModel.NodeFlags flags)
{
subject.flags = flags;
return subject;
}
public static ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StNonNullExpression WithDecorator(this ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StNonNullExpression subject, Func<ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StDecorator, ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StDecorator> decoratorBuilder)
{
subject.decorators.Add(decoratorBuilder(new ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StDecorator()));
return subject;
}
public static ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StNonNullExpression WithModifier(this ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StNonNullExpression subject, ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.IStModifier modifier)
{
subject.modifiers.Add(modifier);
return subject;
}
}
} | 56.606061 | 355 | 0.769807 | [
"MIT"
] | YevgenNabokov/ForgedOnce.TSLanguageServices | ForgedOnce.TsLanguageServices.FullSyntaxTree/AstBuilder/Generated/StNonNullExpressionExtensions.cs | 1,868 | C# |
using FluentValidation;
namespace Gear.Manager.Core.EntityServices.ApplicationUsers.Commands.AddToRoles
{
public class AddToRolesCommandValidator : AbstractValidator<AddToRolesCommand>
{
public AddToRolesCommandValidator()
{
RuleFor(x => x.UserId).NotNull().NotEmpty();
}
}
}
| 25.076923 | 82 | 0.693252 | [
"MIT"
] | indrivo/bizon360_pm | IndrivoPM/IndrivoPM.Application/EntityServices/ApplicationUsers/Commands/AddToRoles/AddToRolesCommandValidator.cs | 328 | C# |
// Copyright (c) .NET Foundation. 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.Reflection;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.JsonPatch.Operations;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace Microsoft.AspNetCore.Mvc.Formatters.Json
{
/// <summary>
/// Implements a provider of <see cref="ApiDescription"/> to change parameters of
/// type <see cref="IJsonPatchDocument"/> to an array of <see cref="Operation"/>.
/// </summary>
public class JsonPatchOperationsArrayProvider : IApiDescriptionProvider
{
private readonly IModelMetadataProvider _modelMetadataProvider;
/// <summary>
/// Creates a new instance of <see cref="JsonPatchOperationsArrayProvider"/>.
/// </summary>
/// <param name="modelMetadataProvider">The <see cref="IModelMetadataProvider"/>.</param>
public JsonPatchOperationsArrayProvider(IModelMetadataProvider modelMetadataProvider)
{
_modelMetadataProvider = modelMetadataProvider;
}
/// <inheritdoc />
/// <remarks>
/// The order -999 ensures that this provider is executed right after the <c>Microsoft.AspNetCore.Mvc.ApiExplorer.DefaultApiDescriptionProvider</c>.
/// </remarks>
public int Order
{
get { return -999; }
}
/// <inheritdoc />
public void OnProvidersExecuting(ApiDescriptionProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
foreach (var result in context.Results)
{
foreach (var parameterDescription in result.ParameterDescriptions)
{
if (typeof(IJsonPatchDocument).GetTypeInfo().IsAssignableFrom(parameterDescription.Type))
{
parameterDescription.Type = typeof(Operation[]);
parameterDescription.ModelMetadata = _modelMetadataProvider.GetMetadataForType(typeof(Operation[]));
}
}
}
}
/// <inheritdoc />
public void OnProvidersExecuted(ApiDescriptionProviderContext context)
{
}
}
} | 37.892308 | 156 | 0.630126 | [
"Apache-2.0"
] | erravimishracse/Mvc | src/Microsoft.AspNetCore.Mvc.Formatters.Json/JsonPatchOperationsArrayProvider.cs | 2,465 | C# |
using System.Collections.Generic;
namespace MvcFramework.Identity
{
public class Principal
{
public Principal()
{
this.Roles = new List<string>();
}
public string Id { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public List<string> Roles { get; set; }
}
}
| 18.142857 | 47 | 0.553806 | [
"MIT"
] | emilia98/CSharpWebSoftUni | C# Web Basics/10. MVC Introduction - Exercise/SIS/WebServer/Identity/Principal.cs | 383 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// このコードはツールによって生成されました。
// ランタイム バージョン:4.0.30319.34209
//
// このファイルへの変更は、以下の状況下で不正な動作の原因になったり、
// コードが再生成されるときに損失したりします。
// </auto-generated>
//------------------------------------------------------------------------------
namespace MsgPack.Serialization.GeneratedSerializers.MapBased {
[System.CodeDom.Compiler.GeneratedCodeAttribute("MsgPack.Serialization.CodeDomSerializers.CodeDomSerializerBuilder", "0.6.0.0")]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public class MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicGetOnlyPropertyAndConstructorSerializer : MsgPack.Serialization.MessagePackSerializer<MsgPack.Serialization.PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicGetOnlyPropertyAndConstructor> {
private MsgPack.Serialization.MessagePackSerializer<string> _serializer0;
private MsgPack.Serialization.MessagePackSerializer<System.Tuple<string, string, string, MsgPack.Serialization.FileSystemEntry, string, string, string>> _serializer1;
public MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicGetOnlyPropertyAndConstructorSerializer(MsgPack.Serialization.SerializationContext context) :
base(context) {
MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema);
MsgPack.Serialization.PolymorphismSchema[] tupleItemsSchema0 = default(MsgPack.Serialization.PolymorphismSchema[]);
tupleItemsSchema0 = new MsgPack.Serialization.PolymorphismSchema[7];
MsgPack.Serialization.PolymorphismSchema tupleItemSchema0 = default(MsgPack.Serialization.PolymorphismSchema);
tupleItemSchema0 = null;
tupleItemsSchema0[0] = tupleItemSchema0;
MsgPack.Serialization.PolymorphismSchema tupleItemSchema1 = default(MsgPack.Serialization.PolymorphismSchema);
tupleItemSchema1 = null;
tupleItemsSchema0[1] = tupleItemSchema1;
MsgPack.Serialization.PolymorphismSchema tupleItemSchema2 = default(MsgPack.Serialization.PolymorphismSchema);
tupleItemSchema2 = null;
tupleItemsSchema0[2] = tupleItemSchema2;
MsgPack.Serialization.PolymorphismSchema tupleItemSchema3 = default(MsgPack.Serialization.PolymorphismSchema);
System.Collections.Generic.Dictionary<string, System.Type> tupleItemSchema3TypeMap0 = default(System.Collections.Generic.Dictionary<string, System.Type>);
tupleItemSchema3TypeMap0 = new System.Collections.Generic.Dictionary<string, System.Type>(2);
tupleItemSchema3TypeMap0.Add("1", typeof(MsgPack.Serialization.DirectoryEntry));
tupleItemSchema3TypeMap0.Add("0", typeof(MsgPack.Serialization.FileEntry));
tupleItemSchema3 = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicObject(typeof(MsgPack.Serialization.FileSystemEntry), tupleItemSchema3TypeMap0);
tupleItemsSchema0[3] = tupleItemSchema3;
MsgPack.Serialization.PolymorphismSchema tupleItemSchema4 = default(MsgPack.Serialization.PolymorphismSchema);
tupleItemSchema4 = null;
tupleItemsSchema0[4] = tupleItemSchema4;
MsgPack.Serialization.PolymorphismSchema tupleItemSchema5 = default(MsgPack.Serialization.PolymorphismSchema);
tupleItemSchema5 = null;
tupleItemsSchema0[5] = tupleItemSchema5;
MsgPack.Serialization.PolymorphismSchema tupleItemSchema6 = default(MsgPack.Serialization.PolymorphismSchema);
tupleItemSchema6 = null;
tupleItemsSchema0[6] = tupleItemSchema6;
schema0 = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicTuple(typeof(System.Tuple<string, string, string, MsgPack.Serialization.FileSystemEntry, string, string, string>), tupleItemsSchema0);
this._serializer0 = context.GetSerializer<string>(schema0);
MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema);
MsgPack.Serialization.PolymorphismSchema[] tupleItemsSchema1 = default(MsgPack.Serialization.PolymorphismSchema[]);
tupleItemsSchema1 = new MsgPack.Serialization.PolymorphismSchema[7];
MsgPack.Serialization.PolymorphismSchema tupleItemSchema7 = default(MsgPack.Serialization.PolymorphismSchema);
tupleItemSchema7 = null;
tupleItemsSchema1[0] = tupleItemSchema7;
MsgPack.Serialization.PolymorphismSchema tupleItemSchema8 = default(MsgPack.Serialization.PolymorphismSchema);
tupleItemSchema8 = null;
tupleItemsSchema1[1] = tupleItemSchema8;
MsgPack.Serialization.PolymorphismSchema tupleItemSchema9 = default(MsgPack.Serialization.PolymorphismSchema);
tupleItemSchema9 = null;
tupleItemsSchema1[2] = tupleItemSchema9;
MsgPack.Serialization.PolymorphismSchema tupleItemSchema10 = default(MsgPack.Serialization.PolymorphismSchema);
System.Collections.Generic.Dictionary<string, System.Type> tupleItemSchema10TypeMap0 = default(System.Collections.Generic.Dictionary<string, System.Type>);
tupleItemSchema10TypeMap0 = new System.Collections.Generic.Dictionary<string, System.Type>(2);
tupleItemSchema10TypeMap0.Add("1", typeof(MsgPack.Serialization.DirectoryEntry));
tupleItemSchema10TypeMap0.Add("0", typeof(MsgPack.Serialization.FileEntry));
tupleItemSchema10 = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicObject(typeof(MsgPack.Serialization.FileSystemEntry), tupleItemSchema10TypeMap0);
tupleItemsSchema1[3] = tupleItemSchema10;
MsgPack.Serialization.PolymorphismSchema tupleItemSchema11 = default(MsgPack.Serialization.PolymorphismSchema);
tupleItemSchema11 = null;
tupleItemsSchema1[4] = tupleItemSchema11;
MsgPack.Serialization.PolymorphismSchema tupleItemSchema12 = default(MsgPack.Serialization.PolymorphismSchema);
tupleItemSchema12 = null;
tupleItemsSchema1[5] = tupleItemSchema12;
MsgPack.Serialization.PolymorphismSchema tupleItemSchema13 = default(MsgPack.Serialization.PolymorphismSchema);
tupleItemSchema13 = null;
tupleItemsSchema1[6] = tupleItemSchema13;
schema1 = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicTuple(typeof(System.Tuple<string, string, string, MsgPack.Serialization.FileSystemEntry, string, string, string>), tupleItemsSchema1);
this._serializer1 = context.GetSerializer<System.Tuple<string, string, string, MsgPack.Serialization.FileSystemEntry, string, string, string>>(schema1);
}
protected internal override void PackToCore(MsgPack.Packer packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicGetOnlyPropertyAndConstructor objectTree) {
packer.PackMapHeader(1);
this._serializer0.PackTo(packer, "Tuple7MidPolymorphic");
this._serializer1.PackTo(packer, objectTree.Tuple7MidPolymorphic);
}
protected internal override MsgPack.Serialization.PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicGetOnlyPropertyAndConstructor UnpackFromCore(MsgPack.Unpacker unpacker) {
MsgPack.Serialization.PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicGetOnlyPropertyAndConstructor result = default(MsgPack.Serialization.PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicGetOnlyPropertyAndConstructor);
if (unpacker.IsArrayHeader) {
int unpacked = default(int);
int itemsCount = default(int);
itemsCount = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker);
System.Tuple<string, string, string, MsgPack.Serialization.FileSystemEntry, string, string, string> ctorArg0 = default(System.Tuple<string, string, string, MsgPack.Serialization.FileSystemEntry, string, string, string>);
ctorArg0 = null;
System.Tuple<string, string, string, MsgPack.Serialization.FileSystemEntry, string, string, string> nullable = default(System.Tuple<string, string, string, MsgPack.Serialization.FileSystemEntry, string, string, string>);
if ((unpacked < itemsCount)) {
if ((unpacker.Read() == false)) {
throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(0);
}
if (((unpacker.IsArrayHeader == false)
&& (unpacker.IsMapHeader == false))) {
nullable = this._serializer1.UnpackFrom(unpacker);
}
else {
MsgPack.Unpacker disposable = default(MsgPack.Unpacker);
disposable = unpacker.ReadSubtree();
try {
nullable = this._serializer1.UnpackFrom(disposable);
}
finally {
if (((disposable == null)
== false)) {
disposable.Dispose();
}
}
}
}
if (((nullable == null)
== false)) {
ctorArg0 = nullable;
}
unpacked = (unpacked + 1);
result = new MsgPack.Serialization.PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicGetOnlyPropertyAndConstructor(ctorArg0);
}
else {
int itemsCount0 = default(int);
itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker);
System.Tuple<string, string, string, MsgPack.Serialization.FileSystemEntry, string, string, string> ctorArg00 = default(System.Tuple<string, string, string, MsgPack.Serialization.FileSystemEntry, string, string, string>);
ctorArg00 = null;
for (int i = 0; (i < itemsCount0); i = (i + 1)) {
string key = default(string);
string nullable0 = default(string);
nullable0 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(MsgPack.Serialization.PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicGetOnlyPropertyAndConstructor), "MemberName");
if (((nullable0 == null)
== false)) {
key = nullable0;
}
else {
throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName");
}
if ((key == "Tuple7MidPolymorphic")) {
System.Tuple<string, string, string, MsgPack.Serialization.FileSystemEntry, string, string, string> nullable1 = default(System.Tuple<string, string, string, MsgPack.Serialization.FileSystemEntry, string, string, string>);
if ((unpacker.Read() == false)) {
throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i);
}
if (((unpacker.IsArrayHeader == false)
&& (unpacker.IsMapHeader == false))) {
nullable1 = this._serializer1.UnpackFrom(unpacker);
}
else {
MsgPack.Unpacker disposable0 = default(MsgPack.Unpacker);
disposable0 = unpacker.ReadSubtree();
try {
nullable1 = this._serializer1.UnpackFrom(disposable0);
}
finally {
if (((disposable0 == null)
== false)) {
disposable0.Dispose();
}
}
}
if (((nullable1 == null)
== false)) {
ctorArg00 = nullable1;
}
}
else {
unpacker.Skip();
}
}
result = new MsgPack.Serialization.PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicGetOnlyPropertyAndConstructor(ctorArg00);
}
return result;
}
private static T @__Conditional<T>(bool condition, T whenTrue, T whenFalse)
{
if (condition) {
return whenTrue;
}
else {
return whenFalse;
}
}
}
}
| 68.129534 | 293 | 0.633965 | [
"Apache-2.0"
] | sosan/msgpack-cli | test/MsgPack.UnitTest/gen/map/MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7MidPolymorphicGetOnlyPropertyAndConstructorSerializer.cs | 13,323 | C# |
namespace Machete.X12Schema.V5010.Maps
{
using X12;
using X12.Configuration;
public class L2010AA_837IMap :
X12LayoutMap<L2010AA_837I, X12Entity>
{
public L2010AA_837IMap()
{
Id = "2010AA";
Name = "Billing Provider Name";
Segment(x => x.BillingProvider, 0, x => x.IsRequired());
Segment(x => x.Address, 1, x => x.IsRequired());
Segment(x => x.GeographicInformation, 2, x => x.IsRequired());
Segment(x => x.TaxIdNumber, 3, x => x.IsRequired());
Segment(x => x.ContactInformation, 4);
}
}
} | 29.090909 | 74 | 0.5375 | [
"Apache-2.0"
] | AreebaAroosh/Machete | src/Machete.X12Schema/Generated/V5010/Layouts/Maps/L2010AA_837IMap.cs | 642 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using MedliSystem = Medli.System;
using System.IO;
using Medli.System;
namespace Medli.Apps
{
public class rm : Command
{
public override string Name
{
get
{
return "rm";
}
}
public override string Summary
{
get
{
return @"Removes the specified file/directory
Directory: rm -r [arg]
File: rm [arg]";
}
}
public override void Execute(string param)
{
string[] args = param.Split(' ');
if (args[0] == "-r")
{
FS.del(args[1], true);
}
else
{
FS.del(args[0], false);
}
}
}
} | 14.136364 | 49 | 0.599678 | [
"BSD-3-Clause-Clear"
] | Siaranite-Solutions/Medli | Medli/Kernel/Utils/Filesystem/rm.cs | 624 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UMA.CharacterSystem;
namespace UMA
{
public class SkeletonDNAConverterPlugin : DynamicDNAPlugin
{
#region FIELDS
[SerializeField]
private List<SkeletonModifier> _skeletonModifiers = new List<SkeletonModifier>();
#endregion
#region PUBLIC PROPERTIES
public List<SkeletonModifier> skeletonModifiers
{
get { return _skeletonModifiers; }
set { _skeletonModifiers = value; }
}
#endregion
#region PUBLIC METHODS
public void AddModifier(SkeletonModifier modifier)
{
_skeletonModifiers.Add(modifier);
}
#endregion
#region REQUIRED DYNAMICDNAPLUGIN METHODS PROPERTIES
/// <summary>
/// Returns a dictionary of all the dna names in use by the plugin and the entries in its converter list that reference them
/// </summary>
/// <returns></returns>
public override Dictionary<string, List<int>> IndexesForDnaNames
{
get
{
var dict = new Dictionary<string, List<int>>();
for (int i = 0; i < _skeletonModifiers.Count; i++)
{
var skelModsUsedNames = SkeletonModifierUsedDNANames(_skeletonModifiers[i]);
for (int ci = 0; ci < skelModsUsedNames.Count; ci++)
{
if (!dict.ContainsKey(skelModsUsedNames[ci]))
dict.Add(skelModsUsedNames[ci], new List<int>());
dict[skelModsUsedNames[ci]].Add(i);
}
}
return dict;
}
}
/// <summary>
/// Apply the modifiers using the given dna (determined by the typehash)
/// </summary>
/// <param name="umaData"></param>
/// <param name="skeleton"></param>
/// <param name="dnaTypeHash"></param>
public override void ApplyDNA(UMAData umaData, UMASkeleton skeleton, int dnaTypeHash)
{
var umaDna = umaData.GetDna(dnaTypeHash);
var masterWeightCalc = masterWeight.GetWeight(umaDna);
if (masterWeightCalc == 0f)
return;
for (int i = 0; i < _skeletonModifiers.Count; i++)
{
_skeletonModifiers[i].umaDNA = umaDna;
var thisHash = (_skeletonModifiers[i].hash != 0) ? _skeletonModifiers[i].hash : UMAUtils.StringToHash(_skeletonModifiers[i].hashName);
//check skeleton has the bone we want to change
if (!skeleton.HasBone(thisHash))
{
Debug.LogWarning("You were trying to apply skeleton modifications to a bone that didn't exist (" + _skeletonModifiers[i].hashName + ") on " + umaData.gameObject.name);
continue;
}
//With these ValueX.x is the calculated value and ValueX.y is min and ValueX.z is max
var thisValueX = _skeletonModifiers[i].CalculateValueX(umaDna);
var thisValueY = _skeletonModifiers[i].CalculateValueY(umaDna);
var thisValueZ = _skeletonModifiers[i].CalculateValueZ(umaDna);
if (_skeletonModifiers[i].property == SkeletonModifier.SkeletonPropType.Position)
{
skeleton.SetPositionRelative(thisHash,
new Vector3(
Mathf.Clamp(thisValueX.x, thisValueX.y, thisValueX.z),
Mathf.Clamp(thisValueY.x, thisValueY.y, thisValueY.z),
Mathf.Clamp(thisValueZ.x, thisValueZ.y, thisValueZ.z)), masterWeightCalc);
}
else if (_skeletonModifiers[i].property == SkeletonModifier.SkeletonPropType.Rotation)
{
skeleton.SetRotationRelative(thisHash,
Quaternion.Euler(new Vector3(
Mathf.Clamp(thisValueX.x, thisValueX.y, thisValueX.z),
Mathf.Clamp(thisValueY.x, thisValueY.y, thisValueY.z),
Mathf.Clamp(thisValueZ.x, thisValueZ.y, thisValueZ.z))), masterWeightCalc);
}
else if (_skeletonModifiers[i].property == SkeletonModifier.SkeletonPropType.Scale)
{
//If there are two sets of skeletonModifiers and both are at 50% it needs to apply them both but the result should be cumulative
//so we need to work out the difference this one is making, weight that and add it to the current scale of the bone
var scale = new Vector3(
Mathf.Clamp(thisValueX.x, thisValueX.y, thisValueX.z),
Mathf.Clamp(thisValueY.x, thisValueY.y, thisValueY.z),
Mathf.Clamp(thisValueZ.x, thisValueZ.y, thisValueZ.z));
//we cant use val.value here because the initial values always need to be applied
var defaultVal = SkeletonModifier.skelAddDefaults[SkeletonModifier.SkeletonPropType.Scale].x;
var scaleDiff = new Vector3(scale.x - defaultVal,
scale.y - defaultVal,
scale.z - defaultVal);
var weightedScaleDiff = scaleDiff * masterWeightCalc;
var fullScale = skeleton.GetScale(_skeletonModifiers[i].hash) + weightedScaleDiff;
skeleton.SetScale(thisHash, fullScale);
}
}
}
#endregion
#region DYNAMICDNAPLUGIN EDITOR OVERRIDES
#if UNITY_EDITOR
public override string PluginHelp
{
get { return "Skeleton DNA Converters use dna values to transform the bones in an avatars skeleton."; }
}
public override string[] ImportSettingsMethods
{
get
{
return new string[]
{
"Add",
"Replace",
"Overwrite",
"AddOverwrite"
};
}
}
public override float GetListFooterHeight
{
get
{
return 16f + (/*EditorGUIUtility.singleLineHeight +*/ (EditorGUIUtility.standardVerticalSpacing * 2));
}
}
#pragma warning disable 618 //disable obsolete warning
/// <summary>
/// Imports SkeletomModifiers from another object into this SkeletonModifiersDNAConverterPlugin
/// </summary>
/// <param name="pluginToImport">You can import another SkeletonModifiersDNAConverterPlugin or settings from a legacy DynamicDNAConverterBehaviour prefab</param>
/// <param name="importMethod">Use 0 to Add to the existing list, 1 to Replace the existing list, 2 to only Overwrite anything in the existing list with matching modifiers in the incoming list, or 3 to Overwrite any existing entries and then Add any entries that were not already in the existing list</param>
/// <returns>True if any settings were imported successfully, otherwise false</returns>
public override bool ImportSettings(Object pluginToImport, int importMethod)
{
List<SkeletonModifier> importedSkeletonModifiers = new List<SkeletonModifier>();
bool isLegacy = false;
if (pluginToImport.GetType() == this.GetType())
importedSkeletonModifiers = (pluginToImport as SkeletonDNAConverterPlugin)._skeletonModifiers;
else if(pluginToImport.GetType().IsAssignableFrom(typeof(DynamicDNAConverterController)))
{
var skelModPlugs = (pluginToImport as DynamicDNAConverterController).GetPlugins(typeof(SkeletonDNAConverterPlugin));
if(skelModPlugs.Count > 0)
{
importedSkeletonModifiers = (skelModPlugs[0] as SkeletonDNAConverterPlugin)._skeletonModifiers;
}
}
else
{
if (typeof(GameObject).IsAssignableFrom(pluginToImport.GetType()))
{
var DDCB = (pluginToImport as GameObject).GetComponent<DynamicDNAConverterBehaviour>();
if(DDCB != null)
{
importedSkeletonModifiers = DDCB.skeletonModifiers;
//hmm this is not always the case because of the backwards compatible property giving us the first found skelModsPlugin aswell
//so if there is no converter controller, *then* its legacy-
//or is it? the user could still assign a controller without upgrading and then try and drag the behaviour in here
//UMA2.8+ FixDNAPrefabs ConverterController doesn't do this backwards compatibility now
//if(DDCB.ConverterController == null)
isLegacy = true;
}
}
}
if(importedSkeletonModifiers != null)
{
// add the modifiers- if the import method is Replace this is a new list
var currentModifiers = importMethod == 1 ? new List<SkeletonModifier>() : _skeletonModifiers;
var incomingModifiers = importedSkeletonModifiers;
List<string> existingDNANames = new List<string>();
if (DNAAsset != null)
existingDNANames.AddRange(DNAAsset.Names);
List<string> missingDNANames = new List<string>();
//If any dnanames are misisng give the user the option to only overwrite matching dna names
//or add the missing dna names and continue
//or cancel
//string nameToCheck = "";
bool existed = false;
//if the names in the dnaAsset get changed during this process we need to save that too
bool updateDNAAsset = false;
for (int i = 0; i < incomingModifiers.Count; i++)
{
//if the Add method is OverwriteAndAdd we need to check dnanames in all the incoming converters
//otherwise we only need to check names for incoming converters that have a matching one in the current list
//was Add = 0 Replace = 1 Overwrite = 2 AddOverwrite = 3
if (importMethod == 2)
{
existed = false;
for (int ci = 0; ci < currentModifiers.Count; ci++)
{
if ((currentModifiers[ci].hash == incomingModifiers[i].hash) && currentModifiers[ci].property == incomingModifiers[i].property)
{
existed = true;
break;
}
}
if (!existed)
continue;
}
var usedDNANames = SkeletonModifierUsedDNANames(incomingModifiers[i], isLegacy);
for(int nc = 0; nc < usedDNANames.Count; nc++)
{
if (!existingDNANames.Contains(usedDNANames[nc]) && !missingDNANames.Contains(usedDNANames[nc]))
missingDNANames.Add(usedDNANames[nc]);
}
}
if (missingDNANames.Count > 0 && DNAAsset != null)
{
string missingDNAMsg = "";
if (missingDNANames.Count > 10)
{
missingDNAMsg = "There were over 10 missing dna names in this converter compared to the one you want to overwrite from";
}
else
{
missingDNAMsg = "The following dna names were missing in this converter compared to the one you want to overwrite from: ";
missingDNAMsg += string.Join(", ", missingDNANames.ToArray());
}
missingDNAMsg += ". Please choose how you would like to proceed.";
//options: "Only Overwrite Existing DNA" "Add Missing DNA" "Cancel"
var missingDNAOption = EditorUtility.DisplayDialogComplex("Missing DNA in Current Converter", missingDNAMsg, "Only Overwrite Existing DNA", "Add Missing DNA", "Cancel");
if (missingDNAOption == 2)
return false;
else if (missingDNAOption == 1)
{
//add the missing names
var assetNames = new List<string>(DNAAsset.Names);
assetNames.AddRange(missingDNANames);
DNAAsset.Names = assetNames.ToArray();
existingDNANames.AddRange(missingDNANames);
updateDNAAsset = true;
}
//now we just add any settings for DNANames that exist, since the ones we need will have either been added or the user knows they will be skipped
}
else if (DNAAsset == null)
{
//the inspector will sort this out later
}
//if the method is add or overwriteAdd we need to add any missing ones (if the method is replace the list will be empty so everything will get added here)
for (int i = 0; i < incomingModifiers.Count; i++)
{
existed = false;
for (int ci = 0; ci < currentModifiers.Count; ci++)
{
if ((currentModifiers[ci].hash == incomingModifiers[i].hash) && currentModifiers[ci].property == incomingModifiers[i].property)
{
existed = true;
if (importMethod == 2 || importMethod == 3)
{
//handle the overwrites
currentModifiers[ci].valuesX.min = incomingModifiers[i].valuesX.min;
currentModifiers[ci].valuesX.max = incomingModifiers[i].valuesX.max;
currentModifiers[ci].valuesX.val.value = incomingModifiers[i].valuesX.val.value;
//now currentModifiers should only ever have modifyingDNA but incomingModifiers might contain data in legacy 'modifiers' OR in 'modifyingDNA'
if (isLegacy)
ProcessSkelModOverwrites(currentModifiers[ci].valuesX.val.modifyingDNA, incomingModifiers[i].valuesX.val.modifiers, existingDNANames);
else
ProcessSkelModOverwrites(currentModifiers[ci].valuesX.val.modifyingDNA, incomingModifiers[i].valuesX.val.modifyingDNA, existingDNANames);
currentModifiers[ci].valuesY.min = incomingModifiers[i].valuesY.min;
currentModifiers[ci].valuesY.max = incomingModifiers[i].valuesY.max;
currentModifiers[ci].valuesY.val.value = incomingModifiers[i].valuesY.val.value;
if (isLegacy)
ProcessSkelModOverwrites(currentModifiers[ci].valuesY.val.modifyingDNA, incomingModifiers[i].valuesY.val.modifiers, existingDNANames);
else
ProcessSkelModOverwrites(currentModifiers[ci].valuesY.val.modifyingDNA, incomingModifiers[i].valuesY.val.modifyingDNA, existingDNANames);
currentModifiers[ci].valuesZ.min = incomingModifiers[i].valuesZ.min;
currentModifiers[ci].valuesZ.max = incomingModifiers[i].valuesZ.max;
currentModifiers[ci].valuesZ.val.value = incomingModifiers[i].valuesZ.val.value;
if (isLegacy)
ProcessSkelModOverwrites(currentModifiers[ci].valuesZ.val.modifyingDNA, incomingModifiers[i].valuesZ.val.modifiers, existingDNANames);
else
ProcessSkelModOverwrites(currentModifiers[ci].valuesZ.val.modifyingDNA, incomingModifiers[i].valuesZ.val.modifyingDNA, existingDNANames);
}
break;
}
}
if (!existed && importMethod != 2)//if the method is anything other overwrite add the missing modifier
{
currentModifiers.Add(new SkeletonModifier(incomingModifiers[i], true));
}
}
_skeletonModifiers = currentModifiers;
EditorUtility.SetDirty(this);
if (updateDNAAsset)
{
EditorUtility.SetDirty(DNAAsset);
}
AssetDatabase.SaveAssets();
return true;
}
else
{
return false;
}
}
#pragma warning restore 618
#pragma warning disable 618 //disable obsolete warning
/// <summary>
/// Converts the legacy incoming values into DNAEvaluators and then overwrites any DNAEvaluators in the current settings with the settings from the incoming DNAEvaluators if the dnaName matches, otherwise adds a new evaluator for the dnaName
/// </summary>
/// <param name="existingDNANames">If the dnaName used by a DNAEvaluator in the incoming settings is not found in this list it will not be processed</param>
private void ProcessSkelModOverwrites(DNAEvaluatorList currentMods, List<SkeletonModifier.spVal.spValValue.spValModifier> incomingMods, List<string> existingDNANames)
{
SkeletonModifier.spVal.spValValue tempValValue = new SkeletonModifier.spVal.spValValue();
tempValValue.modifiers = new List<SkeletonModifier.spVal.spValValue.spValModifier>(incomingMods);
tempValValue.ConvertToDNAEvaluators();
ProcessSkelModOverwrites(currentMods, tempValValue.modifyingDNA, existingDNANames);
}
#pragma warning restore 618
/// <summary>
/// overwrites any DNAEvaluators in the current settings with the settings from the incoming DNAEvaluators if the dnaName matches, otherwise adds a new evaluator for the dnaName
/// </summary>
/// <param name="existingDNANames">If the dnaName used by a DNAEvaluator in the incoming settings is not found in this list it will not be processed</param>
private void ProcessSkelModOverwrites(DNAEvaluatorList currentMods, DNAEvaluatorList incomingMods, List<string> existingDNANames)
{
for (int i = 0; i < incomingMods.Count; i++)
{
if (!existingDNANames.Contains(incomingMods[i].dnaName))
continue;
var foundInCurrent = false;
for (int ci = 0; ci < currentMods.Count; ci++)
{
if (currentMods[ci].dnaName == incomingMods[i].dnaName)
{
currentMods[ci].calcOption = incomingMods[i].calcOption;
currentMods[ci].evaluator = new DNAEvaluationGraph(incomingMods[i].evaluator);
currentMods[ci].multiplier = incomingMods[i].multiplier;
foundInCurrent = true;
}
}
if (!foundInCurrent)
{
currentMods.Add(new DNAEvaluator(incomingMods[i].dnaName, incomingMods[i].evaluator, incomingMods[i].multiplier, incomingMods[i].calcOption));
}
}
}
#endif
#endregion
#region PRIVATE METHODS
#pragma warning disable 618 //disable obsolete warning
/// <summary>
/// Returns the DNANames used by the given skeleton modifier,
/// optionally filtering by a given name, in which case the returned list count will only be greater than zero if the modifier used the name.
/// This can be used to query if any modifiers were using the given name
/// </summary>
/// <returns></returns>
private List<string> SkeletonModifierUsedDNANames(SkeletonModifier skeletonModifier, bool searchLegacy = false, string dnaName = "")
{
List<string> usedNames = new List<string>();
//names from new _modifyingDNA in the modifiers
var xNames = skeletonModifier.valuesX.val.modifyingDNA.UsedDNANames;
var yNames = skeletonModifier.valuesY.val.modifyingDNA.UsedDNANames;
var zNames = skeletonModifier.valuesZ.val.modifyingDNA.UsedDNANames;
for (int i = 0; i < xNames.Count; i++)
{
if (!usedNames.Contains(xNames[i]) && (dnaName == "" || (!string.IsNullOrEmpty(dnaName) && xNames[i] == dnaName)))
usedNames.Add(xNames[i]);
}
for (int i = 0; i < yNames.Count; i++)
{
if (!usedNames.Contains(yNames[i]) && (dnaName == "" || (!string.IsNullOrEmpty(dnaName) && yNames[i] == dnaName)))
usedNames.Add(yNames[i]);
}
for (int i = 0; i < zNames.Count; i++)
{
if (!usedNames.Contains(zNames[i]) && (dnaName == "" || (!string.IsNullOrEmpty(dnaName) && zNames[i] == dnaName)))
usedNames.Add(zNames[i]);
}
if (searchLegacy)
{
//legacy names
for (int xi = 0; xi < skeletonModifier.valuesX.val.modifiers.Count; xi++)
{
if (!string.IsNullOrEmpty(skeletonModifier.valuesX.val.modifiers[xi].DNATypeName) &&
dnaName == "" || (!string.IsNullOrEmpty(dnaName) && skeletonModifier.valuesX.val.modifiers[xi].DNATypeName == dnaName))
{
if (!usedNames.Contains(skeletonModifier.valuesX.val.modifiers[xi].DNATypeName))
usedNames.Add(skeletonModifier.valuesX.val.modifiers[xi].DNATypeName);
}
}
for (int yi = 0; yi < skeletonModifier.valuesY.val.modifiers.Count; yi++)
{
if (!string.IsNullOrEmpty(skeletonModifier.valuesY.val.modifiers[yi].DNATypeName) &&
dnaName == "" || (!string.IsNullOrEmpty(dnaName) && skeletonModifier.valuesY.val.modifiers[yi].DNATypeName == dnaName))
{
if (!usedNames.Contains(skeletonModifier.valuesY.val.modifiers[yi].DNATypeName))
usedNames.Add(skeletonModifier.valuesY.val.modifiers[yi].DNATypeName);
}
}
for (int zi = 0; zi < skeletonModifier.valuesZ.val.modifiers.Count; zi++)
{
if (!string.IsNullOrEmpty(skeletonModifier.valuesZ.val.modifiers[zi].DNATypeName) &&
dnaName == "" || (!string.IsNullOrEmpty(dnaName) && skeletonModifier.valuesZ.val.modifiers[zi].DNATypeName == dnaName))
{
if (!usedNames.Contains(skeletonModifier.valuesZ.val.modifiers[zi].DNATypeName))
usedNames.Add(skeletonModifier.valuesZ.val.modifiers[zi].DNATypeName);
}
}
}
return usedNames;
}
#pragma warning restore 618 //restore obsolete warning
#endregion
}
}
| 41.28976 | 310 | 0.706205 | [
"MIT"
] | DigitalPainting/UMA | UMAProject/Assets/UMA/Core/Scripts/DNAPlugins/SkeletonDNAConverterPlugin.cs | 18,954 | C# |
using Cake.Core;
using Cake.Core.IO;
namespace Cake.Bower
{
/// <summary>
/// Bower link settings
/// </summary>
public class BowerLinkSettings : BowerRunnerSettings
{
/// <summary>
/// Bower link settings
/// </summary>
public BowerLinkSettings() : base("link") { }
/// <summary>
/// Evaluate options
/// </summary>
/// <param name="args"></param>
protected override void EvaluateCore(ProcessArgumentBuilder args)
{
if (!string.IsNullOrWhiteSpace(Name))
{
args.Append(Name);
if (!string.IsNullOrWhiteSpace(LocalName))
args.Append(LocalName);
}
base.EvaluateCore(args);
}
/// <summary>
/// Name of the folder to link to
/// </summary>
public string Name { get; set; }
/// <summary>
/// LocalName
/// </summary>
public string LocalName { get; set; }
/// <summary>
/// Set the name to link to
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public BowerLinkSettings WithName(string name)
{
Name = name;
return this;
}
/// <summary>
/// Set the local name
/// </summary>
/// <param name="localName"></param>
/// <returns></returns>
public BowerLinkSettings WithLocalName(string localName)
{
LocalName = localName;
return this;
}
}
} | 25.967742 | 73 | 0.48882 | [
"MIT"
] | cake-contrib/Cake.Bower | src/Cake.Bower/BowerLinkSettings.cs | 1,612 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** 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.AzureNextGen.Network.V20190601.Outputs
{
[OutputType]
public sealed class ApplicationGatewayRequestRoutingRuleResponse
{
/// <summary>
/// Backend address pool resource of the application gateway.
/// </summary>
public readonly Outputs.SubResourceResponse? BackendAddressPool;
/// <summary>
/// Backend http settings resource of the application gateway.
/// </summary>
public readonly Outputs.SubResourceResponse? BackendHttpSettings;
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
public readonly string? Etag;
/// <summary>
/// Http listener resource of the application gateway.
/// </summary>
public readonly Outputs.SubResourceResponse? HttpListener;
/// <summary>
/// Resource ID.
/// </summary>
public readonly string? Id;
/// <summary>
/// Name of the request routing rule that is unique within an Application Gateway.
/// </summary>
public readonly string? Name;
/// <summary>
/// Provisioning state of the request routing rule resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
/// </summary>
public readonly string? ProvisioningState;
/// <summary>
/// Redirect configuration resource of the application gateway.
/// </summary>
public readonly Outputs.SubResourceResponse? RedirectConfiguration;
/// <summary>
/// Rewrite Rule Set resource in Basic rule of the application gateway.
/// </summary>
public readonly Outputs.SubResourceResponse? RewriteRuleSet;
/// <summary>
/// Rule type.
/// </summary>
public readonly string? RuleType;
/// <summary>
/// Type of the resource.
/// </summary>
public readonly string? Type;
/// <summary>
/// URL path map resource of the application gateway.
/// </summary>
public readonly Outputs.SubResourceResponse? UrlPathMap;
[OutputConstructor]
private ApplicationGatewayRequestRoutingRuleResponse(
Outputs.SubResourceResponse? backendAddressPool,
Outputs.SubResourceResponse? backendHttpSettings,
string? etag,
Outputs.SubResourceResponse? httpListener,
string? id,
string? name,
string? provisioningState,
Outputs.SubResourceResponse? redirectConfiguration,
Outputs.SubResourceResponse? rewriteRuleSet,
string? ruleType,
string? type,
Outputs.SubResourceResponse? urlPathMap)
{
BackendAddressPool = backendAddressPool;
BackendHttpSettings = backendHttpSettings;
Etag = etag;
HttpListener = httpListener;
Id = id;
Name = name;
ProvisioningState = provisioningState;
RedirectConfiguration = redirectConfiguration;
RewriteRuleSet = rewriteRuleSet;
RuleType = ruleType;
Type = type;
UrlPathMap = urlPathMap;
}
}
}
| 33.811321 | 127 | 0.615792 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Network/V20190601/Outputs/ApplicationGatewayRequestRoutingRuleResponse.cs | 3,584 | C# |
using System.Drawing;
namespace ElephantStarter.Domain.Services;
/// <summary>
/// Image service.
/// </summary>
public interface IImageService
{
/// <summary>
/// Auto start bitmap.
/// </summary>
public Bitmap AutoStart { get; }
/// <summary>
/// Exit bitmap.
/// </summary>
Bitmap Exit { get; }
/// <summary>
/// Folder bitmap.
/// </summary>
Bitmap Folder { get; }
/// <summary>
/// Restart bitmap.
/// </summary>
Bitmap Restart { get; }
/// <summary>
/// Settings (gear) bitmap.
/// </summary>
Bitmap Settings { get; }
/// <summary>
/// ToggleVisibility bitmap.
/// </summary>
Bitmap ToggleVisibility { get; }
} | 16.615385 | 42 | 0.608025 | [
"MIT"
] | SquirtingElephant/ElephantStarter | ElephantStarter.Domain/Services/IImageService.cs | 650 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Domain
{
/// <summary>
/// StationDetailInfo Data Structure.
/// </summary>
public class StationDetailInfo : AlipayObject
{
/// <summary>
/// 站点编码
/// </summary>
[JsonPropertyName("code")]
public string Code { get; set; }
/// <summary>
/// 站点外部编码
/// </summary>
[JsonPropertyName("ext_code")]
public string ExtCode { get; set; }
/// <summary>
/// 站点中文名称
/// </summary>
[JsonPropertyName("name")]
public string Name { get; set; }
}
}
| 22.551724 | 49 | 0.525994 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Domain/StationDetailInfo.cs | 688 | 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("ReferenceConflictAnalyzer.CommandLine")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ReferenceConflictAnalyzer.CommandLine")]
[assembly: AssemblyCopyright("Copyright © 2018 Mykola Tarasyuk")]
[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("41d0f74e-963c-49dc-8757-324e2b5fc995")]
// 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.10.0")]
[assembly: AssemblyFileVersion("1.0.10.0")]
| 39.459459 | 84 | 0.756849 | [
"MIT"
] | rstm-sf/reference-conflicts-analyzer | ReferenceConflictAnalyzer.CommandLine/Properties/AssemblyInfo.cs | 1,463 | C# |
namespace BovineLabs.Event.Samples.MultiWorld
{
using Unity.Entities;
using UnityEngine.Scripting;
public class FixedSystemGroup : ComponentSystemGroup
{
[Preserve]
public FixedSystemGroup()
{
#if UNITY_ENTITIES_0_16_OR_NEWER
this.FixedRateManager = new UpdateTimeFour();
#else
int count = -1;
this.UpdateCallback = group =>
{
if (count == 3)
{
count = -1;
return true;
}
count++;
return false;
};
#endif
}
#if UNITY_ENTITIES_0_16_OR_NEWER
public class UpdateTimeFour : IFixedRateManager
{
private int count = -1;
public bool ShouldGroupUpdate(ComponentSystemGroup @group)
{
if (this.count == 3)
{
this.count = -1;
return true;
}
this.Timestep = group.Time.DeltaTime * 4;
this.count++;
return false;
}
public float Timestep { get; set; }
}
#endif
}
} | 22.425926 | 70 | 0.464079 | [
"MIT"
] | tertle/com.bovinelabs.event | Samples~/MultiWorld/FixedSystemGroup.cs | 1,211 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Stock.Api.DTOs;
using Stock.Api.Extensions;
using Stock.AppService.Services;
using Stock.Model.Entities;
namespace Stock.Api.Controllers
{
[Produces("application/json")]
[Route("api/provider")]
[ApiController]
public class ProviderController : ControllerBase
{
private ProviderService service;
private readonly IMapper mapper;
public ProviderController(ProviderService service, IMapper mapper)
{
this.service = service;
this.mapper = mapper;
}
[HttpPost]
public ActionResult Post([FromBody] ProviderDTO value)
{
TryValidateModel(value);
try
{
var provider = this.mapper.Map<Provider>(value);
this.service.Create(provider);
value.Id = provider.Id;
return Ok(new { Success = true, Message = "", data = value });
}
catch
{
return Ok(new { Success = false, Message = "The name is already in use" });
}
}
[HttpGet]
public ActionResult<IEnumerable<ProviderDTO>> Get()
{
try
{
var result = this.service.GetAll();
return this.mapper.Map<IEnumerable<ProviderDTO>>(result).ToList();
}
catch (Exception)
{
return StatusCode(500);
}
}
[HttpGet("{id}")]
public ActionResult<ProviderDTO> Get(string id)
{
try
{
var result = this.service.Get(id);
return this.mapper.Map<ProviderDTO>(result);
}
catch (Exception)
{
return StatusCode(500);
}
}
[HttpPut("{id}")]
public void Put(string id, [FromBody] ProviderDTO value)
{
var provider = this.service.Get(id);
TryValidateModel(value);
this.mapper.Map<ProviderDTO, Provider>(value, provider);
this.service.Update(provider);
}
/// <summary>
/// Permite borrar una instancia
/// </summary>
/// <param name="id">Identificador de la instancia a borrar</param>
[HttpDelete("{id}")]
public ActionResult Delete(string id)
{
var provider = this.service.Get(id);
this.service.Delete(provider);
return Ok(new { Success = true, Message = "", data = id });
}
[HttpPost("search")]
public ActionResult Search([FromBody] ProviderSearchDTO model)
{
Expression<Func<Provider, bool>> filter = x => !string.IsNullOrWhiteSpace(x.Id);
if (!string.IsNullOrWhiteSpace(model.Name))
{
filter = filter.AndOrCustom(
x => x.Name.ToUpper().Contains(model.Name.ToUpper()),
model.Condition.Equals(ActionDto.AND));
}
if (!string.IsNullOrWhiteSpace(model.Email))
{
filter = filter.AndOrCustom(
x => x.Email.ToUpper().Contains(model.Email.ToUpper()),
model.Condition.Equals(ActionDto.AND));
}
var providers = this.service.Search(filter);
return Ok(providers);
}
}
} | 29.338843 | 92 | 0.528732 | [
"Apache-2.0"
] | nicomontes0/HexactaLabs-NetCore_React-Initial | Stock.Api/Controllers/ProviderController.cs | 3,550 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.ServiceBus
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// NamespacesOperations operations.
/// </summary>
internal partial class NamespacesOperations : IServiceOperations<ServiceBusManagementClient>, INamespacesOperations
{
/// <summary>
/// Initializes a new instance of the NamespacesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal NamespacesOperations(ServiceBusManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the ServiceBusManagementClient
/// </summary>
public ServiceBusManagementClient Client { get; private set; }
/// <summary>
/// Gets all the available namespaces within the subscription, irrespective of
/// the resource groups.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" />
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SBNamespace>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.ServiceBus/namespaces").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SBNamespace>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SBNamespace>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the available namespaces within a resource group.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SBNamespace>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SBNamespace>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SBNamespace>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a service namespace. Once created, this namespace's
/// resource manifest is immutable. This operation is idempotent.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639408.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a namespace resource.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<SBNamespace>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, SBNamespace parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<SBNamespace> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes an existing namespace. This operation also removes all associated
/// resources under the namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639389.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a description for the specified namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639379.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<SBNamespace>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (namespaceName != null)
{
if (namespaceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50);
}
if (namespaceName.Length < 6)
{
throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SBNamespace>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SBNamespace>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Updates a service namespace. Once created, this namespace's resource
/// manifest is immutable. This operation is idempotent.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update a namespace resource.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<SBNamespace>> UpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, SBNamespaceUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (namespaceName != null)
{
if (namespaceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50);
}
if (namespaceName.Length < 6)
{
throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6);
}
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201 && (int)_statusCode != 202)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SBNamespace>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SBNamespace>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SBNamespace>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of IP Filter rules for a Namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<IpFilterRule>>> ListIpFilterRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (namespaceName != null)
{
if (namespaceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50);
}
if (namespaceName.Length < 6)
{
throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListIpFilterRules", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/ipfilterrules").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<IpFilterRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<IpFilterRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates an IpFilterRule for a Namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='ipFilterRuleName'>
/// The IP Filter Rule name.
/// </param>
/// <param name='parameters'>
/// The Namespace IpFilterRule.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IpFilterRule>> CreateOrUpdateIpFilterRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string ipFilterRuleName, IpFilterRule parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (namespaceName != null)
{
if (namespaceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50);
}
if (namespaceName.Length < 6)
{
throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6);
}
}
if (ipFilterRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ipFilterRuleName");
}
if (ipFilterRuleName != null)
{
if (ipFilterRuleName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "ipFilterRuleName", 1);
}
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("ipFilterRuleName", ipFilterRuleName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdateIpFilterRule", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/ipfilterrules/{ipFilterRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{ipFilterRuleName}", System.Uri.EscapeDataString(ipFilterRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IpFilterRule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IpFilterRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes an IpFilterRule for a Namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='ipFilterRuleName'>
/// The IP Filter Rule name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteIpFilterRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string ipFilterRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (namespaceName != null)
{
if (namespaceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50);
}
if (namespaceName.Length < 6)
{
throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6);
}
}
if (ipFilterRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ipFilterRuleName");
}
if (ipFilterRuleName != null)
{
if (ipFilterRuleName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "ipFilterRuleName", 1);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("ipFilterRuleName", ipFilterRuleName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "DeleteIpFilterRule", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/ipfilterrules/{ipFilterRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{ipFilterRuleName}", System.Uri.EscapeDataString(ipFilterRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets an IpFilterRule for a Namespace by rule name.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='ipFilterRuleName'>
/// The IP Filter Rule name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IpFilterRule>> GetIpFilterRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string ipFilterRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (namespaceName != null)
{
if (namespaceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50);
}
if (namespaceName.Length < 6)
{
throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6);
}
}
if (ipFilterRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ipFilterRuleName");
}
if (ipFilterRuleName != null)
{
if (ipFilterRuleName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "ipFilterRuleName", 1);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("ipFilterRuleName", ipFilterRuleName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetIpFilterRule", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/ipfilterrules/{ipFilterRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{ipFilterRuleName}", System.Uri.EscapeDataString(ipFilterRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IpFilterRule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IpFilterRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of VirtualNetwork rules for a Namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<VirtualNetworkRule>>> ListVirtualNetworkRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (namespaceName != null)
{
if (namespaceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50);
}
if (namespaceName.Length < 6)
{
throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListVirtualNetworkRules", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/virtualnetworkrules").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<VirtualNetworkRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualNetworkRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates an VirtualNetworkRule for a Namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='virtualNetworkRuleName'>
/// The Virtual Network Rule name.
/// </param>
/// <param name='parameters'>
/// The Namespace VirtualNetworkRule.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VirtualNetworkRule>> CreateOrUpdateVirtualNetworkRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string virtualNetworkRuleName, VirtualNetworkRule parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (namespaceName != null)
{
if (namespaceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50);
}
if (namespaceName.Length < 6)
{
throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6);
}
}
if (virtualNetworkRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkRuleName");
}
if (virtualNetworkRuleName != null)
{
if (virtualNetworkRuleName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "virtualNetworkRuleName", 1);
}
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("virtualNetworkRuleName", virtualNetworkRuleName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdateVirtualNetworkRule", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/virtualnetworkrules/{virtualNetworkRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{virtualNetworkRuleName}", System.Uri.EscapeDataString(virtualNetworkRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualNetworkRule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualNetworkRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes an VirtualNetworkRule for a Namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='virtualNetworkRuleName'>
/// The Virtual Network Rule name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteVirtualNetworkRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string virtualNetworkRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (namespaceName != null)
{
if (namespaceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50);
}
if (namespaceName.Length < 6)
{
throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6);
}
}
if (virtualNetworkRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkRuleName");
}
if (virtualNetworkRuleName != null)
{
if (virtualNetworkRuleName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "virtualNetworkRuleName", 1);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("virtualNetworkRuleName", virtualNetworkRuleName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "DeleteVirtualNetworkRule", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/virtualnetworkrules/{virtualNetworkRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{virtualNetworkRuleName}", System.Uri.EscapeDataString(virtualNetworkRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets an VirtualNetworkRule for a Namespace by rule name.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='virtualNetworkRuleName'>
/// The Virtual Network Rule name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VirtualNetworkRule>> GetVirtualNetworkRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string virtualNetworkRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (namespaceName != null)
{
if (namespaceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50);
}
if (namespaceName.Length < 6)
{
throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6);
}
}
if (virtualNetworkRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkRuleName");
}
if (virtualNetworkRuleName != null)
{
if (virtualNetworkRuleName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "virtualNetworkRuleName", 1);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("virtualNetworkRuleName", virtualNetworkRuleName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetVirtualNetworkRule", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/virtualnetworkrules/{virtualNetworkRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{virtualNetworkRuleName}", System.Uri.EscapeDataString(virtualNetworkRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualNetworkRule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualNetworkRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a service namespace. Once created, this namespace's
/// resource manifest is immutable. This operation is idempotent.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639408.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a namespace resource.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<SBNamespace>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, SBNamespace parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201 && (int)_statusCode != 202)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SBNamespace>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SBNamespace>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SBNamespace>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes an existing namespace. This operation also removes all associated
/// resources under the namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639389.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (namespaceName != null)
{
if (namespaceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50);
}
if (namespaceName.Length < 6)
{
throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the available namespaces within the subscription, irrespective of
/// the resource groups.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" />
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SBNamespace>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SBNamespace>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SBNamespace>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the available namespaces within a resource group.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" />
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SBNamespace>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroupNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SBNamespace>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SBNamespace>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of IP Filter rules for a Namespace.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<IpFilterRule>>> ListIpFilterRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListIpFilterRulesNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<IpFilterRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<IpFilterRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of VirtualNetwork rules for a Namespace.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<VirtualNetworkRule>>> ListVirtualNetworkRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListVirtualNetworkRulesNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<VirtualNetworkRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualNetworkRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 46.337859 | 354 | 0.560364 | [
"MIT"
] | hosunmsft/azure-sdk-for-net | src/SDKs/ServiceBus/Management.ServiceBus/Generated/NamespacesOperations.cs | 177,474 | C# |
using System;
using Mirage.SocketLayer;
using NanoSockets;
namespace Mirage.Sockets.Udp
{
// todo Create an Exception in mirage that can be re-used by multiple sockets (makes it easier for user to catch)
public class NanoSocketException : Exception
{
public NanoSocketException(string message) : base(message) { }
}
public sealed class NanoSocket : ISocket, IDisposable
{
Socket socket;
NanoEndPoint receiveEndPoint;
readonly int bufferSize;
bool needsDisposing;
public NanoSocket(UdpSocketFactory factory)
{
bufferSize = factory.BufferSize;
}
~NanoSocket()
{
Dispose();
}
void InitSocket()
{
socket = UDP.Create(bufferSize, bufferSize);
UDP.SetDontFragment(socket);
UDP.SetNonBlocking(socket);
needsDisposing = true;
}
public void Bind(IEndPoint endPoint)
{
receiveEndPoint = (NanoEndPoint)endPoint;
InitSocket();
int result = UDP.Bind(socket, ref receiveEndPoint.address);
if (result != 0)
{
throw new NanoSocketException("Socket Bind failed: address or port might already be in use");
}
}
public void Dispose()
{
if (!needsDisposing) return;
UDP.Destroy(ref socket);
needsDisposing = false;
}
public void Close()
{
Dispose();
}
public void Connect(IEndPoint endPoint)
{
receiveEndPoint = (NanoEndPoint)endPoint;
InitSocket();
int result = UDP.Connect(socket, ref receiveEndPoint.address);
if (result != 0)
{
throw new NanoSocketException("Socket Connect failed");
}
}
public bool Poll()
{
return UDP.Poll(socket, 0) > 0;
}
public int Receive(byte[] buffer, out IEndPoint endPoint)
{
int count = UDP.Receive(socket, ref receiveEndPoint.address, buffer, buffer.Length);
endPoint = receiveEndPoint;
return count;
}
public void Send(IEndPoint endPoint, byte[] packet, int length)
{
var nanoEndPoint = (NanoEndPoint)endPoint;
UDP.Send(socket, ref nanoEndPoint.address, packet, length);
}
}
}
| 26.666667 | 117 | 0.554032 | [
"MIT"
] | GTextreme169/Mirage | Assets/Mirage/Runtime/Sockets/Udp/NanoSocket.cs | 2,480 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataCenter.Data
{
public class DataContainer
{
// Products
public List<Product> Products { get; set; }
// Data
public SortedDictionary<DateTime, Event> Events { get; set; }
public DataContainer()
{
Products = new List<Product>();
Events = new SortedDictionary<DateTime, Event>();
}
public Event GetEvent(DateTime date)
{
// Get event for current date or insert new one
Event e = null;
if (!Events.TryGetValue(date, out e))
{
// Create new event
e = new Event(Products);
// Add event to dicionary
Events.Add(date, e);
}
return e;
}
private DateTime? MinimalDate = null;
public DateTime GetMinimalDate()
{
if (MinimalDate != null)
return (DateTime)MinimalDate;
DateTime minimal = Events.Keys.ElementAt(0);
foreach (DateTime date in Events.Keys)
{
// Has event some price?
foreach (_ProductData pd in Events[date].ProductsDatas.Values)
if (!double.IsNaN(pd.Price))
{
MinimalDate = date;
return date;
}
}
return new DateTime(0);
}
}
}
| 26.868852 | 79 | 0.47834 | [
"MIT"
] | mastercs999/fn-trading | src/DataCenter/Data/DataContainer.cs | 1,641 | C# |
namespace RestKit
{
public class XmlConventions
{
public static readonly XmlConventions Default = new XmlConventions()
{
AttributeContainerName = "Attributes",
ElementValueName = "Value",
Casing = CasingConvention.AsIs
};
public string AttributeContainerName { get; set; }
public string ElementValueName { get; set; }
public CasingConvention Casing { get; set; }
}
}
| 24.578947 | 76 | 0.61242 | [
"MIT"
] | bkjuice/RestKit | src/RestKit/XmlConventions.cs | 469 | C# |
using System;
// using System.Collections;
using System.Collections.Generic;
public class Person {
public string Name { get; set; }
public override string ToString() { return Name; }
}
public class People : IEnumerable<Person> {
public List<Person> list { get; set; }
public IEnumerable<Person> GetEnumerator() { return list.GetEnumerator(); }
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
}
class MainClass {
public static void Main (string[] args) {
People people = new People();
people.list = new List<Person>() {
new Person() { Name="ctkim"},
new Person() { Name="Steve"},
new Person() { Name="Brown"},
new Person() { Name="Won"},
new Person() { Name="jj"}
};
foreach(var person in people)
Console.WriteLine(person.Name);
}
} | 26.516129 | 77 | 0.650852 | [
"MIT"
] | Neto1235678/CSharp2019 | IEnumerable-2-Hot-to-make-froeachble/main.cs | 822 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** 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.AzureNextGen.DataFactory.Outputs
{
[OutputType]
public sealed class GreenplumTableDatasetResponse
{
/// <summary>
/// List of tags that can be used for describing the Dataset.
/// </summary>
public readonly ImmutableArray<object> Annotations;
/// <summary>
/// Dataset description.
/// </summary>
public readonly string? Description;
/// <summary>
/// The folder that this Dataset is in. If not specified, Dataset will appear at the root level.
/// </summary>
public readonly Outputs.DatasetResponseFolder? Folder;
/// <summary>
/// Linked service reference.
/// </summary>
public readonly Outputs.LinkedServiceReferenceResponse LinkedServiceName;
/// <summary>
/// Parameters for dataset.
/// </summary>
public readonly ImmutableDictionary<string, Outputs.ParameterSpecificationResponse>? Parameters;
/// <summary>
/// Columns that define the physical type schema of the dataset. Type: array (or Expression with resultType array), itemType: DatasetSchemaDataElement.
/// </summary>
public readonly object? Schema;
/// <summary>
/// Columns that define the structure of the dataset. Type: array (or Expression with resultType array), itemType: DatasetDataElement.
/// </summary>
public readonly object? Structure;
/// <summary>
/// The table name of Greenplum. Type: string (or Expression with resultType string).
/// </summary>
public readonly object? Table;
/// <summary>
/// This property will be retired. Please consider using schema + table properties instead.
/// </summary>
public readonly object? TableName;
/// <summary>
/// Type of dataset.
/// Expected value is 'GreenplumTable'.
/// </summary>
public readonly string Type;
[OutputConstructor]
private GreenplumTableDatasetResponse(
ImmutableArray<object> annotations,
string? description,
Outputs.DatasetResponseFolder? folder,
Outputs.LinkedServiceReferenceResponse linkedServiceName,
ImmutableDictionary<string, Outputs.ParameterSpecificationResponse>? parameters,
object? schema,
object? structure,
object? table,
object? tableName,
string type)
{
Annotations = annotations;
Description = description;
Folder = folder;
LinkedServiceName = linkedServiceName;
Parameters = parameters;
Schema = schema;
Structure = structure;
Table = table;
TableName = tableName;
Type = type;
}
}
}
| 34.27957 | 159 | 0.61606 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/DataFactory/Outputs/GreenplumTableDatasetResponse.cs | 3,188 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Minedraft.Entities.Providers
{
public class SolarProvider : Provider
{
public SolarProvider(int id, double energyOutput)
: base(id, energyOutput)
{
this.Durability -= 500;
}
}
}
| 20.388889 | 58 | 0.651226 | [
"MIT"
] | bobo4aces/04.SoftUni-CSharpFundamentals | 03. CSharp OOP Advanced - 08. Exam Preparation/2017.09.07/Structure_Skeleton/Entities/Providers/SolarProvider.cs | 369 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace FileHelpers
{
/// <summary>
/// Engine used to create diff files based on the
/// <see cref="IComparable{T}"/> interface.
/// </summary>
/// <typeparam name="T">The record type.</typeparam>
[DebuggerDisplay(
"FileDiffEngine for type: {RecordType.Name}. ErrorMode: {ErrorManager.ErrorMode.ToString()}. Encoding: {Encoding.EncodingName}"
)]
public sealed class FileDiffEngine<T> : EngineBase
where T : class, IComparable<T>
{
/// <summary>
/// Creates a new <see cref="FileDiffEngine{T}"/>
/// </summary>
public FileDiffEngine()
: base(typeof (T)) {}
/// <summary>Returns the records in newFile that not are in the sourceFile</summary>
/// <param name="sourceFile">The file with the old records.</param>
/// <param name="newFile">The file with the new records.</param>
/// <returns>The records in newFile that not are in the sourceFile</returns>
public T[] OnlyNewRecords(string sourceFile, string newFile)
{
FileHelperEngine<T> engine = CreateEngineAndClearErrors();
var olds = engine.ReadFile(sourceFile);
ErrorManager.AddErrors(engine.ErrorManager);
var currents = engine.ReadFile(newFile);
ErrorManager.AddErrors(engine.ErrorManager);
var news = new List<T>();
ApplyDiffOnlyIn1(currents, olds, news);
return news.ToArray();
}
/// <summary>Returns the records in newFile that not are in the sourceFile</summary>
/// <param name="sourceFile">The file with the old records.</param>
/// <param name="newFile">The file with the new records.</param>
/// <returns>The records in newFile that not are in the sourceFile</returns>
public T[] OnlyMissingRecords(string sourceFile, string newFile)
{
FileHelperEngine<T> engine = CreateEngineAndClearErrors();
T[] olds = engine.ReadFile(sourceFile);
ErrorManager.AddErrors(engine.ErrorManager);
T[] currents = engine.ReadFile(newFile);
ErrorManager.AddErrors(engine.ErrorManager);
var news = new List<T>();
ApplyDiffOnlyIn1(olds, currents, news);
return news.ToArray();
}
private FileHelperEngine<T> CreateEngineAndClearErrors()
{
var engine = new FileHelperEngine<T> {
Encoding = Encoding
};
ErrorManager.ClearErrors();
engine.ErrorManager.ErrorMode = ErrorManager.ErrorMode;
return engine;
}
/// <summary>
/// Returns the duplicated records in both files.
/// </summary>
/// <param name="file1">A file with records.</param>
/// <param name="file2">A file with records.</param>
/// <returns>The records that appear in both files.</returns>
public T[] OnlyDuplicatedRecords(string file1, string file2)
{
FileHelperEngine<T> engine = CreateEngineAndClearErrors();
T[] olds = engine.ReadFile(file1);
ErrorManager.AddErrors(engine.ErrorManager);
T[] currents = engine.ReadFile(file2);
ErrorManager.AddErrors(engine.ErrorManager);
var news = new List<T>();
ApplyDiffInBoth(currents, olds, news);
return news.ToArray();
}
#region " ApplyDiff "
private static void ApplyDiffInBoth(T[] col1, T[] col2, List<T> arr)
{
ApplyDiff(col1, col2, arr, true);
}
private static void ApplyDiffOnlyIn1(T[] col1, T[] col2, List<T> arr)
{
ApplyDiff(col1, col2, arr, false);
}
private static void ApplyDiff(T[] col1, T[] col2, List<T> arr, bool addIfIn1)
{
for (int i = 0; i < col1.Length; i++) {
bool isNew = false;
//OPT: aca podemos hacer algo asi que para cada nuevo
// que encuentra no empieze en j = i sino en j = i - nuevos =)
// Otra idea de guille es agrear un window y usar el Max de las dos
T current = col1[i];
for (int j = i; j < col2.Length; j++) {
if (current.CompareTo(col2[j]) == 0) {
isNew = true;
break;
}
}
if (isNew == false) {
for (int j = 0; j < Math.Min(i, col2.Length); j++) {
if (current.CompareTo(col2[j]) == 0) {
isNew = true;
break;
}
}
}
if (isNew == addIfIn1)
arr.Add(current);
}
}
#endregion
/// <summary>
/// Returns the NON duplicated records in both files.
/// </summary>
/// <param name="file1">A file with record.</param>
/// <param name="file2">A file with record.</param>
/// <returns>The records that NOT appear in both files.</returns>
public T[] OnlyNoDuplicatedRecords(string file1, string file2)
{
FileHelperEngine<T> engine = CreateEngineAndClearErrors();
T[] olds = engine.ReadFile(file1);
ErrorManager.AddErrors(engine.ErrorManager);
T[] currents = engine.ReadFile(file2);
ErrorManager.AddErrors(engine.ErrorManager);
var news = new List<T>();
ApplyDiffOnlyIn1(currents, olds, news);
ApplyDiffOnlyIn1(olds, currents, news);
return news.ToArray();
}
/// <summary>
/// Read the source file, the new File, get the records and write
/// them to a destination file. (record not in first file but in
/// second will be written to the third)
/// </summary>
/// <param name="sourceFile">The file with the source records.</param>
/// <param name="newFile">The file with the new records.</param>
/// <param name="destFile">The destination file.</param>
/// <returns>The new records on the new file.</returns>
public T[] WriteNewRecords(string sourceFile, string newFile, string destFile)
{
FileHelperEngine<T> engine = CreateEngineAndClearErrors();
T[] res = OnlyNewRecords(sourceFile, newFile);
engine.WriteFile(destFile, res);
ErrorManager.AddErrors(engine.ErrorManager);
return res;
}
}
} | 37.026738 | 136 | 0.539861 | [
"MIT"
] | 3dsoft/FileHelpers | FileHelpers/Engines/FileDiffEngine.cs | 6,924 | C# |
// ReSharper disable CheckNamespace
#region
using LibSharpRetro;
#endregion
namespace DamageCore;
public partial class Interpreter {
public bool Interpret(Span<byte> insnBytes, ref ushort pc) {
unchecked {
/* LD-rd-rs */
if((insnBytes[0] & 0xC0) == 0x40) {
var rd = (byte) ((byte) (insnBytes[0] >> 3) & 0x7);
var rs = (byte) ((byte) (insnBytes[0] >> 0) & 0x7);
if(!((rd != 0x6) & (rs != 0x6)))
goto insn_1;
pc += 1;
State.Registers[rd] =
rs switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
AddCycles(0x1);
return true;
}
insn_1:
/* LD-rd-imm8 */
if((insnBytes[0] & 0xC7) == 0x6) {
var rd = (byte) ((byte) (insnBytes[0] >> 3) & 0x7);
var imm = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
if(!(rd != 0x6))
goto insn_2;
pc += 2;
State.Registers[rd] = imm;
AddCycles(0x2);
return true;
}
insn_2:
/* LD-rd-HL */
if((insnBytes[0] & 0xC7) == 0x46) {
var rd = (byte) ((byte) (insnBytes[0] >> 3) & 0x7);
if(!(rd != 0x6))
goto insn_3;
pc += 1;
State.Registers[rd] =
ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]));
AddCycles(0x2);
return true;
}
insn_3:
/* LD-HL-rs */
if((insnBytes[0] & 0xF8) == 0x70) {
var rs = (byte) ((byte) (insnBytes[0] >> 0) & 0x7);
if(!(rs != 0x6))
goto insn_4;
pc += 1;
WriteMemory((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]),
rs switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] });
AddCycles(0x2);
return true;
}
insn_4:
/* LD-HL-imm8 */
if((insnBytes[0] & 0xFF) == 0x36) {
var imm = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
pc += 2;
WriteMemory((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]), imm);
AddCycles(0x3);
return true;
}
/* LD-A-BC */
if((insnBytes[0] & 0xFF) == 0xA) {
pc += 1;
State.Registers[0x7] =
ReadMemory<byte>((ushort) ((State.Registers[0b000] << 8) | State.Registers[0b001]));
AddCycles(0x2);
return true;
}
/* LD-A-DE */
if((insnBytes[0] & 0xFF) == 0x1A) {
pc += 1;
State.Registers[0x7] =
ReadMemory<byte>((ushort) ((State.Registers[0b010] << 8) | State.Registers[0b011]));
AddCycles(0x2);
return true;
}
/* LD-BC-A */
if((insnBytes[0] & 0xFF) == 0x2) {
pc += 1;
WriteMemory((ushort) ((State.Registers[0b000] << 8) | State.Registers[0b001]),
0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] });
AddCycles(0x2);
return true;
}
/* LD-DE-A */
if((insnBytes[0] & 0xFF) == 0x12) {
pc += 1;
WriteMemory((ushort) ((State.Registers[0b010] << 8) | State.Registers[0b011]),
0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] });
AddCycles(0x2);
return true;
}
/* LD-A-imm16 */
if((insnBytes[0] & 0xFF) == 0xFA) {
var lsb = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
var msb = (byte) ((byte) (insnBytes[2] >> 0) & 0xFF);
var addr = (ushort) ((ushort) (msb << 0x8) | lsb);
pc += 3;
State.Registers[0x7] = ReadMemory<byte>(addr);
AddCycles(0x4);
return true;
}
/* LD-imm16-A */
if((insnBytes[0] & 0xFF) == 0xEA) {
var lsb = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
var msb = (byte) ((byte) (insnBytes[2] >> 0) & 0xFF);
var addr = (ushort) ((ushort) (msb << 0x8) | lsb);
pc += 3;
WriteMemory(addr,
0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] });
AddCycles(0x4);
return true;
}
/* LDH-A-C */
if((insnBytes[0] & 0xFF) == 0xF2) {
pc += 1;
State.Registers[0x7] = ReadMemory<byte>((ushort) (0xFF00 | 0x1 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
}));
AddCycles(0x2);
return true;
}
/* LDH-C-A */
if((insnBytes[0] & 0xFF) == 0xE2) {
pc += 1;
WriteMemory(
(ushort) (0xFF00 | 0x1 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
}), 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] });
AddCycles(0x2);
return true;
}
/* LDH-A-imm8 */
if((insnBytes[0] & 0xFF) == 0xF0) {
var imm = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
var addr = (ushort) (0xFF00 | imm);
pc += 2;
State.Registers[0x7] = ReadMemory<byte>(addr);
AddCycles(0x3);
return true;
}
/* LDH-imm8-A */
if((insnBytes[0] & 0xFF) == 0xE0) {
var imm = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
var addr = (ushort) (0xFF00 | imm);
pc += 2;
WriteMemory(addr,
0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] });
AddCycles(0x3);
return true;
}
/* LD-A-HL- */
if((insnBytes[0] & 0xFF) == 0x3A) {
pc += 1;
var hl = (ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]);
State.Registers[0x7] = ReadMemory<byte>(hl);
var temp_36 = (ushort) (hl - 0x1);
State.Registers[0b100] = (byte) (temp_36 >> 8);
State.Registers[0b101] = (byte) (temp_36 & 0xFF);
AddCycles(0x2);
return true;
}
/* LD-HL--A */
if((insnBytes[0] & 0xFF) == 0x32) {
pc += 1;
var hl = (ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]);
WriteMemory(hl, 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] });
var temp_37 = (ushort) (hl - 0x1);
State.Registers[0b100] = (byte) (temp_37 >> 8);
State.Registers[0b101] = (byte) (temp_37 & 0xFF);
AddCycles(0x2);
return true;
}
/* LD-A-HL+ */
if((insnBytes[0] & 0xFF) == 0x2A) {
pc += 1;
var hl = (ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]);
State.Registers[0x7] = ReadMemory<byte>(hl);
var temp_38 = (ushort) (hl + 0x1);
State.Registers[0b100] = (byte) (temp_38 >> 8);
State.Registers[0b101] = (byte) (temp_38 & 0xFF);
AddCycles(0x2);
return true;
}
/* LD-HL+-A */
if((insnBytes[0] & 0xFF) == 0x22) {
pc += 1;
var hl = (ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]);
WriteMemory(hl, 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] });
var temp_39 = (ushort) (hl + 0x1);
State.Registers[0b100] = (byte) (temp_39 >> 8);
State.Registers[0b101] = (byte) (temp_39 & 0xFF);
AddCycles(0x2);
return true;
}
/* LD-rr-imm16 */
if((insnBytes[0] & 0xCF) == 0x1) {
var r = (byte) ((byte) (insnBytes[0] >> 4) & 0x3);
var lsb = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
var msb = (byte) ((byte) (insnBytes[2] >> 0) & 0xFF);
var imm = (ushort) ((ushort) (msb << 0x8) | lsb);
pc += 3;
switch(r) {
case 0x0: {
var temp_40 = imm;
State.Registers[0b000] = (byte) (temp_40 >> 8);
State.Registers[0b001] = (byte) (temp_40 & 0xFF);
break;
}
case 0x1: {
var temp_41 = imm;
State.Registers[0b010] = (byte) (temp_41 >> 8);
State.Registers[0b011] = (byte) (temp_41 & 0xFF);
break;
}
case 0x2: {
var temp_42 = imm;
State.Registers[0b100] = (byte) (temp_42 >> 8);
State.Registers[0b101] = (byte) (temp_42 & 0xFF);
break;
}
default: {
State.SP = imm;
break;
}
}
AddCycles(0x3);
return true;
}
/* LD-imm16-SP */
if((insnBytes[0] & 0xFF) == 0x8) {
var lsb = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
var msb = (byte) ((byte) (insnBytes[2] >> 0) & 0xFF);
var addr = (ushort) ((ushort) (msb << 0x8) | lsb);
pc += 3;
WriteMemory(addr, State.SP);
AddCycles(0x5);
return true;
}
/* LD-SP-HL */
if((insnBytes[0] & 0xFF) == 0xF9) {
pc += 1;
State.SP = (ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]);
AddCycles(0x2);
return true;
}
/* PUSH-rr */
if((insnBytes[0] & 0xCF) == 0xC5) {
var r = (byte) ((byte) (insnBytes[0] >> 4) & 0x3);
pc += 1;
var sp = (ushort) (State.SP - 0x2);
State.SP = sp;
WriteMemory(sp,
r switch {
0x0 => (ushort) ((State.Registers[0b000] << 8) | State.Registers[0b001]),
0x1 => (ushort) ((State.Registers[0b010] << 8) | State.Registers[0b011]),
0x2 => (ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]),
_ => (ushort) ((State.Registers[0b111] << 8) | State.Flags),
});
AddCycles(0x4);
return true;
}
/* POP-rr */
if((insnBytes[0] & 0xCF) == 0xC1) {
var r = (byte) ((byte) (insnBytes[0] >> 4) & 0x3);
pc += 1;
var sp = State.SP;
var v = ReadMemory<ushort>(sp);
switch(r) {
case 0x0: {
var temp_44 = v;
State.Registers[0b000] = (byte) (temp_44 >> 8);
State.Registers[0b001] = (byte) (temp_44 & 0xFF);
break;
}
case 0x1: {
var temp_45 = v;
State.Registers[0b010] = (byte) (temp_45 >> 8);
State.Registers[0b011] = (byte) (temp_45 & 0xFF);
break;
}
case 0x2: {
var temp_46 = v;
State.Registers[0b100] = (byte) (temp_46 >> 8);
State.Registers[0b101] = (byte) (temp_46 & 0xFF);
break;
}
default: {
var temp_47 = v;
State.Registers[0b111] = (byte) (temp_47 >> 8);
State.Flags = (byte) (temp_47 & 0xF0);
break;
}
}
State.SP = (ushort) (sp + 0x2);
AddCycles(0x4);
return true;
}
/* JP-nn */
if((insnBytes[0] & 0xFF) == 0xC3) {
var lsb = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
var msb = (byte) ((byte) (insnBytes[2] >> 0) & 0xFF);
var addr = (ushort) ((ushort) (msb << 0x8) | lsb);
pc += 3;
Branch(addr);
AddCycles(0x4);
return true;
}
/* JP-HL */
if((insnBytes[0] & 0xFF) == 0xE9) {
pc += 1;
Branch((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]));
AddCycles(0x1);
return true;
}
/* JP-cc-imm16 */
if((insnBytes[0] & 0xE7) == 0xC2) {
var cc = (byte) ((byte) (insnBytes[0] >> 3) & 0x3);
var lsb = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
var msb = (byte) ((byte) (insnBytes[2] >> 0) & 0xFF);
var addr = (ushort) ((ushort) (msb << 0x8) | lsb);
pc += 3;
if((byte) (cc >> 0x1) switch {
0x0 => (byte) (State.Flags >> 0x7) == (byte) (cc & 0x1),
_ => (byte) ((byte) (State.Flags >> 0x4) &
0x1) ==
(byte) (cc & 0x1),
})
Branch(addr);
else
Branch(pc);
AddCycles((byte) (cc >> 0x1) switch {
0x0 => (byte) (State.Flags >> 0x7) == (byte) (cc & 0x1),
_ => (byte) ((byte) (State.Flags >> 0x4) &
0x1) ==
(byte) (cc & 0x1),
}
? (byte) 0x4
: (byte) 0x3);
return true;
}
/* JR-simm8 */
if((insnBytes[0] & 0xFF) == 0x18) {
var e = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
var offset = (sbyte) e;
pc += 2;
Branch((ushort) (pc + (ushort) offset));
AddCycles(0x3);
return true;
}
/* JR-cc-simm8 */
if((insnBytes[0] & 0xE7) == 0x20) {
var cc = (byte) ((byte) (insnBytes[0] >> 3) & 0x3);
var e = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
var offset = (sbyte) e;
pc += 2;
if((byte) (cc >> 0x1) switch {
0x0 => (byte) (State.Flags >> 0x7) == (byte) (cc & 0x1),
_ => (byte) ((byte) (State.Flags >> 0x4) &
0x1) ==
(byte) (cc & 0x1),
})
Branch((ushort) (pc + (ushort) offset));
else
Branch(pc);
AddCycles((byte) (cc >> 0x1) switch {
0x0 => (byte) (State.Flags >> 0x7) == (byte) (cc & 0x1),
_ => (byte) ((byte) (State.Flags >> 0x4) &
0x1) ==
(byte) (cc & 0x1),
}
? (byte) 0x3
: (byte) 0x2);
return true;
}
/* CALL-imm16 */
if((insnBytes[0] & 0xFF) == 0xCD) {
var lsb = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
var msb = (byte) ((byte) (insnBytes[2] >> 0) & 0xFF);
var addr = (ushort) ((ushort) (msb << 0x8) | lsb);
pc += 3;
var sp = (ushort) (State.SP - 0x2);
State.SP = sp;
WriteMemory(sp, pc);
Branch(addr);
AddCycles(0x6);
return true;
}
/* CALL-cc-imm16 */
if((insnBytes[0] & 0xE7) == 0xC4) {
var cc = (byte) ((byte) (insnBytes[0] >> 3) & 0x3);
var lsb = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
var msb = (byte) ((byte) (insnBytes[2] >> 0) & 0xFF);
var addr = (ushort) ((ushort) (msb << 0x8) | lsb);
pc += 3;
if((byte) (cc >> 0x1) switch {
0x0 => (byte) (State.Flags >> 0x7) == (byte) (cc & 0x1),
_ => (byte) ((byte) (State.Flags >> 0x4) &
0x1) ==
(byte) (cc & 0x1),
}) {
var sp = (ushort) (State.SP - 0x2);
State.SP = sp;
WriteMemory(sp, pc);
Branch(addr);
}
else {
Branch(pc);
}
AddCycles((byte) (cc >> 0x1) switch {
0x0 => (byte) (State.Flags >> 0x7) == (byte) (cc & 0x1),
_ => (byte) ((byte) (State.Flags >> 0x4) &
0x1) ==
(byte) (cc & 0x1),
}
? (byte) 0x6
: (byte) 0x3);
return true;
}
/* RET */
if((insnBytes[0] & 0xFF) == 0xC9) {
pc += 1;
var sp = State.SP;
var ra = ReadMemory<ushort>(sp);
State.SP = (ushort) (sp + 0x2);
Branch(ra);
AddCycles(0x4);
return true;
}
/* RET-cc */
if((insnBytes[0] & 0xE7) == 0xC0) {
var cc = (byte) ((byte) (insnBytes[0] >> 3) & 0x3);
pc += 1;
if((byte) (cc >> 0x1) switch {
0x0 => (byte) (State.Flags >> 0x7) == (byte) (cc & 0x1),
_ => (byte) ((byte) (State.Flags >> 0x4) &
0x1) ==
(byte) (cc & 0x1),
}) {
var sp = State.SP;
var ra = ReadMemory<ushort>(sp);
State.SP = (ushort) (sp + 0x2);
Branch(ra);
}
else {
Branch(pc);
}
AddCycles((byte) (cc >> 0x1) switch {
0x0 => (byte) (State.Flags >> 0x7) == (byte) (cc & 0x1),
_ => (byte) ((byte) (State.Flags >> 0x4) &
0x1) ==
(byte) (cc & 0x1),
}
? (byte) 0x5
: (byte) 0x2);
return true;
}
/* RETI */
if((insnBytes[0] & 0xFF) == 0xD9) {
pc += 1;
var sp = State.SP;
var ra = ReadMemory<ushort>(sp);
State.SP = (ushort) (sp + 0x2);
State.InterruptsEnabled = true;
Branch(ra);
AddCycles(0x4);
return true;
}
/* RST */
if((insnBytes[0] & 0xC7) == 0xC7) {
var n = (byte) ((byte) (insnBytes[0] >> 3) & 0x7);
var addr = (byte) (n << 0x3);
pc += 1;
var sp = (ushort) (State.SP - 0x2);
State.SP = sp;
WriteMemory(sp, pc);
Branch(addr);
AddCycles(0x4);
return true;
}
/* DI */
if((insnBytes[0] & 0xFF) == 0xF3) {
pc += 1;
State.InterruptsEnabled = false;
State.InterruptsEnableScheduled = false;
AddCycles(0x1);
return true;
}
/* EI */
if((insnBytes[0] & 0xFF) == 0xFB) {
pc += 1;
State.InterruptsEnableScheduled = true;
AddCycles(0x1);
return true;
}
/* CCF */
if((insnBytes[0] & 0xFF) == 0x3F) {
pc += 1;
var flags = State.Flags;
flags = (byte) (flags & 0x9F);
State.Flags = (byte) ((byte) (flags ^ 0x10) & 0xF0);
AddCycles(0x1);
return true;
}
/* SCF */
if((insnBytes[0] & 0xFF) == 0x37) {
pc += 1;
var flags = State.Flags;
flags = (byte) (flags & 0x8F);
State.Flags = (byte) ((byte) (flags | 0x10) & 0xF0);
AddCycles(0x1);
return true;
}
/* CPL */
if((insnBytes[0] & 0xFF) == 0x2F) {
pc += 1;
State.Flags = (byte) ((byte) (State.Flags | 0x60) & 0xF0);
State.Registers[0x7] = (byte) ~(0x7 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
});
AddCycles(0x1);
return true;
}
/* NOP */
if((insnBytes[0] & 0xFF) == 0x0) {
pc += 1;
AddCycles(0x1);
return true;
}
/* INC */
if((insnBytes[0] & 0xC7) == 0x4) {
var rd = (byte) ((byte) (insnBytes[0] >> 3) & 0x7);
pc += 1;
var lhs = rd == 0x6
? ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]))
: rd switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var result = (byte) (lhs + 0x1);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0x1F) |
(byte) ((byte) (result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(byte) (
(byte)
((byte) ((byte) (lhs &
0xF) +
(0x1 &
0xF)) >
0xF
? 1U
: 0U) << 0x5)) & 0xF0);
if(rd == 0x6)
WriteMemory((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]), result);
else
State.Registers[rd] = result;
AddCycles(rd == 0x6 ? (byte) 0x3 : (byte) 0x1);
return true;
}
/* DEC */
if((insnBytes[0] & 0xC7) == 0x5) {
var rd = (byte) ((byte) (insnBytes[0] >> 3) & 0x7);
pc += 1;
var lhs = rd == 0x6
? ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]))
: rd switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var result = (byte) (lhs - 0x1);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0x1F) |
(byte) ((byte) (result == 0x0 ? 1U : 0U) <<
0x7) |
(0x1 << 0x6) |
(byte) ((byte) ((byte) (lhs &
0xF) < (0x1 & 0xF)
? 1U
: 0U) << 0x5)) & 0xF0);
if(rd == 0x6)
WriteMemory((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]), result);
else
State.Registers[rd] = result;
AddCycles(rd == 0x6 ? (byte) 0x3 : (byte) 0x1);
return true;
}
/* INC-16 */
if((insnBytes[0] & 0xCF) == 0x3) {
var rd = (byte) ((byte) (insnBytes[0] >> 4) & 0x3);
pc += 1;
switch(rd) {
case 0x0: {
var temp_56 = (ushort) (rd switch {
0x0 => (ushort) ((State.Registers[0b000] << 8) | State.Registers[0b001]),
0x1 => (ushort) ((State.Registers[0b010] << 8) | State.Registers[0b011]),
0x2 => (ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]),
_ => State.SP,
} + 0x1);
State.Registers[0b000] = (byte) (temp_56 >> 8);
State.Registers[0b001] = (byte) (temp_56 & 0xFF);
break;
}
case 0x1: {
var temp_58 = (ushort) (rd switch {
0x0 => (ushort) ((State.Registers[0b000] << 8) | State.Registers[0b001]),
0x1 => (ushort) ((State.Registers[0b010] << 8) | State.Registers[0b011]),
0x2 => (ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]),
_ => State.SP,
} + 0x1);
State.Registers[0b010] = (byte) (temp_58 >> 8);
State.Registers[0b011] = (byte) (temp_58 & 0xFF);
break;
}
case 0x2: {
var temp_60 = (ushort) (rd switch {
0x0 => (ushort) ((State.Registers[0b000] << 8) | State.Registers[0b001]),
0x1 => (ushort) ((State.Registers[0b010] << 8) | State.Registers[0b011]),
0x2 => (ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]),
_ => State.SP,
} + 0x1);
State.Registers[0b100] = (byte) (temp_60 >> 8);
State.Registers[0b101] = (byte) (temp_60 & 0xFF);
break;
}
default: {
State.SP = (ushort) (rd switch {
0x0 => (ushort) ((State.Registers[0b000] << 8) | State.Registers[0b001]),
0x1 => (ushort) ((State.Registers[0b010] << 8) | State.Registers[0b011]),
0x2 => (ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]),
_ => State.SP,
} + 0x1);
break;
}
}
AddCycles(0x2);
return true;
}
/* DEC-16 */
if((insnBytes[0] & 0xCF) == 0xB) {
var rd = (byte) ((byte) (insnBytes[0] >> 4) & 0x3);
pc += 1;
switch(rd) {
case 0x0: {
var temp_63 = (ushort) (rd switch {
0x0 => (ushort) ((State.Registers[0b000] << 8) | State.Registers[0b001]),
0x1 => (ushort) ((State.Registers[0b010] << 8) | State.Registers[0b011]),
0x2 => (ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]),
_ => State.SP,
} - 0x1);
State.Registers[0b000] = (byte) (temp_63 >> 8);
State.Registers[0b001] = (byte) (temp_63 & 0xFF);
break;
}
case 0x1: {
var temp_65 = (ushort) (rd switch {
0x0 => (ushort) ((State.Registers[0b000] << 8) | State.Registers[0b001]),
0x1 => (ushort) ((State.Registers[0b010] << 8) | State.Registers[0b011]),
0x2 => (ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]),
_ => State.SP,
} - 0x1);
State.Registers[0b010] = (byte) (temp_65 >> 8);
State.Registers[0b011] = (byte) (temp_65 & 0xFF);
break;
}
case 0x2: {
var temp_67 = (ushort) (rd switch {
0x0 => (ushort) ((State.Registers[0b000] << 8) | State.Registers[0b001]),
0x1 => (ushort) ((State.Registers[0b010] << 8) | State.Registers[0b011]),
0x2 => (ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]),
_ => State.SP,
} - 0x1);
State.Registers[0b100] = (byte) (temp_67 >> 8);
State.Registers[0b101] = (byte) (temp_67 & 0xFF);
break;
}
default: {
State.SP = (ushort) (rd switch {
0x0 => (ushort) ((State.Registers[0b000] << 8) | State.Registers[0b001]),
0x1 => (ushort) ((State.Registers[0b010] << 8) | State.Registers[0b011]),
0x2 => (ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]),
_ => State.SP,
} - 0x1);
break;
}
}
AddCycles(0x2);
return true;
}
/* ADD-HL */
if((insnBytes[0] & 0xCF) == 0x9) {
var rs = (byte) ((byte) (insnBytes[0] >> 4) & 0x3);
pc += 1;
var lhs = (ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]);
var rhs = rs switch {
0x0 => (ushort) ((State.Registers[0b000] << 8) | State.Registers[0b001]),
0x1 => (ushort) ((State.Registers[0b010] << 8) | State.Registers[0b011]),
0x2 => (ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]),
_ => State.SP,
};
var result = lhs + (uint) rhs;
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0x8F) | (0x0 << 0x6) |
(byte) ((byte) ((ushort) ((ushort) (lhs &
0xFFF) +
(ushort) (rhs &
0xFFF)) >
0xFFF
? 1U
: 0U) << 0x5) |
(byte) ((byte) (result >>
0x10 != 0x0
? 1U
: 0U) << 0x4)) & 0xF0);
var temp_71 = (ushort) result;
State.Registers[0b100] = (byte) (temp_71 >> 8);
State.Registers[0b101] = (byte) (temp_71 & 0xFF);
AddCycles(0x2);
return true;
}
/* ADD-SP-r8 */
if((insnBytes[0] & 0xFF) == 0xE8) {
var rimm = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
var imm = (sbyte) rimm;
pc += 2;
var sp = State.SP;
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) | (0x0 << 0x7) |
(0x0 << 0x6) |
(byte) (
(byte)
((byte)
((byte) ((byte) sp &
0xF) +
(byte) (rimm & 0xF)) >
0xF
? 1U
: 0U) << 0x5) |
(byte) ((byte)
((ushort)
((ushort) (sp &
0xFF) +
rimm) >= 0x100
? 1U
: 0U) << 0x4)) & 0xF0);
State.SP = (ushort) (sp + (uint) imm);
AddCycles(0x4);
return true;
}
/* LD-HL-SP-r8 */
if((insnBytes[0] & 0xFF) == 0xF8) {
var rimm = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
var imm = (sbyte) rimm;
pc += 2;
var sp = State.SP;
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) | (0x0 << 0x7) |
(0x0 << 0x6) |
(byte) (
(byte)
((byte)
((byte) ((byte) sp &
0xF) +
(byte) (rimm & 0xF)) >
0xF
? 1U
: 0U) << 0x5) |
(byte) ((byte)
((ushort)
((ushort) (sp &
0xFF) +
rimm) >= 0x100
? 1U
: 0U) << 0x4)) & 0xF0);
var temp_72 = (ushort) (sp + (uint) imm);
State.Registers[0b100] = (byte) (temp_72 >> 8);
State.Registers[0b101] = (byte) (temp_72 & 0xFF);
AddCycles(0x3);
return true;
}
/* ADD */
if((insnBytes[0] & 0xF8) == 0x80) {
var rs = (byte) ((byte) (insnBytes[0] >> 0) & 0x7);
pc += 1;
var lhs = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var rhs = rs switch {
0x0 => 0x0 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] },
0x1 => 0x1 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] },
0x2 => 0x2 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x3 => 0x3 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x4 => 0x4 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x5 => 0x5 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x6 => ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) |
State.Registers[0b101])),
_ => 0x7 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
};
var result = (ushort) (lhs + rhs);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) ((byte) result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(byte) (
(byte)
((byte) ((byte) (lhs &
0xF) +
(byte) (rhs &
0xF)) >
0xF
? 1U
: 0U) << 0x5) |
(byte) ((byte) (result >=
0x100
? 1U
: 0U) << 0x4)) & 0xF0);
State.Registers[0x7] = (byte) result;
AddCycles(rs == 0x6 ? (byte) 0x2 : (byte) 0x1);
return true;
}
/* ADD-imm8 */
if((insnBytes[0] & 0xFF) == 0xC6) {
var imm = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
pc += 2;
var lhs = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var rhs = imm;
var result = (ushort) (lhs + rhs);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) ((byte) result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(byte) (
(byte)
((byte) ((byte) (lhs &
0xF) +
(byte) (rhs &
0xF)) > 0xF
? 1U
: 0U) << 0x5) |
(byte) ((byte) (result >=
0x100
? 1U
: 0U) << 0x4)) & 0xF0);
State.Registers[0x7] = (byte) result;
AddCycles(0x2);
return true;
}
/* ADC */
if((insnBytes[0] & 0xF8) == 0x88) {
var rs = (byte) ((byte) (insnBytes[0] >> 0) & 0x7);
pc += 1;
var lhs = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var rhs = rs switch {
0x0 => 0x0 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] },
0x1 => 0x1 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] },
0x2 => 0x2 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x3 => 0x3 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x4 => 0x4 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x5 => 0x5 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x6 => ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) |
State.Registers[0b101])),
_ => 0x7 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
};
var carry = (byte) ((byte) (State.Flags >> 0x4) & 0x1);
var result = (ushort) ((ushort) (lhs + rhs) +
carry);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) ((byte) result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(byte) ((byte) ((carry != 0
? (byte) ((byte) (lhs &
0xF) +
(byte) (rhs &
0xF)) >=
0xF
: (byte) ((byte) (lhs &
0xF) +
(byte) (rhs &
0xF)) >
0xF)
? 1U
: 0U) << 0x5) |
(byte) ((byte) (result >=
0x100
? 1U
: 0U) << 0x4)) & 0xF0);
State.Registers[0x7] = (byte) result;
AddCycles(rs == 0x6 ? (byte) 0x2 : (byte) 0x1);
return true;
}
/* ADC-imm8 */
if((insnBytes[0] & 0xFF) == 0xCE) {
var imm = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
pc += 2;
var lhs = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var rhs = imm;
var carry = (byte) ((byte) (State.Flags >> 0x4) & 0x1);
var result = (ushort) ((ushort) (lhs + rhs) +
carry);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) ((byte) result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(byte) ((byte) ((carry != 0
? (byte) ((byte) (lhs &
0xF) +
(byte) (rhs & 0xF)) >=
0xF
: (byte) ((byte) (lhs &
0xF) +
(byte) (rhs & 0xF)) >
0xF)
? 1U
: 0U) << 0x5) |
(byte) ((byte) (result >=
0x100
? 1U
: 0U) << 0x4)) & 0xF0);
State.Registers[0x7] = (byte) result;
AddCycles(0x2);
return true;
}
/* SUB */
if((insnBytes[0] & 0xF8) == 0x90) {
var rs = (byte) ((byte) (insnBytes[0] >> 0) & 0x7);
pc += 1;
var lhs = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var rhs = rs switch {
0x0 => 0x0 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] },
0x1 => 0x1 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] },
0x2 => 0x2 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x3 => 0x3 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x4 => 0x4 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x5 => 0x5 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x6 => ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) |
State.Registers[0b101])),
_ => 0x7 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
};
var result = (ushort) (lhs - rhs);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) ((byte) result == 0x0 ? 1U : 0U) <<
0x7) |
(0x1 << 0x6) |
(byte) ((byte) ((byte) (lhs &
0xF) < (byte) (rhs & 0xF)
? 1U
: 0U) << 0x5) |
(byte) ((byte) (result >=
0x100
? 1U
: 0U) << 0x4)) & 0xF0);
State.Registers[0x7] = (byte) result;
AddCycles(rs == 0x6 ? (byte) 0x2 : (byte) 0x1);
return true;
}
/* SUB-imm8 */
if((insnBytes[0] & 0xFF) == 0xD6) {
var imm = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
pc += 2;
var lhs = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var rhs = imm;
var result = (ushort) (lhs - rhs);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) ((byte) result == 0x0 ? 1U : 0U) <<
0x7) |
(0x1 << 0x6) |
(byte) ((byte) ((byte) (lhs &
0xF) < (byte) (rhs & 0xF)
? 1U
: 0U) << 0x5) |
(byte) ((byte) (result >=
0x100
? 1U
: 0U) << 0x4)) & 0xF0);
State.Registers[0x7] = (byte) result;
AddCycles(0x2);
return true;
}
/* SBC */
if((insnBytes[0] & 0xF8) == 0x98) {
var rs = (byte) ((byte) (insnBytes[0] >> 0) & 0x7);
pc += 1;
var lhs = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var rhs = rs switch {
0x0 => 0x0 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] },
0x1 => 0x1 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] },
0x2 => 0x2 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x3 => 0x3 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x4 => 0x4 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x5 => 0x5 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x6 => ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) |
State.Registers[0b101])),
_ => 0x7 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
};
var carry = (byte) ((byte) (State.Flags >> 0x4) & 0x1);
var result = (ushort) ((ushort) (lhs - rhs) -
carry);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) ((byte) result == 0x0 ? 1U : 0U) <<
0x7) |
(0x1 << 0x6) |
(byte) ((byte) ((carry != 0
? (byte) (lhs & 0xF) <
(byte)
((byte) (rhs &
0xF) +
0x1)
: (byte) (lhs & 0xF) <
(byte) (rhs & 0xF))
? 1U
: 0U) << 0x5) |
(byte) ((byte) (result >=
0x100
? 1U
: 0U) << 0x4)) & 0xF0);
State.Registers[0x7] = (byte) result;
AddCycles(rs == 0x6 ? (byte) 0x2 : (byte) 0x1);
return true;
}
/* SBC-imm8 */
if((insnBytes[0] & 0xFF) == 0xDE) {
var imm = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
pc += 2;
var lhs = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var rhs = imm;
var carry = (byte) ((byte) (State.Flags >> 0x4) & 0x1);
var result = (ushort) ((ushort) (lhs - rhs) -
carry);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) ((byte) result == 0x0 ? 1U : 0U) <<
0x7) |
(0x1 << 0x6) |
(byte) ((byte) ((carry != 0
? (byte) (lhs & 0xF) <
(byte)
((byte) (rhs & 0xF) +
0x1)
: (byte) (lhs & 0xF) <
(byte) (rhs & 0xF))
? 1U
: 0U) << 0x5) |
(byte) ((byte) (result >=
0x100
? 1U
: 0U) << 0x4)) & 0xF0);
State.Registers[0x7] = (byte) result;
AddCycles(0x2);
return true;
}
/* AND */
if((insnBytes[0] & 0xF8) == 0xA0) {
var rs = (byte) ((byte) (insnBytes[0] >> 0) & 0x7);
pc += 1;
var lhs = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var rhs = rs switch {
0x0 => 0x0 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] },
0x1 => 0x1 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] },
0x2 => 0x2 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x3 => 0x3 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x4 => 0x4 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x5 => 0x5 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x6 => ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) |
State.Registers[0b101])),
_ => 0x7 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
};
var result = (byte) (lhs & rhs);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) (result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(0x1 << 0x5) |
(0x0 << 0x4)) & 0xF0);
State.Registers[0x7] = result;
AddCycles(rs == 0x6 ? (byte) 0x2 : (byte) 0x1);
return true;
}
/* AND-imm8 */
if((insnBytes[0] & 0xFF) == 0xE6) {
var imm = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
pc += 2;
var lhs = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var rhs = imm;
var result = (byte) (lhs & rhs);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) (result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(0x1 << 0x5) |
(0x0 << 0x4)) & 0xF0);
State.Registers[0x7] = result;
AddCycles(0x2);
return true;
}
/* XOR */
if((insnBytes[0] & 0xF8) == 0xA8) {
var rs = (byte) ((byte) (insnBytes[0] >> 0) & 0x7);
pc += 1;
var lhs = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var rhs = rs switch {
0x0 => 0x0 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] },
0x1 => 0x1 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] },
0x2 => 0x2 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x3 => 0x3 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x4 => 0x4 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x5 => 0x5 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x6 => ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) |
State.Registers[0b101])),
_ => 0x7 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
};
var result = (byte) (lhs ^ rhs);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) (result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(0x0 << 0x5) |
(0x0 << 0x4)) & 0xF0);
State.Registers[0x7] = result;
AddCycles(rs == 0x6 ? (byte) 0x2 : (byte) 0x1);
return true;
}
/* XOR-imm8 */
if((insnBytes[0] & 0xFF) == 0xEE) {
var imm = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
pc += 2;
var lhs = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var rhs = imm;
var result = (byte) (lhs ^ rhs);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) (result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(0x0 << 0x5) |
(0x0 << 0x4)) & 0xF0);
State.Registers[0x7] = result;
AddCycles(0x2);
return true;
}
/* OR */
if((insnBytes[0] & 0xF8) == 0xB0) {
var rs = (byte) ((byte) (insnBytes[0] >> 0) & 0x7);
pc += 1;
var lhs = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var rhs = rs switch {
0x0 => 0x0 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] },
0x1 => 0x1 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] },
0x2 => 0x2 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x3 => 0x3 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x4 => 0x4 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x5 => 0x5 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x6 => ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) |
State.Registers[0b101])),
_ => 0x7 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
};
var result = (byte) (lhs | rhs);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) (result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(0x0 << 0x5) |
(0x0 << 0x4)) & 0xF0);
State.Registers[0x7] = result;
AddCycles(rs == 0x6 ? (byte) 0x2 : (byte) 0x1);
return true;
}
/* OR-imm8 */
if((insnBytes[0] & 0xFF) == 0xF6) {
var imm = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
pc += 2;
var lhs = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var rhs = imm;
var result = (byte) (lhs | rhs);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) (result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(0x0 << 0x5) |
(0x0 << 0x4)) & 0xF0);
State.Registers[0x7] = result;
AddCycles(0x2);
return true;
}
/* CP */
if((insnBytes[0] & 0xF8) == 0xB8) {
var rs = (byte) ((byte) (insnBytes[0] >> 0) & 0x7);
pc += 1;
var lhs = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var rhs = rs switch {
0x0 => 0x0 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] },
0x1 => 0x1 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] },
0x2 => 0x2 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x3 => 0x3 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x4 => 0x4 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x5 => 0x5 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
0x6 => ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) |
State.Registers[0b101])),
_ => 0x7 switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
},
};
var result = (ushort) (lhs - rhs);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) ((byte) result == 0x0 ? 1U : 0U) <<
0x7) |
(0x1 << 0x6) |
(byte) ((byte) ((byte) (lhs &
0xF) < (byte) (rhs & 0xF)
? 1U
: 0U) << 0x5) |
(byte) ((byte) (result >=
0x100
? 1U
: 0U) << 0x4)) & 0xF0);
AddCycles(rs == 0x6 ? (byte) 0x2 : (byte) 0x1);
return true;
}
/* CP-imm8 */
if((insnBytes[0] & 0xFF) == 0xFE) {
var imm = (byte) ((byte) (insnBytes[1] >> 0) & 0xFF);
pc += 2;
var lhs = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var rhs = imm;
var result = (ushort) (lhs - rhs);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) ((byte) result == 0x0 ? 1U : 0U) <<
0x7) |
(0x1 << 0x6) |
(byte) ((byte) ((byte) (lhs &
0xF) < (byte) (rhs & 0xF)
? 1U
: 0U) << 0x5) |
(byte) ((byte) (result >=
0x100
? 1U
: 0U) << 0x4)) & 0xF0);
AddCycles(0x2);
return true;
}
/* RLCA */
if((insnBytes[0] & 0xFF) == 0x7) {
pc += 1;
var a = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) | (0x0 << 0x7) |
(0x0 << 0x6) |
(0x0 << 0x5) |
(byte) ((byte) (a >> 0x7) <<
0x4)) & 0xF0);
State.Registers[0x7] = (byte) ((byte) (a << 0x1) | (byte) (a >> 0x7));
AddCycles(0x1);
return true;
}
/* RLA */
if((insnBytes[0] & 0xFF) == 0x17) {
pc += 1;
var v = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var result = (byte) ((byte) (v << 0x1) | (byte) ((byte) (State.Flags >> 0x4) & 0x1));
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) | (0x0 << 0x7) |
(0x0 << 0x6) |
(0x0 << 0x5) |
(byte) ((byte) (v >> 0x7) <<
0x4)) & 0xF0);
State.Registers[0x7] = result;
AddCycles(0x1);
return true;
}
/* RLC */
if((insnBytes[0] & 0xFF) == 0xCB && (insnBytes[1] & 0xF8) == 0x0) {
var reg = (byte) ((byte) (insnBytes[1] >> 0) & 0x7);
pc += 2;
var v = reg == 0x6
? ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]))
: reg switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var result = (byte) ((byte) (v << 0x1) | (byte) (v >> 0x7));
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) (result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(0x0 << 0x5) |
(byte) ((byte) (v >> 0x7) <<
0x4)) & 0xF0);
if(reg == 0x6)
WriteMemory((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]), result);
else
State.Registers[reg] = result;
AddCycles(reg == 0x6 ? (byte) 0x4 : (byte) 0x2);
return true;
}
/* RL */
if((insnBytes[0] & 0xFF) == 0xCB && (insnBytes[1] & 0xF8) == 0x10) {
var reg = (byte) ((byte) (insnBytes[1] >> 0) & 0x7);
pc += 2;
var v = reg == 0x6
? ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]))
: reg switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var result = (byte) ((byte) (v << 0x1) | (byte) ((byte) (State.Flags >> 0x4) & 0x1));
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) (result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(0x0 << 0x5) |
(byte) ((byte) (v >> 0x7) <<
0x4)) & 0xF0);
if(reg == 0x6)
WriteMemory((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]), result);
else
State.Registers[reg] = result;
AddCycles(reg == 0x6 ? (byte) 0x4 : (byte) 0x2);
return true;
}
/* RRCA */
if((insnBytes[0] & 0xFF) == 0xF) {
pc += 1;
var a = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) | (0x0 << 0x7) |
(0x0 << 0x6) |
(0x0 << 0x5) |
(byte) ((byte) (a & 0x1) <<
0x4)) & 0xF0);
State.Registers[0x7] = (byte) ((byte) (a >> 0x1) | (byte) (a << 0x7));
AddCycles(0x1);
return true;
}
/* RRC */
if((insnBytes[0] & 0xFF) == 0xCB && (insnBytes[1] & 0xF8) == 0x8) {
var reg = (byte) ((byte) (insnBytes[1] >> 0) & 0x7);
pc += 2;
var v = reg == 0x6
? ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]))
: reg switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var result = (byte) ((byte) (v >> 0x1) | (byte) (v << 0x7));
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) (result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(0x0 << 0x5) |
(byte) ((byte) (v & 0x1) <<
0x4)) & 0xF0);
if(reg == 0x6)
WriteMemory((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]), result);
else
State.Registers[reg] = result;
AddCycles(reg == 0x6 ? (byte) 0x4 : (byte) 0x2);
return true;
}
/* RRA */
if((insnBytes[0] & 0xFF) == 0x1F) {
pc += 1;
var v = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var result = (byte) ((byte) (v >> 0x1) |
(byte) ((byte) ((byte) (State.Flags >> 0x4) & 0x1) << 0x7));
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) | (0x0 << 0x7) |
(0x0 << 0x6) |
(0x0 << 0x5) |
(byte) ((byte) (v & 0x1) <<
0x4)) & 0xF0);
State.Registers[0x7] = result;
AddCycles(0x1);
return true;
}
/* RR */
if((insnBytes[0] & 0xFF) == 0xCB && (insnBytes[1] & 0xF8) == 0x18) {
var reg = (byte) ((byte) (insnBytes[1] >> 0) & 0x7);
pc += 2;
var v = reg == 0x6
? ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]))
: reg switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var result = (byte) ((byte) (v >> 0x1) |
(byte) ((byte) ((byte) (State.Flags >> 0x4) & 0x1) << 0x7));
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) (result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(0x0 << 0x5) |
(byte) ((byte) (v & 0x1) <<
0x4)) & 0xF0);
if(reg == 0x6)
WriteMemory((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]), result);
else
State.Registers[reg] = result;
AddCycles(reg == 0x6 ? (byte) 0x4 : (byte) 0x2);
return true;
}
/* SLA */
if((insnBytes[0] & 0xFF) == 0xCB && (insnBytes[1] & 0xF8) == 0x20) {
var reg = (byte) ((byte) (insnBytes[1] >> 0) & 0x7);
pc += 2;
var v = reg == 0x6
? ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]))
: reg switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var result = (byte) (v << 0x1);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) (result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(0x0 << 0x5) |
(byte) ((byte) (v >> 0x7) <<
0x4)) & 0xF0);
if(reg == 0x6)
WriteMemory((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]), result);
else
State.Registers[reg] = result;
AddCycles(reg == 0x6 ? (byte) 0x4 : (byte) 0x2);
return true;
}
/* SRA */
if((insnBytes[0] & 0xFF) == 0xCB && (insnBytes[1] & 0xF8) == 0x28) {
var reg = (byte) ((byte) (insnBytes[1] >> 0) & 0x7);
pc += 2;
var v = reg == 0x6
? ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]))
: reg switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var result = (byte) ((byte) (v >> 0x1) | (byte) (v & 0x80));
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) (result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(0x0 << 0x5) |
(byte) ((byte) (v & 0x1) <<
0x4)) & 0xF0);
if(reg == 0x6)
WriteMemory((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]), result);
else
State.Registers[reg] = result;
AddCycles(reg == 0x6 ? (byte) 0x4 : (byte) 0x2);
return true;
}
/* SWAP */
if((insnBytes[0] & 0xFF) == 0xCB && (insnBytes[1] & 0xF8) == 0x30) {
var reg = (byte) ((byte) (insnBytes[1] >> 0) & 0x7);
pc += 2;
var v = reg == 0x6
? ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]))
: reg switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var result = (byte) ((byte) (v >> 0x4) | (byte) (v << 0x4));
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) (result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(0x0 << 0x5) |
(0x0 << 0x4)) & 0xF0);
if(reg == 0x6)
WriteMemory((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]), result);
else
State.Registers[reg] = result;
AddCycles(reg == 0x6 ? (byte) 0x4 : (byte) 0x2);
return true;
}
/* SRL */
if((insnBytes[0] & 0xFF) == 0xCB && (insnBytes[1] & 0xF8) == 0x38) {
var reg = (byte) ((byte) (insnBytes[1] >> 0) & 0x7);
pc += 2;
var v = reg == 0x6
? ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]))
: reg switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
var result = (byte) (v >> 0x1);
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) (result == 0x0 ? 1U : 0U) <<
0x7) |
(0x0 << 0x6) |
(0x0 << 0x5) |
(byte) ((byte) (v & 0x1) <<
0x4)) & 0xF0);
if(reg == 0x6)
WriteMemory((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]), result);
else
State.Registers[reg] = result;
AddCycles(reg == 0x6 ? (byte) 0x4 : (byte) 0x2);
return true;
}
/* BIT */
if((insnBytes[0] & 0xFF) == 0xCB && (insnBytes[1] & 0xC0) == 0x40) {
var bit = (byte) ((byte) (insnBytes[1] >> 3) & 0x7);
var reg = (byte) ((byte) (insnBytes[1] >> 0) & 0x7);
pc += 2;
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0x1F) |
(byte) ((byte) ((byte)
((byte) ((reg == 0x6
? ReadMemory<byte>(
(ushort) ((State.Registers[0b100] << 8) |
State.Registers[0b101]))
: reg switch {
0b110 => throw new NotSupportedException(),
{ } i => State.Registers[i],
}) >> bit) & 0x1) ^
0x1) <<
0x7) |
(0x0 << 0x6) |
(0x1 << 0x5)) & 0xF0);
AddCycles(reg == 0x6 ? (byte) 0x4 : (byte) 0x2);
return true;
}
/* RES */
if((insnBytes[0] & 0xFF) == 0xCB && (insnBytes[1] & 0xC0) == 0x80) {
var bit = (byte) ((byte) (insnBytes[1] >> 3) & 0x7);
var reg = (byte) ((byte) (insnBytes[1] >> 0) & 0x7);
pc += 2;
if(reg == 0x6)
WriteMemory((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]),
(byte) ((reg == 0x6
? ReadMemory<byte>(
(ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]))
: reg switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
}) &
(byte) ~(byte) (0x1 << bit)));
else
State.Registers[reg] =
(byte) ((reg == 0x6
? ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) |
State.Registers[0b101]))
: reg switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
}) &
(byte) ~(byte) (0x1 << bit));
AddCycles(reg == 0x6 ? (byte) 0x4 : (byte) 0x2);
return true;
}
/* SET */
if((insnBytes[0] & 0xFF) == 0xCB && (insnBytes[1] & 0xC0) == 0xC0) {
var bit = (byte) ((byte) (insnBytes[1] >> 3) & 0x7);
var reg = (byte) ((byte) (insnBytes[1] >> 0) & 0x7);
pc += 2;
if(reg == 0x6)
WriteMemory((ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]),
(byte) ((reg == 0x6
? ReadMemory<byte>(
(ushort) ((State.Registers[0b100] << 8) | State.Registers[0b101]))
: reg switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
}) |
(byte) (0x1 << bit)));
else
State.Registers[reg] =
(byte) ((reg == 0x6
? ReadMemory<byte>((ushort) ((State.Registers[0b100] << 8) |
State.Registers[0b101]))
: reg switch {
0b110 => throw new NotSupportedException(), { } i => State.Registers[i],
}) |
(byte) (0x1 << bit));
AddCycles(reg == 0x6 ? (byte) 0x4 : (byte) 0x2);
return true;
}
/* DAA */
if((insnBytes[0] & 0xFF) == 0x27) {
pc += 1;
var n = (byte) ((byte) (State.Flags >> 0x6) & 0x1);
var h = (byte) ((byte) (State.Flags >> 0x5) & 0x1);
var c = (byte) ((byte) (State.Flags >> 0x4) & 0x1);
var a = 0x7 switch { 0b110 => throw new NotSupportedException(), { } i => State.Registers[i] };
State.Registers[0x7] = (byte) (a + (byte) (sbyte) (n != 0
? (byte) (sbyte) ((sbyte) (c != 0 ? (byte) -0x60 : (byte) 0x0) +
(sbyte) (h != 0
? (byte) -0x6
: (byte) 0x0))
: (byte) (((byte) (c |
(byte) (a > 0x99 ? 1U : 0U)) != 0
? FunctionalHelpers.Funcify(() => {
c = 0x1;
return (byte) 0x60;
})()
: 0x0) +
((byte) (h |
(byte) ((byte) (a &
0xF) > 0x9
? 1U
: 0U)) != 0
? 0x6
: 0x0))));
State.Flags = (byte) ((byte) ((byte) (State.Flags & 0xF) |
(byte) ((byte) (0x7 switch {
0b110 => throw new NotSupportedException(),
{ } i => State.Registers[i],
} == 0x0
? 1U
: 0U) << 0x7) |
(byte) (n << 0x6) |
(0x0 << 0x5) |
(byte) (c << 0x4)) & 0xF0);
AddCycles(0x1);
return true;
}
/* HALT */
if((insnBytes[0] & 0xFF) == 0x76) {
pc += 1;
Halt();
AddCycles(0x1);
return true;
}
/* STOP */
if((insnBytes[0] & 0xFF) == 0x10) {
pc += 1;
AddCycles(0x1);
return true;
}
return false;
}
}
} | 50.402155 | 120 | 0.317233 | [
"Apache-2.0"
] | daeken/SharpRetro | DamageCore/Generated/Interpreter.cs | 88,859 | C# |
namespace RemoteDebugger
{
partial class SpriteView
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.numPattern = new System.Windows.Forms.NumericUpDown();
this.pictureBox1 = new RemoteDebugger.PictureBoxWithInterpolationMode();
((System.ComponentModel.ISupportInitialize)(this.numPattern)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 15);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(81, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Pattern Number";
//
// numericUpDown1
//
this.numPattern.Location = new System.Drawing.Point(152, 13);
this.numPattern.Name = "numericUpDown1";
this.numPattern.Size = new System.Drawing.Size(120, 20);
this.numPattern.TabIndex = 1;
this.numPattern.Anchor =((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top
| System.Windows.Forms.AnchorStyles.Right)));
//
// pictureBox1
//
this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pictureBox1.Location = new System.Drawing.Point(13, 47);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(259, 202);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.pictureBox1.TabIndex = 2;
this.pictureBox1.TabStop = false;
//
// SpriteView
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 261);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.numPattern);
this.Controls.Add(this.label1);
this.Name = "SpriteView";
this.Text = "SpriteView";
((System.ComponentModel.ISupportInitialize)(this.numPattern)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.NumericUpDown numPattern;
private RemoteDebugger.PictureBoxWithInterpolationMode pictureBox1;
}
} | 42.793478 | 161 | 0.579121 | [
"MIT"
] | Ckirby101/Remote-Debugger | RemoteDebugger/Docks/SpriteView.Designer.cs | 3,939 | C# |
// $Id: StylusModel.cs 990 2006-07-06 00:53:49Z julenka $
using System;
using Microsoft.Ink;
namespace UW.ClassroomPresenter.Model.Stylus {
public abstract class StylusModel : PropertyPublisher {
private readonly Guid m_Id;
protected DrawingAttributes m_DrawingAttributes;
protected StylusModel(Guid id) {
this.m_Id = id;
this.m_DrawingAttributes = new DrawingAttributes();
}
public Guid Id {
get { return this.m_Id; }
}
[Published]
public DrawingAttributes DrawingAttributes {
get { return this.GetPublishedProperty("DrawingAttributes", ref this.m_DrawingAttributes); }
set { this.SetPublishedProperty("DrawingAttributes", ref this.m_DrawingAttributes, value); }
}
}
}
| 31.148148 | 105 | 0.631391 | [
"Apache-2.0"
] | ClassroomPresenter/CP3 | UW.ClassroomPresenter/Model/Stylus/StylusModel.cs | 841 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.4927
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class CMSModules_Groups_Tools_Polls_Polls_New {
/// <summary>
/// PollNew control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMSModules_Polls_Controls_PollNew PollNew;
}
| 31 | 81 | 0.520161 | [
"MIT"
] | BryanSoltis/KenticoMVCWidgetShowcase | CMS/CMSModules/Groups/Tools/Polls/Polls_New.aspx.designer.cs | 746 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace Structr.AspNetCore.Validation
{
[AttributeUsage(AttributeTargets.Property)]
public abstract class ModelAwareValidationAttribute : ValidationAttribute
{
public override string FormatErrorMessage(string name)
{
if (string.IsNullOrEmpty(ErrorMessageResourceName) && string.IsNullOrEmpty(ErrorMessage))
ErrorMessage = DefaultErrorMessage;
return base.FormatErrorMessage(name);
}
public virtual string DefaultErrorMessage
{
get { return "{0} is invalid."; }
}
public abstract bool IsValid(object value, object container);
public virtual string ClientTypeName
{
get { return this.GetType().Name.Replace("Attribute", ""); }
}
public Dictionary<string, object> ClientValidationParameters
{
get { return GetClientValidationParameters().ToDictionary(kv => kv.Key.ToLower(), kv => kv.Value); }
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
bool validate = IsValid(value, validationContext.ObjectInstance);
if (validate)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult(this.ErrorMessage, new[] { validationContext.MemberName });
}
}
protected virtual IEnumerable<KeyValuePair<string, object>> GetClientValidationParameters()
{
return new KeyValuePair<string, object>[0];
}
}
}
| 31.160714 | 112 | 0.629799 | [
"MIT"
] | askalione/Structr | src/Structr.AspNetCore.Validation/ModelAwareValidationAttribute.cs | 1,745 | C# |
namespace test_interface
{
partial class ANNCreate
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button3 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.textBox1 = new System.Windows.Forms.TextBox();
this.button2 = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button3
//
this.button3.Location = new System.Drawing.Point(313, 205);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(162, 31);
this.button3.TabIndex = 36;
this.button3.Text = "打开结果输出位置";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.label1.Location = new System.Drawing.Point(63, 145);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(266, 21);
this.label1.TabIndex = 35;
this.label1.Text = "请先选择一个包含车牌图片的文件夹";
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(67, 103);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(644, 11);
this.progressBar1.TabIndex = 34;
//
// textBox1
//
this.textBox1.Font = new System.Drawing.Font("微软雅黑", 12F);
this.textBox1.Location = new System.Drawing.Point(176, 53);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(418, 29);
this.textBox1.TabIndex = 33;
//
// button2
//
this.button2.Location = new System.Drawing.Point(67, 52);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(111, 31);
this.button2.TabIndex = 32;
this.button2.Text = "选择文件夹";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button1
//
this.button1.Location = new System.Drawing.Point(616, 52);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(95, 31);
this.button1.TabIndex = 31;
this.button1.Text = "生成";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// ANNCreate
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(775, 288);
this.Controls.Add(this.button3);
this.Controls.Add(this.label1);
this.Controls.Add(this.progressBar1);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Name = "ANNCreate";
this.Text = "ANN训练样本自动生成";
this.Load += new System.EventHandler(this.ANNCreate_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button1;
}
} | 40.97541 | 152 | 0.565913 | [
"Apache-2.0"
] | huangweiboy/EasyPR-DLL-CSharp | test_interface/ANNCreate.Designer.cs | 5,095 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** 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.AzureNative.Web.V20201201.Outputs
{
/// <summary>
/// Rules that can be defined for auto-heal.
/// </summary>
[OutputType]
public sealed class AutoHealRulesResponse
{
/// <summary>
/// Actions to be executed when a rule is triggered.
/// </summary>
public readonly Outputs.AutoHealActionsResponse? Actions;
/// <summary>
/// Conditions that describe when to execute the auto-heal actions.
/// </summary>
public readonly Outputs.AutoHealTriggersResponse? Triggers;
[OutputConstructor]
private AutoHealRulesResponse(
Outputs.AutoHealActionsResponse? actions,
Outputs.AutoHealTriggersResponse? triggers)
{
Actions = actions;
Triggers = triggers;
}
}
}
| 29.230769 | 81 | 0.648246 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Web/V20201201/Outputs/AutoHealRulesResponse.cs | 1,140 | C# |
using System;
using System.Collections.Generic;
using System.Text;
public interface IEmployee
{
string Name { get; set; }
int WorkHoursPerWeek { get; }
}
| 16.4 | 33 | 0.713415 | [
"Apache-2.0"
] | KostadinovK/CSharp-OOP | 12-Object-Communication-And-Events/Homework/04-Work-Force/Contracts/IEmployee.cs | 166 | C# |
using System;
using System.Net;
using System.Threading.Tasks;
using DnsClient.Windows;
using Xunit;
namespace DnsClient.Tests
{
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public class NameServerTest
{
#if !NET461
[Fact]
public void NativeDnsServerResolution()
{
var ex = Record.Exception(() => NameServer.ResolveNameServersNative());
Assert.Null(ex);
}
#endif
[Fact]
public void ValidateAnyAddressIPv4()
{
Assert.ThrowsAny<InvalidOperationException>(() => NameServer.ValidateNameServers(new[] { new NameServer(IPAddress.Any) }));
}
[Fact]
public void ValidateAnyAddressIPv6()
{
Assert.ThrowsAny<InvalidOperationException>(() => NameServer.ValidateNameServers(new[] { new NameServer(IPAddress.IPv6Any) }));
}
[Fact]
public void ValidateAnyAddress_LookupClientInit()
{
Assert.ThrowsAny<InvalidOperationException>(() => new LookupClient(IPAddress.Any));
Assert.ThrowsAny<InvalidOperationException>(() => new LookupClient(IPAddress.Any, 33));
Assert.ThrowsAny<InvalidOperationException>(() => new LookupClient(IPAddress.IPv6Any));
Assert.ThrowsAny<InvalidOperationException>(() => new LookupClient(IPAddress.IPv6Any, 555));
}
[Fact]
public void ValidateAnyAddress_LookupClientQuery()
{
var client = new LookupClient(NameServer.Cloudflare);
Assert.ThrowsAny<InvalidOperationException>(() => client.QueryServer(new[] { IPAddress.Any }, "query", QueryType.A));
Assert.ThrowsAny<InvalidOperationException>(() => client.QueryServerReverse(new[] { IPAddress.Any }, IPAddress.Loopback));
}
[Fact]
public async Task ValidateAnyAddress_LookupClientQueryAsync()
{
var client = new LookupClient(NameServer.Cloudflare);
await Assert.ThrowsAnyAsync<InvalidOperationException>(() => client.QueryServerAsync(new[] { IPAddress.Any }, "query", QueryType.A));
await Assert.ThrowsAnyAsync<InvalidOperationException>(() => client.QueryServerReverseAsync(new[] { IPAddress.Any }, IPAddress.Loopback));
}
[Fact]
public void ValidateNameResolutionPolicyDoesntThrowNormally()
{
var ex = Record.Exception(() => NameResolutionPolicy.Resolve());
Assert.Null(ex);
}
}
}
| 35.183099 | 150 | 0.645717 | [
"Apache-2.0"
] | BorisDog/DnsClient.NET | test/DnsClient.Tests/NameServerTest.cs | 2,500 | C# |
/*
* Quickpay API v10
*
* <h2 id=\"authorization\">Authorization</h2> Authorization is done using basic-auth. Authorization can be done with a user or an agreement. <ul> <li>When authorized with a user one is able to edit own settings, create new merchant or request access to existing merchant.</li> <li>When authorized with an agreement one is able to perform anything on the account that agreement gives permissions to.</li> </ul>
*
* OpenAPI spec version: 10.0
* Contact: support@quickpay.net
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using NUnit.Framework;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using IO.Swagger.Api;
using IO.Swagger.Model;
using IO.Swagger.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace IO.Swagger.Test
{
/// <summary>
/// Class for testing AcquirerSettingsCoinify
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the model.
/// </remarks>
[TestFixture]
public class AcquirerSettingsCoinifyTests
{
// TODO uncomment below to declare an instance variable for AcquirerSettingsCoinify
//private AcquirerSettingsCoinify instance;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
// TODO uncomment below to create an instance of AcquirerSettingsCoinify
//instance = new AcquirerSettingsCoinify();
}
/// <summary>
/// Clean up after each test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of AcquirerSettingsCoinify
/// </summary>
[Test]
public void AcquirerSettingsCoinifyInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" AcquirerSettingsCoinify
//Assert.IsInstanceOfType<AcquirerSettingsCoinify> (instance, "variable 'instance' is a AcquirerSettingsCoinify");
}
/// <summary>
/// Test the property 'Active'
/// </summary>
[Test]
public void ActiveTest()
{
// TODO unit test for the property 'Active'
}
/// <summary>
/// Test the property 'ApiKey'
/// </summary>
[Test]
public void ApiKeyTest()
{
// TODO unit test for the property 'ApiKey'
}
/// <summary>
/// Test the property 'ApiSecret'
/// </summary>
[Test]
public void ApiSecretTest()
{
// TODO unit test for the property 'ApiSecret'
}
/// <summary>
/// Test the property 'IpnSecret'
/// </summary>
[Test]
public void IpnSecretTest()
{
// TODO unit test for the property 'IpnSecret'
}
}
}
| 28.72381 | 418 | 0.596154 | [
"MIT"
] | mattgenious/QuickPaySharp | csharp-client-generated/csharp-client/src/IO.Swagger.Test/Model/AcquirerSettingsCoinifyTests.cs | 3,016 | C# |
/*
* Copyright 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 appstream-2016-12-01.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.AppStream.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.AppStream.Model.Internal.MarshallTransformations
{
/// <summary>
/// DescribeUsers Request Marshaller
/// </summary>
public class DescribeUsersRequestMarshaller : IMarshaller<IRequest, DescribeUsersRequest> , 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((DescribeUsersRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(DescribeUsersRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.AppStream");
string target = "PhotonAdminProxyService.DescribeUsers";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-12-01";
request.HttpMethod = "POST";
request.ResourcePath = "/";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetAuthenticationType())
{
context.Writer.WritePropertyName("AuthenticationType");
context.Writer.Write(publicRequest.AuthenticationType);
}
if(publicRequest.IsSetMaxResults())
{
context.Writer.WritePropertyName("MaxResults");
context.Writer.Write(publicRequest.MaxResults);
}
if(publicRequest.IsSetNextToken())
{
context.Writer.WritePropertyName("NextToken");
context.Writer.Write(publicRequest.NextToken);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static DescribeUsersRequestMarshaller _instance = new DescribeUsersRequestMarshaller();
internal static DescribeUsersRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribeUsersRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.444444 | 141 | 0.615867 | [
"Apache-2.0"
] | PureKrome/aws-sdk-net | sdk/src/Services/AppStream/Generated/Model/Internal/MarshallTransformations/DescribeUsersRequestMarshaller.cs | 4,147 | C# |
// <auto-generated>
using KyGunCo.Counterpoint.Sdk.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace KyGunCo.Counterpoint.Sdk.Configuration
{
// USER_ORDER_INFO
public class UserOrderInfoConfiguration : IEntityTypeConfiguration<UserOrderInfo>
{
public void Configure(EntityTypeBuilder<UserOrderInfo> builder)
{
builder.ToView("USER_ORDER_INFO", "dbo");
builder.HasNoKey();
builder.Property(x => x.TktNo).HasColumnName(@"TKT_NO").HasColumnType("varchar(15)").IsRequired().IsUnicode(false).HasMaxLength(15);
builder.Property(x => x.WebOrderNo).HasColumnName(@"WEB_ORDER_NO").HasColumnType("varchar(15)").IsRequired(false).IsUnicode(false).HasMaxLength(15);
builder.Property(x => x.CustNo).HasColumnName(@"CUST_NO").HasColumnType("varchar(15)").IsRequired(false).IsUnicode(false).HasMaxLength(15);
builder.Property(x => x.BillNam).HasColumnName(@"BILL_NAM").HasColumnType("varchar(40)").IsRequired(false).IsUnicode(false).HasMaxLength(40);
builder.Property(x => x.BillPhone).HasColumnName(@"BILL_PHONE").HasColumnType("varchar(25)").IsRequired(false).IsUnicode(false).HasMaxLength(25);
builder.Property(x => x.ShipNam).HasColumnName(@"SHIP_NAM").HasColumnType("varchar(40)").IsRequired(false).IsUnicode(false).HasMaxLength(40);
builder.Property(x => x.ShipPhone).HasColumnName(@"SHIP_PHONE").HasColumnType("varchar(25)").IsRequired(false).IsUnicode(false).HasMaxLength(25);
builder.Property(x => x.DocStat).HasColumnName(@"DOC_STAT").HasColumnType("varchar(1)").IsRequired(false).IsUnicode(false).HasMaxLength(1);
builder.Property(x => x.DocId).HasColumnName(@"DOC_ID").HasColumnType("bigint").IsRequired();
builder.Property(x => x.OrigTktNo).HasColumnName(@"ORIG_TKT_NO").HasColumnType("varchar(15)").IsRequired(false).IsUnicode(false).HasMaxLength(15);
}
}
}
// </auto-generated>
| 63.40625 | 160 | 0.712173 | [
"MIT"
] | kygunco/KyGunCo.Counterpoint | Source/KyGunCo.Counterpoint.Sdk/Configuration/UserOrderInfoConfiguration.cs | 2,029 | C# |
using System;
namespace _06.ReplaceRepeatingChars
{
class Program
{
static void Main(string[] args)
{
string text = Console.ReadLine();
for (int i = 0; i < text.Length - 1; i++)
{
if (text[i] == text[i + 1])
{
text = text.Remove(i, 1);
i--;
}
}
Console.WriteLine(text);
}
}
} | 20.130435 | 53 | 0.38013 | [
"MIT"
] | grekssi/Softuni-Courses | SoftUni/01. .NET Courses/02. Technology Fundamentals - C#/15. Strings and Text Processing/Exercises/06.ReplaceRepeatingChars/06.cs | 465 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 這段程式碼是由工具產生的。
// 執行階段版本:4.0.30319.34209
//
// 對這個檔案所做的變更可能會造成錯誤的行為,而且如果重新產生程式碼,
// 變更將會遺失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace UFO.Properties {
using System;
/// <summary>
/// 用於查詢當地語系化字串等的強類型資源類別。
/// </summary>
// 這個類別是自動產生的,是利用 StronglyTypedResourceBuilder
// 類別透過 ResGen 或 Visual Studio 這類工具。
// 若要加入或移除成員,請編輯您的 .ResX 檔,然後重新執行 ResGen
// (利用 /str 選項),或重建您的 VS 專案。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// 傳回這個類別使用的快取的 ResourceManager 執行個體。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("UFO.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 覆寫目前執行緒的 CurrentUICulture 屬性,對象是所有
/// 使用這個強類型資源類別的資源查閱。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 38.265625 | 169 | 0.587995 | [
"MIT"
] | ryans610/CSharp-UFOGame | UFO/Properties/Resources.Designer.cs | 2,831 | C# |
using Newtonsoft.Json;
namespace Notion.Client
{
public class TableOfContentsBlock : Block, IColumnChildrenBlock, INonColumnBlock
{
public override BlockType Type => BlockType.TableOfContents;
[JsonProperty("table_of_contents")]
public Data TableOfContents { get; set; }
public class Data
{
}
}
}
| 21.235294 | 84 | 0.65651 | [
"MIT"
] | Titaye/notion-sdk-net | Src/Notion.Client/Models/Blocks/TableOfContentsBlock.cs | 363 | C# |
using System;
using Bridge.Html5;
using Philadelphia.Common;
using Philadelphia.Web;
namespace Philadelphia.Demo.Client {
class NavigationProgram : IFlow<HTMLElement> {
private readonly SomeChoicesForm _dataEntry;
private readonly InformationalMessageForm _msg;
public NavigationProgram() {
_dataEntry = new SomeChoicesForm();
_msg = new InformationalMessageForm("", "Outcome display");
}
public void Run(IFormRenderer<HTMLElement> renderer, Action atExit) {
renderer.AddPopup(_dataEntry);
_dataEntry.Ended += async (x, outcome) => {
Logger.Debug(GetType(), "_dataEntry ended with outcome {0}", outcome);
renderer.Remove(x);
switch (outcome) {
case SomeChoicesForm.Outcome.Canceled:
await _msg.Init("You've canceled form");
break;
case SomeChoicesForm.Outcome.FirstChoice:
await _msg.Init("You've picked first choice");
break;
case SomeChoicesForm.Outcome.SecondChoice:
await _msg.Init("You've picked second choice");
break;
default: throw new Exception("unsupported outcome");
}
renderer.AddPopup(_msg);
};
_msg.Ended += (x, unit) => {
Logger.Debug(GetType(), "_msg ended with outcome {0}", unit);
renderer.Remove(x);
atExit();
};
}
}
}
| 32.82 | 86 | 0.532602 | [
"Apache-2.0"
] | todo-it/philadelphia | Philadelphia.Demo.Client/FormsNavigation/NavigationProgram.cs | 1,643 | C# |
using UptimeHippoApi.Data.DataContext;
namespace UptimeHippoApi.Data.DataAccessLayer
{
public abstract class BaseRepository
{
protected UptimeHippoDataContext DataContext;
}
} | 21.888889 | 53 | 0.766497 | [
"MIT"
] | joshuakaluba/UptimeHippoApi | src/UptimeHippoApi.Data/DataAccessLayer/BaseRepository.cs | 199 | C# |
namespace Styr.Windows
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Text = "Form1";
}
#endregion
}
}
| 24.325 | 102 | 0.651593 | [
"MIT"
] | villor/Styr | Styr.Windows/MainForm.Designer.cs | 975 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.